πŸ“– Intend Matrix β€” Catalog Explorer v2.0

βœ… Loaded
322
MATRICES
1,939
CELLS
5,084
RULES
3,767
ANTI-PATTERNS
2,016
CODE HINTS
14
LAYERS
🧠 Matrix 0 β€” Command Cortex (1)🧱 L1 β€” Foundation (30)πŸ“ L2 β€” Language (30)πŸ—„οΈ L3 β€” Data (30)πŸ”„ L4 β€” State (30)βœ… L5 β€” Validation (30)🎨 L6 β€” UI (30)πŸ–±οΈ L7 β€” Interaction (30)🌐 L8 β€” Integration (30)πŸ” L9 β€” Security (30)πŸ› οΈ L10 β€” Build/Ops (30)⭐ Bonus (301–309) (9)🧩 Gap Fill (311–321) (11)πŸ”­ Matrix Ξ© β€” Observer (1)
β–Ό 🧠 Matrix 0 β€” Command Cortex 1 matrices
#0Core Intent Router Matrix6 cells18 rules18 anti6 hints
Serve as the cognitive entry point for the Intend Matrix System β€” routing user intent to the correct matrix layer, detecting composite commands, resolving ambiguity, and initiating system fallback paths when no matrix is available.
intent_type_detectionlayer_routing_strategyambiguity_resolutioncomposite_intent_disassemblyfallback_trigger_logicmulti_matrix_coordination
INTENT_GRAMMAR_PARSING
When a raw user request arrives in natural language
βœ… RULES (3)
Use grammar and semantic pattern matching
Assign domain tags and confidence score
Log parse tree for audit
❌ ANTI-PATTERNS (3)
Keyword-only classification
No parameter extraction
Failure to tag multi-intent phrases
πŸ’» CODE HINTS (1)
parseIntent('Build resilient API gateway') β†’ { intent: 'design', layer: 7, domain: 'integration' }
LAYER_ROUTING_DECISION_TREE
When intent has been classified and tagged
βœ… RULES (3)
Route via decision graph of layers by domain
Support both vertical (depth) and lateral (scope) traversal
Log all route candidates and final decision
❌ ANTI-PATTERNS (3)
Hardcoded layer mappings
Ignoring cross-layer links
No visibility into routing rationale
πŸ’» CODE HINTS (1)
intent β†’ layerGraph.resolve('resilience') β†’ Layer 8
COMPOSITE_INTENT_SPLITTER
When a request implies multiple operations or domains
βœ… RULES (3)
Segment intent into atomic actions
Resolve each sub-intent independently
Track dependency graph between results
❌ ANTI-PATTERNS (3)
Single-matrix routing for multi-intent input
Dropping secondary intent
No context linkage across subtasks
πŸ’» CODE HINTS (1)
'Design, test, and deploy queue system' β†’ 3 sub-intents β†’ matrices 7, 8, 9
AMBIGUITY_RESOLUTION_PROTOCOL
When user intent maps to multiple plausible layers
βœ… RULES (3)
Score candidates by domain, layer, and history
Engage user or AI adjudicator if tie
Cache resolution path for similar future intents
❌ ANTI-PATTERNS (3)
First-match wins without scoring
No memory of past decisions
Looping between options
πŸ’» CODE HINTS (1)
resolveAmbiguity(['layer 3', 'layer 7'], confidenceScores)
MATRIX_FALLBACK_CHAIN_ACTIVATION
When no suitable matrix is found for given intent
βœ… RULES (3)
Trigger fallback policy based on severity
Alert system admin or Omega layer
Suggest temporary heuristic logic if safe
❌ ANTI-PATTERNS (3)
Null return on missing matrix
No escalation path
Silent default logic execution
πŸ’» CODE HINTS (1)
if (!matrixFound) routeTo(999)
MULTI_MATRIX_EXECUTION_COORDINATOR
When resolution spans across several matrices
βœ… RULES (3)
Orchestrate matrix calls via resolver engine
Merge outputs using intent map
Report lineage of all decisions
❌ ANTI-PATTERNS (3)
Isolated matrix calls without coordination
Conflicting outputs with no merger
No trace of resolution graph
πŸ’» CODE HINTS (1)
intentEngine.plan([M14, M21, M41]) β†’ synthesisLayer.output()
πŸ§ͺ VALIDATION
Inject composite and ambiguous intents. Confirm correct routing, splitting, fallback to Omega, and coordination across matrix layers.
β–Ό 🧱 L1 β€” Foundation 30 matrices
#1Execution Model Matrix7 cells16 rules8 anti7 hints
Helps a developer decide how code is executed, retried, isolated, and terminated under different execution and failure conditions.
execution_triggerfailure_typeresource_scopeconcurrency_modeltime_constraint
execution_model_matr_001
When an external request fails transiently, retry safely without blocking.
βœ… RULES (3)
Retry max 3 times with exponential backoff: 100ms, 400ms, 1600ms
Abort if not retryable (4xx except 429)
Per-attempt timeout 5s via AbortController
❌ ANTI-PATTERNS (2)
Retrying indefinitely
Retrying non-idempotent operations
πŸ’» CODE HINTS (1)
await retry(fn, {retries:3, factor:4, minTimeout:100})
execution_model_matr_002
Background job permanent failure β€” stop and surface.
βœ… RULES (2)
Classify as permanent after first occurrence
Persist failure state with job_id
❌ ANTI-PATTERNS (1)
Blindly retrying corrupted data
πŸ’» CODE HINTS (1)
if (isPermanent(err)) markJobFailed(jobId, err.code)
execution_model_matr_003
Event listener exceeds time β€” terminate to protect event loop.
βœ… RULES (2)
Hard timeout 200ms per handler
Cancel downstream on timeout
❌ ANTI-PATTERNS (1)
Unbounded async in event handlers
πŸ’» CODE HINTS (1)
Promise.race([handler(), timeout(200)])
execution_model_matr_004
Scheduled task under resource pressure β€” degrade gracefully.
βœ… RULES (2)
Abort if >80% heap
Reduce batch 50% on warning
❌ ANTI-PATTERNS (1)
Full workload despite low memory
πŸ’» CODE HINTS (1)
if (process.memoryUsage().heapUsed/heapTotal > 0.8) return
execution_model_matr_005
Concurrent user actions on same resource β€” serialize.
βœ… RULES (3)
Mutex per resource_id
Lock TTL 3s
Reject after 100ms wait
❌ ANTI-PATTERNS (1)
Optimistic writes without conflict detection
πŸ’» CODE HINTS (1)
await mutex.runExclusive(async () => { ... })
execution_model_matr_006
Critical dependency missing at startup β€” fail fast.
βœ… RULES (2)
Check all deps before serving
Exit after 10s
❌ ANTI-PATTERNS (1)
Starting with missing dependencies
πŸ’» CODE HINTS (1)
await waitForDependency(db, {timeout:10000})
execution_model_matr_007
Pipeline step fails β€” halt and compensate.
βœ… RULES (2)
Short-circuit on first failure
Emit compensation event
❌ ANTI-PATTERNS (1)
Continuing after failed step
πŸ’» CODE HINTS (1)
if (!result.ok) throw new PipelineError(step)
πŸ§ͺ VALIDATION
Verify retries bounded, timeouts enforced, resources checked, failures compensated.
#2Program Lifecycle Matrix7 cells21 rules14 anti12 hints
Determines what operations are permitted in each phase of a program or module lifecycle, from initialization through active execution to shutdown and cleanup.
lifecycle_phaseoperation_typefailure_contextscope_levelvisibility
program_lifecycle_001
During initialization, load all critical dependencies with timeout and fail fast if any are unavailable.
βœ… RULES (3)
Load dependencies in declared order with per-dependency timeout of 5s
Fail entire init if any critical dependency times out β€” do not enter partial state
Log each dependency load with name, duration_ms, and status
❌ ANTI-PATTERNS (2)
Silent fallback on missing dependency (hides critical failures until runtime)
Loading dependencies lazily during init phase (unpredictable init duration)
πŸ’» CODE HINTS (2)
await Promise.all(criticalDeps.map(d => loadWithTimeout(d, 5000)))
if (!allLoaded) { log.fatal('Init failed', {missing}); process.exit(1); }
program_lifecycle_002
During initialization, validate all configuration values before proceeding to active phase.
βœ… RULES (3)
Parse and validate config schema before any service starts
Reject unknown config keys to prevent typo-driven bugs
Freeze config object after validation β€” no runtime mutations
❌ ANTI-PATTERNS (2)
Reading config values scattered across codebase without central validation
Allowing config changes after init (causes inconsistent behavior mid-execution)
πŸ’» CODE HINTS (2)
const config = Object.freeze(validateConfig(rawConfig, schema))
if (unknownKeys.length) throw new ConfigError('Unknown keys: ' + unknownKeys)
program_lifecycle_003
Once in active phase, expose health and readiness endpoints that reflect actual internal state.
βœ… RULES (3)
Health check must verify all critical dependencies are still reachable
Readiness endpoint returns 503 until all init steps complete
Health check timeout: 2s β€” if exceeded, report unhealthy
❌ ANTI-PATTERNS (2)
Health endpoint that always returns 200 (masks real failures)
Checking only HTTP connectivity but not database query ability
πŸ’» CODE HINTS (2)
app.get('/healthz', async (req, res) => { const ok = await checkDeps(); res.status(ok ? 200 : 503).json({status: ok ? 'healthy' : 'degraded'}); })
app.get('/readyz', (req, res) => res.status(isReady ? 200 : 503).end())
program_lifecycle_004
During graceful shutdown, complete in-flight requests within a deadline before forcing termination.
βœ… RULES (3)
Stop accepting new connections immediately on SIGTERM
Allow in-flight requests up to 30s to complete
Force-kill remaining connections after deadline
❌ ANTI-PATTERNS (2)
Immediate process.exit() on SIGTERM (drops active requests)
No shutdown deadline (process hangs indefinitely on stuck request)
πŸ’» CODE HINTS (2)
process.on('SIGTERM', () => { server.close(); setTimeout(() => process.exit(1), 30000); })
server.close(() => { cleanup(); process.exit(0); })
program_lifecycle_005
During shutdown, release all acquired resources in reverse acquisition order to prevent leaks.
βœ… RULES (3)
Close resources in reverse order: connections β†’ pools β†’ file handles β†’ temp files
Set per-resource cleanup timeout of 5s
Log any resource that fails to close β€” do not throw
❌ ANTI-PATTERNS (2)
No cleanup on shutdown (leaks database connections, file locks)
Cleanup that throws exceptions (prevents other resources from closing)
πŸ’» CODE HINTS (1)
for (const resource of resources.reverse()) { try { await withTimeout(resource.close(), 5000); } catch(e) { log.warn('Cleanup failed', {resource: resource.name}); } }
program_lifecycle_006
During hot reload, preserve critical in-memory state while replacing code modules.
βœ… RULES (3)
Snapshot state before reload into serializable format
Validate new module loads successfully before discarding old module
Restore state into new module β€” rollback to old module if restore fails
❌ ANTI-PATTERNS (2)
Hot reload that silently drops in-memory caches (causes cold-start behavior)
Replacing module before verifying new version compiles/loads
πŸ’» CODE HINTS (1)
const snapshot = serialize(currentState); const newModule = await import(path + '?t=' + Date.now()); newModule.restore(snapshot);
program_lifecycle_007
On forced termination (SIGKILL, OOM), ensure data integrity through write-ahead strategies applied during active phase.
βœ… RULES (3)
Use write-ahead log or transaction journal for all critical writes
On next startup, replay uncommitted entries from journal
Never rely on graceful shutdown for data safety β€” assume crash at any point
❌ ANTI-PATTERNS (2)
Buffering writes in memory without flush strategy (data loss on crash)
Assuming shutdown hooks always run (SIGKILL skips them)
πŸ’» CODE HINTS (2)
await wal.append({op: 'write', key, value}); await wal.flush(); await db.write(key, value); await wal.commit();
// On startup: await wal.recover()
πŸ§ͺ VALIDATION
Simulate startup with missing dependency and verify fail-fast. Send SIGTERM during active requests and verify completion within deadline. Force-kill and verify WAL recovery on restart.
#3Responsibility Separation Matrix7 cells21 rules14 anti11 hints
Determines how to divide a system into modules with clear, single responsibilities β€” defining what each module owns, what it delegates, and where its boundary ends.
module_rolecoupling_typecommunication_patterngranularitypurity
responsibility_sep_001
Entry point modules (controllers, handlers) should contain zero business logic β€” only parse input, delegate to service, and format output.
βœ… RULES (3)
Controller receives request, validates shape, delegates to service, returns response
Max 10 lines per controller method β€” if more, logic is leaking in
No database calls, no business rules, no state mutations in controllers
❌ ANTI-PATTERNS (2)
Fat controller with 200+ lines containing business logic, DB queries, and formatting
Controller that imports ORM models directly (tight coupling to data layer)
πŸ’» CODE HINTS (2)
async handleCreateUser(req, res) { const dto = validate(req.body, CreateUserSchema); const user = await userService.create(dto); res.json(format(user)); }
// Controller knows: HTTP. Service knows: Business. Repo knows: Storage.
responsibility_sep_002
Service modules own all business rules and orchestration β€” they are the single source of truth for domain decisions.
βœ… RULES (3)
All business rules live in service layer β€” never in controller or repository
Service methods are framework-agnostic (no req/res objects, no HTTP codes)
Service can call multiple repositories but never calls other controllers
❌ ANTI-PATTERNS (2)
Business rule duplicated in controller AND service (diverges over time)
Service that returns HTTP status codes (leaks transport concern)
πŸ’» CODE HINTS (1)
class OrderService { async create(dto) { if (dto.total > customer.creditLimit) throw new BusinessError('CREDIT_EXCEEDED'); return this.orderRepo.save(dto); } }
responsibility_sep_003
Repository modules handle all data persistence β€” hiding storage implementation from services.
βœ… RULES (3)
Repository exposes domain-language methods: findByEmail, save, delete β€” not SQL
Storage technology (PostgreSQL, Redis, S3) is invisible to callers
Repository handles connection pooling and query optimization internally
❌ ANTI-PATTERNS (2)
Raw SQL in service layer (impossible to change storage without rewriting services)
Repository that returns ORM objects instead of plain DTOs (leaks ORM dependency)
πŸ’» CODE HINTS (1)
class UserRepository { async findByEmail(email) { const row = await db.query('SELECT * FROM users WHERE email=$1', [email]); return row ? toDTO(row) : null; } }
responsibility_sep_004
Cross-cutting concerns (logging, auth, rate-limiting) must be extracted into middleware β€” never embedded in business modules.
βœ… RULES (3)
Auth check = middleware, not a line inside every controller
Logging = middleware that wraps request/response, not scattered console.log
Rate limiting = middleware per route group, not per-handler implementation
❌ ANTI-PATTERNS (2)
Every controller starts with if(!user.isAdmin) return 403 (duplicated auth logic)
Logging added inside service methods (mixes concern with business logic)
πŸ’» CODE HINTS (2)
app.use('/admin/*', authMiddleware('admin'));
app.use(requestLogger({ excludePaths: ['/healthz'] }));
responsibility_sep_005
When organizing by feature (vertical slice), each feature folder owns its own controller, service, repo, and types β€” shared only via explicit public API.
βœ… RULES (3)
Feature folder contains: controller, service, repository, types, tests
Cross-feature communication only through exported service interface
No direct imports from another feature's internal modules
❌ ANTI-PATTERNS (2)
Feature A importing Feature B's repository directly (bypasses B's business rules)
Shared 'utils' folder that grows into a God module with 50+ functions
πŸ’» CODE HINTS (2)
// features/orders/index.ts exports only: OrderService, OrderDTO, CreateOrderInput
// features/users/service.ts imports from '../orders' β€” only the public API
responsibility_sep_006
All dependency wiring happens in one composition root β€” modules never instantiate their own dependencies.
βœ… RULES (3)
Composition root creates all instances and passes dependencies via constructor
Modules declare dependencies as constructor parameters β€” never import and instantiate
One composition root per application entry point
❌ ANTI-PATTERNS (2)
Service that does new Database() internally (untestable, hidden dependency)
Multiple places where dependencies are wired differently (inconsistent behavior)
πŸ’» CODE HINTS (1)
// composition-root.ts const db = new Database(config.db); const userRepo = new UserRepo(db); const userService = new UserService(userRepo); const userController = new UserController(userService);
responsibility_sep_007
Isolate side-effects (I/O, network, disk) at module boundaries β€” keep core logic pure and testable.
βœ… RULES (3)
Business rule functions take data in, return data out β€” no I/O inside
I/O operations wrapped in dedicated adapter modules
Core logic testable with plain objects β€” no mocks needed
❌ ANTI-PATTERNS (2)
Business calculation that also sends email (untestable without email mock)
Pure function that secretly reads environment variable (hidden side-effect)
πŸ’» CODE HINTS (2)
// Pure: const discount = calculateDiscount(order, customer);
// Impure adapter: await emailService.send(customer.email, receiptTemplate(order, discount));
πŸ§ͺ VALIDATION
Verify that controllers contain zero business logic, services have no HTTP concerns, repositories hide storage implementation, and cross-cutting concerns are middleware-only. Test core logic with plain objects β€” no mocks required.
#4Determinism vs Non-Determinism Matrix6 cells12 rules6 anti8 hints
Determines which parts of a system must produce identical output for identical input, and how to control, test, and isolate non-deterministic behavior.
determinism_requirementsource_of_nondeterminismisolation_strategytestability_impact
determinism_001
When logic depends on current time (e.g. expiration checks), inject a Clock interface to control time source.
βœ… RULES (2)
Define IClock interface with now(): Date
Inject FakeClock in tests to simulate time advancement
❌ ANTI-PATTERNS (1)
Calling Date.now() directly in business logic (prevents deterministic testing)
πŸ’» CODE HINTS (2)
interface Clock { now(): Date }
constructor(private clock: Clock) { ... }
determinism_002
When generating random values for deterministic output (e.g. test IDs), use a seeded generator.
βœ… RULES (2)
Use a fixed seed per test case
Reset seed before each test to ensure reproducibility
❌ ANTI-PATTERNS (1)
Using Math.random() in tests (breaks reproducibility)
πŸ’» CODE HINTS (1)
import seedrandom from 'seedrandom'; const rng = seedrandom('test-seed'); const value = rng()
determinism_003
When logic depends on external services (e.g. geolocation), wrap with adapter to allow mocking and fallback.
βœ… RULES (2)
Create adapter interface for external service
Provide mock implementation for tests and fallback behavior for errors
❌ ANTI-PATTERNS (1)
Calling fetch() directly inside business logic (tight coupling, hard to test)
πŸ’» CODE HINTS (2)
class GeoAdapter { getLocation(): Promise<Coords> }
geo = test ? new FakeGeo() : new RealGeo()
determinism_004
When financial logic uses floating-point math, convert to integer cents to avoid rounding errors.
βœ… RULES (2)
Store monetary values in cents as integers
Avoid multiplying/dividing floats directly
❌ ANTI-PATTERNS (1)
Using floating-point for currency math (leads to precision bugs)
πŸ’» CODE HINTS (1)
const cents = Math.round(dollars * 100); const total = priceCents * qty
determinism_005
When tasks may run in any order (e.g. UI rendering), ensure assertions don’t assume specific order.
βœ… RULES (2)
Assert presence of elements regardless of order
Use Set equality instead of array equality
❌ ANTI-PATTERNS (1)
Writing tests that fail due to order-only differences
πŸ’» CODE HINTS (1)
expect(new Set(rendered)).toEqual(new Set(expected))
determinism_006
When sorting or hashing data, use explicit comparator and stable algorithms to preserve order.
βœ… RULES (2)
Always pass a comparator to sort
Use Map/Object instead of raw Set when key order matters
❌ ANTI-PATTERNS (1)
Relying on default sort without comparator (non-portable behavior)
πŸ’» CODE HINTS (1)
arr.sort((a, b) => a.localeCompare(b))
πŸ§ͺ VALIDATION
Run each business function 100 times with identical input and verify identical output. Test with FakeClock and seeded random. Verify financial calculations use integer cents. Assert sort stability across environments.
#5Sync vs Async Matrix6 cells12 rules6 anti6 hints
Determines when to use synchronous vs asynchronous execution, what guarantees each provides, and how to prevent mixing patterns that cause subtle bugs.
operation_natureblocking_riskerror_propagation_modecomposability
sync_async_001
When a CPU-bound operation exceeds 16ms on the main thread (e.g. parsing large JSON), offload to a worker to avoid UI stalls or event loop lag.
βœ… RULES (2)
Profile execution time; offload if >16ms
Use worker_threads in Node or Web Workers in browser
❌ ANTI-PATTERNS (1)
Running heavy parsing or computation inline (causes frame drops and input lag)
πŸ’» CODE HINTS (1)
const worker = new Worker('worker.js'); worker.postMessage(payload);
sync_async_002
When performing I/O operations (e.g. DB query, HTTP call), use async APIs and enforce timeouts.
βœ… RULES (2)
Wrap fetch or db call with timeout (e.g. AbortController)
Never block with sync fs or net APIs
❌ ANTI-PATTERNS (1)
Using sync I/O in async handlers (blocks event loop)
πŸ’» CODE HINTS (1)
const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); await fetch(url, { signal: controller.signal });
sync_async_003
When firing multiple independent I/O calls (e.g. fetches), use Promise.all but control concurrency to avoid overload.
βœ… RULES (2)
Limit concurrency with a utility like p-limit
Batch dependent on system capacity
❌ ANTI-PATTERNS (1)
Firing 1000 fetches simultaneously (socket exhaustion, slowdowns)
πŸ’» CODE HINTS (1)
import pLimit from 'p-limit'; const limit = pLimit(10); await Promise.all(urls.map(u => limit(() => fetch(u))))
sync_async_004
When bridging from callback-based code to async/await, wrap in a Promise and handle errors at the boundary.
βœ… RULES (2)
Use util.promisify or wrap manually
Ensure error-first callback is properly captured
❌ ANTI-PATTERNS (1)
Calling async code from callbacks without try/catch (leads to swallowed rejections)
πŸ’» CODE HINTS (1)
const fs = require('fs'); const readFile = util.promisify(fs.readFile); await readFile('file.txt')
sync_async_005
When processing streaming data (e.g. large files, HTTP chunks), use for-await-of and respect backpressure.
βœ… RULES (2)
Use async iterators and pipe with highWaterMark
Avoid reading entire stream into memory
❌ ANTI-PATTERNS (1)
Buffering entire input before processing (high memory usage, delayed response)
πŸ’» CODE HINTS (1)
for await (const chunk of stream) { process(chunk); }
sync_async_006
When initializing async state at module load (e.g. config from disk), use top-level await or an async factory.
βœ… RULES (2)
Avoid blocking initialization via sync fs/net
Ensure consumers await readiness signal
❌ ANTI-PATTERNS (1)
Returning uninitialized module state (leads to undefined behavior)
πŸ’» CODE HINTS (1)
const config = await fetchConfig(); export default config;
πŸ§ͺ VALIDATION
Verify: no sync I/O in server code, no unnecessary async wrappers on sync functions, independent operations run concurrently, all async calls have error handling, streams respect backpressure.
#6Error Propagation Matrix7 cells14 rules7 anti7 hints
Determines how errors are created, categorized, propagated, and communicated across module boundaries.
propagation_methoderror_severityboundary_typecontext_strategy
error_propagation_001
When a fatal programmer error occurs (e.g. TypeError), throw immediately and allow the process to crash.
βœ… RULES (2)
Do not catch programmer errors like TypeError, ReferenceError
Let fatal errors bubble to global handler
❌ ANTI-PATTERNS (1)
Catching fatal errors and attempting to continue (leads to undefined behavior)
πŸ’» CODE HINTS (1)
if (err instanceof TypeError) throw err;
error_propagation_002
When an operational error occurs in a service boundary (e.g. user not found), return a Result<T, E> instead of throwing.
βœ… RULES (2)
Define domain error types (e.g. UserNotFound)
Return Result.ok or Result.err explicitly
❌ ANTI-PATTERNS (1)
Throwing for expected errors (makes control flow hard to follow)
πŸ’» CODE HINTS (1)
return Result.err(new UserNotFound(userId));
error_propagation_003
When propagating operational errors across layers, wrap them with context using the cause chain.
βœ… RULES (2)
Use custom error classes that accept a cause
Preserve original stack trace
❌ ANTI-PATTERNS (1)
Throwing plain Error and losing original context
πŸ’» CODE HINTS (1)
throw new PaymentFailedError('Card declined', { cause: err });
error_propagation_004
When an operational error occurs in an event-based system, emit an error event on the process or application emitter.
βœ… RULES (2)
Use EventEmitter and emit 'error' with enriched object
Listen globally for 'error' events
❌ ANTI-PATTERNS (1)
Failing silently inside an event handler (invisible failure)
πŸ’» CODE HINTS (1)
emitter.emit('error', new ServiceError('Payment failed', { cause: err }));
error_propagation_005
When an unhandled rejection occurs in an async context, capture at the process level, log, and exit.
βœ… RULES (2)
Register process.on('unhandledRejection', handler)
Log and terminate for fatal categories
❌ ANTI-PATTERNS (1)
Allowing unhandled rejections to go unnoticed (leads to silent crashes)
πŸ’» CODE HINTS (1)
process.on('unhandledRejection', (reason) => { log(reason); process.exit(1); });
error_propagation_006
At service boundaries, replace internal errors with domain-specific errors that hide implementation details.
βœ… RULES (2)
Catch low-level errors and return mapped domain error
Never leak stack traces or internal error codes to clients
❌ ANTI-PATTERNS (1)
Returning internal error message directly to API response
πŸ’» CODE HINTS (1)
return Result.err(new DomainError('Unable to process payment'));
error_propagation_007
For transient errors (e.g. DB timeout), enrich the error with context like request ID, user ID, and timestamp.
βœ… RULES (2)
Wrap error with metadata relevant to request
Use structured logging format
❌ ANTI-PATTERNS (1)
Returning raw DB timeout message without correlation info
πŸ’» CODE HINTS (1)
return Result.err(new TransientError('DB timeout', { requestId, userId, timestamp }));
πŸ§ͺ VALIDATION
Verify: no swallowed errors, all async paths have catch, errors enriched at each boundary, programmer errors crash process, operational errors return typed Result.
#7Dependency Direction Matrix7 cells14 rules7 anti7 hints
Determines dependency direction between modules to prevent circular deps and keep core independent.
directionabstraction_levellayer_crossingvolatility
dependency_001
When infrastructure depends on core logic, define the interface in the core and implement it in the outer layer.
βœ… RULES (2)
Core defines contracts/interfaces
Infra layer implements the interface and calls into core
❌ ANTI-PATTERNS (1)
Core importing from infrastructure (creates cycle and violates layering)
πŸ’» CODE HINTS (1)
interface UserRepo { findById(id: string): User } // defined in core
dependency_002
When UI layer imports directly from data layer (skip-layer access), flag as architecture violation.
βœ… RULES (2)
Only import from adjacent layers
Block imports from non-adjacent layers in CI
❌ ANTI-PATTERNS (1)
UI β†’ Data layer import (bypasses service logic and breaks encapsulation)
πŸ’» CODE HINTS (1)
// forbidden: import { fetchFromDb } from 'data-layer/db'
dependency_003
When two same-layer modules communicate, define a shared abstract class or interface to prevent tight coupling.
βœ… RULES (2)
Move shared contract to a neutral package
Avoid direct imports between peer modules
❌ ANTI-PATTERNS (1)
Module A importing internal concrete types from Module B
πŸ’» CODE HINTS (1)
abstract class TaskScheduler { schedule(task: Task): void }
dependency_004
Break circular dependency between core and adapter by extracting shared abstract class to common neutral zone.
βœ… RULES (2)
Extract shared dependency to a stable shared module
Use abstract classes for bidirectional dependency boundaries
❌ ANTI-PATTERNS (1)
Core and adapter mutually importing each other
πŸ’» CODE HINTS (1)
abstract class Logger { log(msg: string): void } // used by both core and infra
dependency_005
When depending on unstable external modules, wrap them behind stable interfaces to isolate churn.
βœ… RULES (2)
Expose only stable interface to core
Swap volatile library without touching callers
❌ ANTI-PATTERNS (1)
Core code importing from unstable third-party lib directly
πŸ’» CODE HINTS (1)
class UuidGenAdapter implements UuidGen { constructor(private uuid = require('uuid')) }
dependency_006
Use plugin architecture where the core defines an interface and the infrastructure registers implementations at runtime.
βœ… RULES (2)
Core defines a pluggable port
Infra registers implementation via registration API
❌ ANTI-PATTERNS (1)
Plugin directly imports core and initializes itself (violates inversion)
πŸ’» CODE HINTS (1)
registerStorageProvider(new S3StorageProvider())
dependency_007
Enforce a build-time DAG check to detect and reject cycles in the import graph.
βœ… RULES (2)
Analyze imports statically before bundling
Reject builds with circular paths
❌ ANTI-PATTERNS (1)
Two modules importing each other (A β†’ B β†’ A)
πŸ’» CODE HINTS (1)
// build script fails if detect-cycle returns non-zero
πŸ§ͺ VALIDATION
Verify: no circular imports, core has zero outward dependencies, all infrastructure behind interfaces, skip-layer imports rejected at build time.
#8Pure vs Impure Logic Matrix6 cells12 rules6 anti6 hints
Determines which functions must be pure and which may be impure, and how to isolate impurity at boundaries.
purityboundary_positiontestabilitycqs_compliance
purity_001
When business logic is purely computational, extract it into a pure function in the core domain.
βœ… RULES (2)
Inputs and outputs must be data only
Must not access external state or perform I/O
❌ ANTI-PATTERNS (1)
Mixing database access or logging into business rules
πŸ’» CODE HINTS (1)
function calculateDiscount(price, rate) { return price * rate; }
purity_002
When performing I/O (e.g. API calls, file access), move these actions to the outer shell and inject results into pure functions.
βœ… RULES (2)
All I/O should happen outside the core
Inject data into core as parameters
❌ ANTI-PATTERNS (1)
Calling fetch or fs.readFile directly inside logic module
πŸ’» CODE HINTS (1)
const data = await fetch(...); const result = calculate(data);
purity_003
When a function is pure and has no hidden state, it can safely be memoized.
βœ… RULES (2)
Ensure referential transparency
Do not use Date, Math.random or global vars
❌ ANTI-PATTERNS (1)
Memoizing impure or time-based logic (produces stale/broken results)
πŸ’» CODE HINTS (1)
const cache = new Map(); function memoized(x) { if (cache.has(x)) return cache.get(x); const y = compute(x); cache.set(x, y); return y; }
purity_004
When a function mixes querying and side-effects (e.g. read + write), split into separate query and command functions.
βœ… RULES (2)
Apply CQS: query = no side effects, command = no return value
Separate concerns even in the same module
❌ ANTI-PATTERNS (1)
Functions that mutate state and return data in same call
πŸ’» CODE HINTS (1)
const user = repo.getUser(id); repo.updateLastSeen(id);
purity_005
When Date.now() or similar time logic appears inside core functions, mock time and isolate impurity to boundary.
βœ… RULES (2)
Inject time provider as parameter
Avoid direct calls to Date/clock APIs in logic
❌ ANTI-PATTERNS (1)
Calling Date.now() inside pricing or rules engine
πŸ’» CODE HINTS (1)
function now(clock) { return clock.now(); }
purity_006
When adapting external libraries or services, wrap impure logic behind an interface and expose a pure API.
βœ… RULES (2)
Adapter should isolate third-party calls
Expose deterministic output to core
❌ ANTI-PATTERNS (1)
Exposing raw fetch or db call to core domain
πŸ’» CODE HINTS (1)
class UserAdapter { async findById(id) { const r = await fetch(...); return r.json(); } }
πŸ§ͺ VALIDATION
Verify: core functions have no I/O, memoization only on pure functions, all impurity pushed to shell/adapter, tests for core need zero mocks.
#9Side-Effects Control Matrix7 cells14 rules7 anti7 hints
Determines how side effects are controlled, ordered, and made reversible.
effect_typereversibilityexecution_timingtraceability
side_effects_001
When performing irreversible writes (e.g. send email, log to disk), validate inputs and execute immediately without rollback.
βœ… RULES (2)
Sanitize and validate before performing write
Do not attempt rollback; log for traceability
❌ ANTI-PATTERNS (1)
Issuing irreversible write before validating inputs
πŸ’» CODE HINTS (1)
if (!isValid(input)) throw new Error('invalid'); await sendEmail(input);
side_effects_002
When executing write effects that may need rollback (e.g. account creation), batch them and flush at end with compensation available.
βœ… RULES (2)
Queue write effects during transaction
Define compensating action for each
❌ ANTI-PATTERNS (1)
Executing writes mid-transaction without rollback path
πŸ’» CODE HINTS (1)
effects.push({ do: () => db.insert(...), undo: () => db.delete(...) });
side_effects_003
When performing reversible writes (e.g. database update), wrap in transaction and rollback on error.
βœ… RULES (2)
Begin transaction before first write
Rollback on any failure
❌ ANTI-PATTERNS (1)
Modifying state outside transaction block
πŸ’» CODE HINTS (1)
db.begin(); try { db.update(...); db.commit(); } catch { db.rollback(); }
side_effects_004
When making external API calls with effect (e.g. send SMS), log request and response for trace and enable manual replay.
βœ… RULES (2)
Log full request/response
Store correlation ID for later investigation
❌ ANTI-PATTERNS (1)
Calling external service without trace/log
πŸ’» CODE HINTS (1)
logEffect({ id, request, response });
side_effects_005
When executing irreversible but retryable write effects (e.g. payment), use idempotency key to ensure safe retries.
βœ… RULES (2)
Generate unique idempotency key per logical operation
Check key before repeating effect
❌ ANTI-PATTERNS (1)
Issuing duplicate write on retry without protection
πŸ’» CODE HINTS (1)
if (!store.has(key)) { store.set(key, effect()); }
side_effects_006
When batching irreversible emit effects (e.g. metrics, analytics), deduplicate and flush together to reduce noise.
βœ… RULES (2)
Group identical emits into one
Flush emit queue at controlled boundary
❌ ANTI-PATTERNS (1)
Emitting same event multiple times per loop iteration
πŸ’» CODE HINTS (1)
const queue = new Set(); queue.add('page_view'); ... flush(queue);
side_effects_007
When running a dry-run (sandbox) of write logic, defer actual commit until explicit confirmation.
βœ… RULES (2)
Run writes in memory or mock layer
Only persist when approved
❌ ANTI-PATTERNS (1)
Performing irreversible action in preview mode
πŸ’» CODE HINTS (1)
if (dryRun) simulateWrite(data); else commit(data);
πŸ§ͺ VALIDATION
Verify: no accidental effects in read context, all writes traced, batched effects flushed at boundary, reversible effects have rollback, idempotent effects safe to retry.
#10Contract-First Matrix6 cells12 rules6 anti6 hints
Determines when and how to define interface contracts before implementation.
design_approachenforcementevolution_strategyownership
contract_001
When designing a new module, define the interface and types first, then implement behind it.
βœ… RULES (2)
Define TypeScript interface or Protocol Buffer schema before any code
All consumers must type-check against interface
❌ ANTI-PATTERNS (1)
Writing code first and retrofitting types (leads to leaking internal structure)
πŸ’» CODE HINTS (1)
interface PaymentService { charge(amount: number): Promise<Receipt> }
contract_002
When defining API request/response, validate schema at runtime using a shared contract definition.
βœ… RULES (2)
Use Zod or JSON Schema to validate inputs at boundary
Reject requests with structural mismatches
❌ ANTI-PATTERNS (1)
Trusting incoming data without validation
πŸ’» CODE HINTS (1)
const schema = z.object({ name: z.string() }); schema.parse(req.body);
contract_003
When consumer owns the contract (e.g. frontend), provider validates at runtime and matches in tests.
βœ… RULES (2)
Use Pact or similar for consumer-driven contract tests
Validate schema during development and CI
❌ ANTI-PATTERNS (1)
Provider changing contract shape without notifying consumers
πŸ’» CODE HINTS (1)
pactVerifier.verifyProvider({ providerBaseUrl, pactUrls })
contract_004
When evolving API contracts, make changes backward compatible (e.g. add optional fields only).
βœ… RULES (2)
Never remove or rename fields without version bump
Mark added fields as optional and nullable
❌ ANTI-PATTERNS (1)
Breaking existing clients by removing or retyping fields
πŸ’» CODE HINTS (1)
type User = { id: string; name?: string | null }
contract_005
When extracting interface from working code, freeze it after initial stabilization to prevent drift.
βœ… RULES (2)
Use tools to extract .d.ts or OpenAPI from implementation
Treat as public contract from that point forward
❌ ANTI-PATTERNS (1)
Letting internal changes alter contract without review
πŸ’» CODE HINTS (1)
npx tsc --emitDeclarationOnly
contract_006
When using schema-first development (e.g. OpenAPI), generate types to enforce consistency across layers.
βœ… RULES (2)
Generate TypeScript types from OpenAPI using openapi-typescript
Regenerate types on schema change in CI
❌ ANTI-PATTERNS (1)
Handwriting types that drift from canonical schema
πŸ’» CODE HINTS (1)
npx openapi-typescript schema.yaml --output types.ts
πŸ§ͺ VALIDATION
Verify: all public modules have typed interface, API boundaries have schema validation, contract changes are backward compatible by default, generated types match source schema.
#11Input β†’ Output Mapping Matrix6 cells12 rules6 anti6 hints
Determines how input data is transformed into output data β€” mapping rules, transformation boundaries, and data flow contracts.
mapping_typetransformation_complexitydata_fidelitydirectionality
mapping_001
When input maps directly to output without transformation, pass through with identity function.
βœ… RULES (2)
Ensure shape and type match exactly
Avoid unnecessary wrapping or cloning
❌ ANTI-PATTERNS (1)
Adding wrapper objects that break shape compatibility
πŸ’» CODE HINTS (1)
function map(input) { return input; }
mapping_002
When renaming fields for DTOs or APIs, map each field explicitly.
βœ… RULES (2)
Define explicit field mapping per target schema
Use mapping utility for traceability
❌ ANTI-PATTERNS (1)
Implicit renaming via spread operators
πŸ’» CODE HINTS (1)
{ user_name: source.username, user_id: source.id }
mapping_003
When output includes derived fields (e.g. full name), compute during mapping.
βœ… RULES (2)
Keep computation pure and side-effect free
Document all computed fields and formulas
❌ ANTI-PATTERNS (1)
Embedding business logic inside mapper unnecessarily
πŸ’» CODE HINTS (1)
output.fullName = input.first + ' ' + input.last
mapping_004
When mapping nested inputs into flat outputs, extract and flatten structure.
βœ… RULES (2)
Use dot notation or destructuring for clarity
Log mapping path for debugging
❌ ANTI-PATTERNS (1)
Mixing flattened and nested fields inconsistently
πŸ’» CODE HINTS (1)
const { user: { id, name } } = input; output.user_id = id
mapping_005
When output removes fields or precision, mark as lossy and prevent inverse mapping.
βœ… RULES (2)
Document irreversible transformations
Reject attempts to reverse map lossy output
❌ ANTI-PATTERNS (1)
Attempting round-trip on lossy transformations
πŸ’» CODE HINTS (1)
output = { price: Math.floor(input.price) }
mapping_006
When mapping is round-trippable, define both forward and reverse maps.
βœ… RULES (2)
Test reverse(map(input)) equals input
Ensure no transformation causes info loss
❌ ANTI-PATTERNS (1)
Inconsistent reverse transformation logic
πŸ’» CODE HINTS (1)
mapper = { to: fn, from: revFn }
πŸ§ͺ VALIDATION
Verify: bidirectional mappings are reversible, derived fields are pure, lossy transformations are flagged, flattening does not break contract.
#12Data Ownership Matrix6 cells12 rules6 anti6 hints
Determines which module owns which data β€” who can read, write, and mutate each piece of state.
ownership_modelaccess_patternmutation_rightssharing_scope
ownership_001
When one module owns and controls a data structure, restrict all mutations to it.
βœ… RULES (2)
Expose read-only interface to others
Enforce all writes through owner module
❌ ANTI-PATTERNS (1)
External module modifying internal state via object reference
πŸ’» CODE HINTS (1)
export function getState() { return deepClone(state); }
ownership_002
When multiple modules need read access but only one writes, enforce read-only sharing.
βœ… RULES (2)
Expose immutable view for readers
Writer module must mediate all updates
❌ ANTI-PATTERNS (1)
Multiple writers on shared state leading to race conditions
πŸ’» CODE HINTS (1)
Object.freeze(sharedData)
ownership_003
When ownership of state changes via event (e.g. checkout β†’ order), emit event and reassign ownership.
βœ… RULES (2)
Track previous owner in event log
Transfer control explicitly at event time
❌ ANTI-PATTERNS (1)
Changing data owner without recording transfer event
πŸ’» CODE HINTS (1)
emit('ownershipChanged', { from: 'cart', to: 'order' })
ownership_004
When data is used only within one module, keep it private and fully encapsulated.
βœ… RULES (2)
Avoid exporting internal data structures
Allow mutation only through internal functions
❌ ANTI-PATTERNS (1)
Cross-module imports of internal state
πŸ’» CODE HINTS (1)
const internal = {}; function update() { internal.v++ }
ownership_005
When data is shared between modules, define contract to govern access and updates.
βœ… RULES (2)
Use schema to define shared shape
Validate on read and write
❌ ANTI-PATTERNS (1)
Unstructured sharing via global object
πŸ’» CODE HINTS (1)
type SharedUser = { id: string, email: string }
ownership_006
When client owns its own data (e.g. local form), allow it to POST to API but validate before write.
βœ… RULES (2)
Validate incoming data strictly
Allow only permitted fields to change
❌ ANTI-PATTERNS (1)
Client directly updates server-side data store
πŸ’» CODE HINTS (1)
POST /update-profile { name, phone } // backend validates
πŸ§ͺ VALIDATION
Verify: all data has exactly one write authority, shared data is validated, ownership transfers are logged or explicit, private data is not leaked.
#13Mutation Control Matrix6 cells12 rules6 anti6 hints
Determines when and how data can be mutated β€” immutable by default, controlled mutation points, and mutation tracking.
mutabilityscopetrackingenforcement
mutation_001
When defaulting to immutability, enforce copy-on-write and never mutate shared data.
βœ… RULES (2)
Use spread or cloning to update data
Mark all state as readonly where possible
❌ ANTI-PATTERNS (1)
Mutating arguments inside pure functions
πŸ’» CODE HINTS (1)
const next = { ...prev, updated: true }
mutation_002
When mutation is allowed, funnel it through named actions or reducers.
βœ… RULES (2)
Only allow mutation inside predefined reducers
Disallow external mutation outside flow
❌ ANTI-PATTERNS (1)
Calling setState directly from arbitrary module
πŸ’» CODE HINTS (1)
dispatch({ type: 'add_item', payload })
mutation_003
To support structural sharing, copy-on-write state updates ensure performance and consistency.
βœ… RULES (2)
Never modify original object
Create new reference on every update
❌ ANTI-PATTERNS (1)
Patching existing state inline
πŸ’» CODE HINTS (1)
return { ...state, count: state.count + 1 }
mutation_004
When enforcing immutability, freeze entire object tree at runtime in dev mode.
βœ… RULES (2)
Use deepFreeze utility in tests and development
Throw on mutation attempt
❌ ANTI-PATTERNS (1)
Silent mutation of nested object in shared state
πŸ’» CODE HINTS (1)
deepFreeze(appState)
mutation_005
Only allow mutations during open transaction boundaries (e.g. database tx, Redux batch).
βœ… RULES (2)
Begin transaction before mutation
Rollback on failure or cancel
❌ ANTI-PATTERNS (1)
Modifying multiple stores inconsistently
πŸ’» CODE HINTS (1)
begin(); try { update(); commit(); } catch { rollback(); }
mutation_006
When mutation tracking is required (e.g. audit or undo), capture before/after diff.
βœ… RULES (2)
Log all state diffs with timestamp and user
Support rollback via patching
❌ ANTI-PATTERNS (1)
Overwriting without diff tracking or metadata
πŸ’» CODE HINTS (1)
diff = deepDiff(prev, next); logChange(diff)
πŸ§ͺ VALIDATION
Verify: no shared state mutated outside allowed zones, deep freeze catches accidental mutations, all tracked mutations logged, transactions rollback properly.
#14Idempotency Matrix6 cells12 rules6 anti6 hints
Determines which operations must be idempotent (safe to repeat) and how to enforce idempotency guarantees.
operation_typeidempotency_levelenforcement_mechanismscope
idempotency_001
When implementing HTTP GET endpoints, ensure they never modify state and can be repeated safely.
βœ… RULES (2)
Do not mutate any state or trigger effects
Allow aggressive caching and retry
❌ ANTI-PATTERNS (1)
Using GET to trigger actions (e.g. send email)
πŸ’» CODE HINTS (1)
app.get('/profile', (req, res) => res.json(user));
idempotency_002
When using PUT to update state, ensure the same input leads to same result, allowing safe retries.
βœ… RULES (2)
PUT must fully overwrite resource or produce consistent patch
Use conditional update or version checks
❌ ANTI-PATTERNS (1)
Partial updates with side effects in PUT
πŸ’» CODE HINTS (1)
db.update({ id, ...data })
idempotency_003
When POST has side effects (e.g. create charge), enforce idempotency with client-generated key.
βœ… RULES (2)
Store idempotency key and result server-side
Reject duplicates with same key
❌ ANTI-PATTERNS (1)
Accepting repeated POST with different side effects
πŸ’» CODE HINTS (1)
if (store.has(key)) return store.get(key); else { result = run(); store.set(key, result); }
idempotency_004
When inserting or updating DB row, use upsert to avoid duplicate inserts.
βœ… RULES (2)
Use DB-native upsert if available
Match on business key not auto ID
❌ ANTI-PATTERNS (1)
INSERT without ON CONFLICT or equivalent
πŸ’» CODE HINTS (1)
INSERT ... ON CONFLICT DO UPDATE
idempotency_005
When consuming events, deduplicate by ID or hash to ensure idempotent side effects.
βœ… RULES (2)
Log processed message IDs with TTL
Skip known IDs
❌ ANTI-PATTERNS (1)
Replaying events without dedup logic
πŸ’» CODE HINTS (1)
if (seen.has(event.id)) return; seen.add(event.id); handle(event)
idempotency_006
When retrying operations (e.g. API call), ensure all operations are safe to repeat.
βœ… RULES (2)
Wrap in idempotent method or middleware
Avoid side effects inside retry loop
❌ ANTI-PATTERNS (1)
Retrying unsafe operation without protection
πŸ’» CODE HINTS (1)
await withRetry(doIdempotentThing, { retries: 3 })
πŸ§ͺ VALIDATION
Verify: GET has no side effects, POST with idempotency key is deduplicated, events are not processed twice, database writes use UPSERT or equivalent.
#15Versioning Strategy Matrix6 cells12 rules6 anti6 hints
Determines how to version APIs, schemas, and modules β€” when to bump, what constitutes a breaking change, and how to maintain compatibility.
versioning_schemescopecompatibility_promisemigration_support
versioning_001
When publishing internal or shared modules, use semantic versioning to signal compatibility.
βœ… RULES (2)
Major = breaking, Minor = additive, Patch = bugfix
Automate semver checks in CI
❌ ANTI-PATTERNS (1)
Changing exports without bumping major
πŸ’» CODE HINTS (1)
v2.1.3 β†’ v3.0.0 after breaking API change
versioning_002
When versioning REST APIs, embed version in URL to allow parallel evolution.
βœ… RULES (2)
Use /v1/, /v2/ in route prefix
Maintain older versions for clients
❌ ANTI-PATTERNS (1)
Changing response shape in-place without version bump
πŸ’» CODE HINTS (1)
GET /v2/products
versioning_003
When supporting multiple formats, use header to indicate API version.
βœ… RULES (2)
Use Accept-Version or custom header
Respond with versioned schema
❌ ANTI-PATTERNS (1)
Silently changing behavior without header negotiation
πŸ’» CODE HINTS (1)
Accept-Version: 1.2
versioning_004
When changing DB schema, store version in row to enable forward/backward compatibility.
βœ… RULES (2)
Include 'schema_version' field in records
Transform rows as needed during read
❌ ANTI-PATTERNS (1)
Applying migration blindly to old-format rows
πŸ’» CODE HINTS (1)
{ id: 1, schema_version: 2, name: '...' }
versioning_005
When deprecating API, mark old version as deprecated, set sunset header, and remove later.
βœ… RULES (2)
Use standard HTTP headers for deprecation
Document replacement clearly
❌ ANTI-PATTERNS (1)
Breaking old clients without warning
πŸ’» CODE HINTS (1)
Sunset: Tue, 31 Dec 2024 23:59:59 GMT
versioning_006
When interface is contract-first, bump version manually when schema changes.
βœ… RULES (2)
Add version suffix to schema filename or ID
Track contract change history in changelog
❌ ANTI-PATTERNS (1)
Auto-generating breaking changes without version bump
πŸ’» CODE HINTS (1)
openapi.v2.yaml β†’ openapi.v3.yaml
πŸ§ͺ VALIDATION
Verify: all changes documented with version, backward compatibility promises are respected, deprecation periods are enforced, API schema versions align with implementation.
#16Backward Compatibility Matrix6 cells12 rules6 anti6 hints
Determines how to maintain backward compatibility when evolving interfaces, schemas, and protocols.
change_typecompatibility_leveldetection_methodremediation
compat_001
When adding a field, make it optional or provide default to preserve compatibility.
βœ… RULES (2)
Do not require new field from older clients
Allow null/undefined in new field
❌ ANTI-PATTERNS (1)
Adding required field without default
πŸ’» CODE HINTS (1)
type User = { name: string; nickname?: string }
compat_002
When removing a field, treat as breaking change and coordinate migration.
βœ… RULES (2)
Deprecate field before removal
Notify consumers and allow transition period
❌ ANTI-PATTERNS (1)
Deleting fields still in use by clients
πŸ’» CODE HINTS (1)
// DEPRECATED: use fullName instead of name
compat_003
When changing field type (e.g. string β†’ number), treat as breaking and require version bump.
βœ… RULES (2)
Update documentation and downstream types
Provide type adapters for transition
❌ ANTI-PATTERNS (1)
Silently changing field type
πŸ’» CODE HINTS (1)
field: string β†’ field: number // v2
compat_004
When adding field with default, older clients ignore and newer clients benefit.
βœ… RULES (2)
Set safe default on server side
Document semantic meaning of default
❌ ANTI-PATTERNS (1)
Leaving field undefined for some records
πŸ’» CODE HINTS (1)
isActive = input.isActive ?? true
compat_005
When verifying client compatibility, use contract tests to catch unexpected changes.
βœ… RULES (2)
Run consumer-driven tests on provider
CI must fail if contract breaks
❌ ANTI-PATTERNS (1)
Skipping contract tests for minor changes
πŸ’» CODE HINTS (1)
pactVerifier.verifyProvider(...)
compat_006
When removing features or fields, use a deprecation phase before final removal.
βœ… RULES (2)
Log usage of deprecated fields
Announce removal date
❌ ANTI-PATTERNS (1)
Removing deprecated things without tracking usage
πŸ’» CODE HINTS (1)
console.warn('Deprecated: use newField')
πŸ§ͺ VALIDATION
Verify: all breaking changes are versioned or deprecated first, additive fields are optional, contract tests are enforced, deprecated fields are logged before removal.
#17Failure Domains Matrix6 cells12 rules6 anti6 hints
Determines how to isolate failure domains β€” so that a failure in one part of the system does not cascade to other parts.
isolation_levelfailure_scopeblast_radiusrecovery_strategy
failure_001
When isolating failure by process, crash one feature without affecting others.
βœ… RULES (2)
Run each feature in separate worker/thread
Restart only affected unit
❌ ANTI-PATTERNS (1)
Global crash from one failing feature
πŸ’» CODE HINTS (1)
new Worker('./featureA.js')
failure_002
When a domain fails (e.g. payments), isolate service so others function.
βœ… RULES (2)
Split domains into separate deployable services
Failover only domain-specific pieces
❌ ANTI-PATTERNS (1)
Shared DB or runtime between unrelated domains
πŸ’» CODE HINTS (1)
/payment, /user on separate servers
failure_003
Use bulkhead pattern to partition resources so that overload in one subsystem doesn't affect others.
βœ… RULES (2)
Throttle per-subsystem traffic
Separate queues, threads
❌ ANTI-PATTERNS (1)
Shared queue saturating all subsystems
πŸ’» CODE HINTS (1)
queuePerService[userService].enqueue(task)
failure_004
Prevent cascading failure by cutting off failing dependency with circuit breaker.
βœ… RULES (2)
Track error rate and open circuit on threshold
Retry only after cooldown
❌ ANTI-PATTERNS (1)
Retrying continuously into failing dependency
πŸ’» CODE HINTS (1)
if (breaker.isOpen()) return fallback()
failure_005
When backend fails, degrade UI gracefully with offline/cache mode.
βœ… RULES (2)
Detect backend unavailability
Display local cache or fallback message
❌ ANTI-PATTERNS (1)
Uncaught error crashing entire UI
πŸ’» CODE HINTS (1)
if (!data) return <Offline />
failure_006
Design each domain/module as isolated failure domain with local error handling and fallback.
βœ… RULES (2)
Handle errors close to origin
Expose fallback per module
❌ ANTI-PATTERNS (1)
Catching all errors at top-level only
πŸ’» CODE HINTS (1)
try { moduleA.doThing() } catch { moduleA.showFallback() }
πŸ§ͺ VALIDATION
Verify: each module can fail independently, circuit breakers trip on error, UI handles backend failure gracefully, domain failures don't affect unrelated modules.
#18Retry Logic Matrix6 cells12 rules6 anti6 hints
Determines when and how to retry failed operations β€” retry conditions, backoff strategies, and retry budgets.
retry_triggerbackoff_strategybudgetidempotency_requirement
retry_001
When encountering transient errors (e.g. 503), retry with exponential backoff to reduce pressure.
βœ… RULES (2)
Base delay doubles each retry
Apply jitter
❌ ANTI-PATTERNS (1)
Immediate retry without delay
πŸ’» CODE HINTS (1)
delay = base * (2 ** attempt) + random() * jitter
retry_002
When retrying, enforce global or per-user retry budget to avoid overload.
βœ… RULES (2)
Track retry attempts in memory or DB
Reject after limit exceeded
❌ ANTI-PATTERNS (1)
Infinite retries or no limit enforcement
πŸ’» CODE HINTS (1)
if (retryCount > 3) throw new Error('Budget exceeded')
retry_003
Add random jitter to retry delays to prevent thundering herd effect.
βœ… RULES (2)
Use full jitter or decorrelated jitter per retry
Spread out load
❌ ANTI-PATTERNS (1)
Synchronized retries across clients
πŸ’» CODE HINTS (1)
delay = Math.min(cap, random(base, prev * 3))
retry_004
When error is permanent or invalid input (e.g. 400), do not retry.
βœ… RULES (2)
Detect non-retryable status or codes
Abort immediately
❌ ANTI-PATTERNS (1)
Retrying 4xx errors
πŸ’» CODE HINTS (1)
if (status >= 400 && status < 500) return failFast()
retry_005
If circuit breaker is open, skip retries and fail fast.
βœ… RULES (2)
Check breaker state before retry
Only retry when half-open
❌ ANTI-PATTERNS (1)
Retrying blindly through open circuit
πŸ’» CODE HINTS (1)
if (breaker.isOpen()) return fallback()
retry_006
Only retry idempotent operations to avoid duplicate side effects.
βœ… RULES (2)
Mark operations as idempotent or not
Wrap in retry guard
❌ ANTI-PATTERNS (1)
Retrying POST without idempotency key
πŸ’» CODE HINTS (1)
await retry(() => fetch(...), { retries: 3 })
πŸ§ͺ VALIDATION
Verify: retries capped by budget, jitter is applied, non-retryable errors skipped, retries only applied to idempotent operations, circuit breaker state respected.
#19Timeout Strategy Matrix6 cells12 rules6 anti6 hints
Determines how to set, enforce, and cascade timeouts across system boundaries.
timeout_scopeenforcement_methodcascade_behaviorfallback
timeout_001
When enforcing timeout per request, use AbortController to cancel fetch or async task.
βœ… RULES (2)
Set deadline in ms per request
Cancel on timeout and log
❌ ANTI-PATTERNS (1)
Waiting indefinitely for slow request
πŸ’» CODE HINTS (1)
const ctrl = new AbortController(); setTimeout(() => ctrl.abort(), 5000);
timeout_002
Assign timeout per dependency (e.g. DB, API) based on SLA or risk.
βœ… RULES (2)
Tune each dependency individually
Use config-driven values
❌ ANTI-PATTERNS (1)
Single timeout for all external calls
πŸ’» CODE HINTS (1)
config.timeout.db = 4000
timeout_003
When request spans services, propagate remaining timeout in headers.
βœ… RULES (2)
Track remaining budget at each hop
Use request header like X-Timeout-MS
❌ ANTI-PATTERNS (1)
Each service setting new full timeout
πŸ’» CODE HINTS (1)
req.headers['x-timeout-ms'] = remaining
timeout_004
When timeout hits, trigger graceful fallback (e.g. cache, default value).
βœ… RULES (2)
Wrap risky logic in timeout + fallback
Surface fallback reason
❌ ANTI-PATTERNS (1)
Throwing generic error without context
πŸ’» CODE HINTS (1)
await withTimeout(fetchData(), 3000, () => getCached())
timeout_005
Use separate timeouts for connection and read (e.g. socket timeout vs payload read).
βœ… RULES (2)
Define connectTimeout and readTimeout separately
Monitor both durations
❌ ANTI-PATTERNS (1)
Single large timeout for entire lifecycle
πŸ’» CODE HINTS (1)
axios({ timeout: 3000, timeoutErrorMessage: 'Read timeout' })
timeout_006
When all else fails, respond with degraded but valid result to preserve UX.
βœ… RULES (2)
Use stale cache or reduced payload
Return partial success with warning
❌ ANTI-PATTERNS (1)
Cascading failure due to one timeout
πŸ’» CODE HINTS (1)
return { data: cached, warning: 'live fetch timed out' }
πŸ§ͺ VALIDATION
Verify: timeouts per request and dependency are enforced, cascading budgets are propagated, timeouts lead to graceful fallback, long-lived calls are aborted.
#20Resource Lifetime Matrix6 cells12 rules6 anti6 hints
Determines how resources (connections, handles, memory, locks) are acquired, held, and released throughout their lifecycle.
resource_typeacquisitionholding_strategyrelease_trigger
lifetime_001
When working with DB or network connections, use pooling to reuse and cap resource use.
βœ… RULES (2)
Configure max pool size
Release connection after use
❌ ANTI-PATTERNS (1)
Opening new connection per request
πŸ’» CODE HINTS (1)
pool.connect().then(client => { ... client.release(); })
lifetime_002
Always release file handles using try/finally to avoid leaks.
βœ… RULES (2)
Open file in try, close in finally block
Support error handling in between
❌ ANTI-PATTERNS (1)
Opening without closing on error path
πŸ’» CODE HINTS (1)
try { fh = open(); ... } finally { fh.close(); }
lifetime_003
When acquiring locks, set TTL or expiration to avoid deadlock or stale locks.
βœ… RULES (2)
Store lock time and enforce expiry
Release or renew before TTL
❌ ANTI-PATTERNS (1)
Lock without expiration, hanging forever
πŸ’» CODE HINTS (1)
setLock(key, value, { ttl: 30000 })
lifetime_004
When using memory cache, allocate only when accessed (lazy init).
βœ… RULES (2)
Use getOrCreate pattern
Avoid preload unless necessary
❌ ANTI-PATTERNS (1)
Allocating large cache up front unused
πŸ’» CODE HINTS (1)
cache.getOrCreate(key, () => compute())
lifetime_005
Release resources eagerly on shutdown to prevent leaks (e.g. destroy DB pool, flush logs).
βœ… RULES (2)
Listen for SIGTERM/SIGINT
Flush and destroy all managed resources
❌ ANTI-PATTERNS (1)
Leaving resources open on exit
πŸ’» CODE HINTS (1)
process.on('SIGINT', shutdown)
lifetime_006
When memory is bounded, evict cache entries using LRU or TTL policies.
βœ… RULES (2)
Track access timestamps
Evict oldest or expired entries
❌ ANTI-PATTERNS (1)
Unbounded memory growth from uncapped cache
πŸ’» CODE HINTS (1)
if (cache.size > MAX) cache.evictLRU()
πŸ§ͺ VALIDATION
Verify: all resources acquired are released, no memory or handle leaks, locks have TTLs, caches are bounded, shutdown handler releases resources.
#21Memory Responsibility Matrix6 cells12 rules7 anti6 hints
Determines who is responsible for allocating, managing, and freeing memory β€” preventing leaks, bloat, and dangling references.
allocation_ownerlifecyclecleanup_strategymonitoring
memory_001
When a module allocates memory, it must also take responsibility for disposing it explicitly.
βœ… RULES (2)
Always pair allocation with disposal
Never allow allocation without a disposal path
❌ ANTI-PATTERNS (2)
Allocating memory in one layer and disposing it in another (cross-layer responsibility)
Memory retained after module unload
πŸ’» CODE HINTS (1)
const buf = alloc(); try { use(buf); } finally { buf.dispose(); }
memory_002
When memory is scoped to a function or block, dispose automatically on exit.
βœ… RULES (2)
Use 'with' or destructor pattern if language supports it
Ensure memory is released even on exceptions
❌ ANTI-PATTERNS (1)
Allocating resources in function but leaking on early return or error
πŸ’» CODE HINTS (1)
with open_resource() as res: use(res)
memory_003
When observers are cached, use WeakRef so they don't prevent GC of original object.
βœ… RULES (2)
Wrap observer references with WeakRef
Clean up expired weak references periodically
❌ ANTI-PATTERNS (1)
Observer registry holds strong references, preventing GC
πŸ’» CODE HINTS (1)
const registry = new WeakMap();
memory_004
Track memory usage per module and alert if thresholds are exceeded.
βœ… RULES (2)
Set memory budget per module
Use sampling to track peak usage
❌ ANTI-PATTERNS (1)
Allowing uncontrolled growth without tracking
πŸ’» CODE HINTS (1)
memoryTracker.track('upload', buffer.length)
memory_005
When testing, compare heap snapshots before and after to detect memory leaks.
βœ… RULES (2)
Take snapshot before and after test run
Fail test if unreachable memory grows unexpectedly
❌ ANTI-PATTERNS (1)
Tests pass despite growing heap from stale objects
πŸ’» CODE HINTS (1)
heapdump.writeSnapshot('before.heapsnapshot'); ... heapdump.writeSnapshot('after.heapsnapshot');
memory_006
When choosing structures, prefer GC-friendly options that don't create uncollectable chains.
βœ… RULES (2)
Avoid long-lived closures referencing large objects
Use simple, acyclic graphs for cache or lookup
❌ ANTI-PATTERNS (1)
Retaining hidden references through closures or listeners
πŸ’» CODE HINTS (1)
const cache = new Map();
πŸ§ͺ VALIDATION
Verify: all allocations have paired disposals or auto-cleanup, weak references are GC’d, budgets enforced per module, heap growth is bounded during tests.
#22State Isolation Matrix6 cells12 rules6 anti6 hints
Determines how state is isolated between components, modules, and contexts to prevent unintended sharing and cross-contamination.
isolation_levelsharing_mechanismboundary_typeenforcement
state_iso_001
When state is scoped to a single UI component, use local React state or equivalent hook-based isolation.
βœ… RULES (2)
State should reset when component unmounts
Avoid lifting state unless reused externally
❌ ANTI-PATTERNS (1)
Declaring component state in outer scope (leads to shared mutable state)
πŸ’» CODE HINTS (1)
const [value, setValue] = useState(0);
state_iso_002
When isolating module-internal state, use closure-based private storage to prevent external access.
βœ… RULES (2)
Wrap state in function scope
Expose only pure accessors or mutators
❌ ANTI-PATTERNS (1)
Exporting mutable state object directly from module
πŸ’» CODE HINTS (1)
let _state = {}; export function get() { return _state; }
state_iso_003
When isolating shared state across a subtree, use React Context or equivalent provider pattern.
βœ… RULES (2)
Create dedicated provider per domain
Avoid storing large or write-heavy state in context
❌ ANTI-PATTERNS (1)
Putting all global app state in one giant context object
πŸ’» CODE HINTS (1)
const AppContext = createContext();
state_iso_004
When isolating state in parallel environments (e.g. Workers), avoid shared memory and use message passing.
βœ… RULES (2)
Pass structured data via postMessage
Never reference main-thread objects in worker
❌ ANTI-PATTERNS (1)
Sharing JS object across threads using reference
πŸ’» CODE HINTS (1)
worker.postMessage({ type: 'sync' })
state_iso_005
Disallow shared mutable global state via linter or static analysis.
βœ… RULES (2)
Use ESLint rule to ban global mutation
Enforce context-only access for all shared state
❌ ANTI-PATTERNS (1)
Writing to globalThis or window as central state hub
πŸ’» CODE HINTS (1)
// eslint: no-global-assign
state_iso_006
In test environments, reset state between tests to ensure isolation and avoid flakiness.
βœ… RULES (2)
Clear all state between tests
Avoid shared mocks with internal state
❌ ANTI-PATTERNS (1)
State from test A leaking into test B
πŸ’» CODE HINTS (1)
beforeEach(() => resetState())
πŸ§ͺ VALIDATION
Verify: state is not shared across modules or tests unless explicitly scoped, global state changes are blocked, test runs are isolated with fresh state.
#23Concurrency Boundaries Matrix6 cells12 rules6 anti6 hints
Determines where concurrency is allowed, how shared resources are protected, and how race conditions are prevented.
concurrency_modelresource_protectionconflict_resolutionscope
concurrency_001
When using a single-threaded event loop (e.g. Node.js), avoid shared state and block-free design.
βœ… RULES (2)
Use async I/O only
Defer CPU-intensive work to child thread
❌ ANTI-PATTERNS (1)
Blocking operations inside event handlers
πŸ’» CODE HINTS (1)
setTimeout(() => heavyComputation(), 0);
concurrency_002
When using Web Workers or threads, isolate state and communicate via message passing only.
βœ… RULES (2)
Avoid shared memory between threads
Use structured clone or Transferable
❌ ANTI-PATTERNS (1)
Passing object references directly across threads
πŸ’» CODE HINTS (1)
worker.postMessage({ type: 'compute', data });
concurrency_003
When accessing a shared resource, protect it with a mutex or lock to prevent concurrent modification.
βœ… RULES (2)
Acquire lock before access
Ensure lock release on error paths
❌ ANTI-PATTERNS (1)
Concurrent mutation of shared state without locking
πŸ’» CODE HINTS (1)
await mutex.runExclusive(() => { updateState(); });
concurrency_004
When allowing concurrent writes, use version tokens to detect conflicts and reject stale updates.
βœ… RULES (2)
Attach version to entity
Reject update if version mismatch
❌ ANTI-PATTERNS (1)
Blind writes overwriting concurrent updates
πŸ’» CODE HINTS (1)
if (current.version !== input.version) return 409;
concurrency_005
When concurrency causes conflicts, serialize execution per resource using an internal queue.
βœ… RULES (2)
Enqueue task per resource ID
Run one task at a time per key
❌ ANTI-PATTERNS (1)
Multiple parallel writes to same resource without queue
πŸ’» CODE HINTS (1)
await queue[resourceId].push(task)
concurrency_006
When using atomic values, apply compare-and-swap (CAS) to update safely without locks.
βœ… RULES (2)
Read-modify-write must be atomic
Retry on CAS failure
❌ ANTI-PATTERNS (1)
Separate read and write without CAS protection
πŸ’» CODE HINTS (1)
Atomics.compareExchange(mem, index, expected, newVal);
πŸ§ͺ VALIDATION
Verify: all shared resources have appropriate protection, no concurrent writes without guard, all threads use message passing, CAS used when lockless.
#24Deterministic Output Matrix6 cells12 rules6 anti6 hints
Ensures system outputs are reproducible and predictable given the same inputs β€” extending determinism beyond individual functions to full pipelines.
pipeline_scopereproducibility_levelverification_methodcontrol_mechanism
det_out_001
When verifying deterministic output of functions, use snapshot testing to capture exact return values.
βœ… RULES (2)
Store snapshot on first run and compare in CI
Fail tests on diff unless snapshot is updated
❌ ANTI-PATTERNS (1)
Manually comparing JSON stringified output in each test
πŸ’» CODE HINTS (1)
expect(result).toMatchSnapshot()
det_out_002
Ensure builds are reproducible given same source, same inputs β€” produce same artifact bit-for-bit.
βœ… RULES (2)
Disable timestamps and non-deterministic metadata
Hash artifacts and compare in CI
❌ ANTI-PATTERNS (1)
Letting build output depend on current time or machine ID
πŸ’» CODE HINTS (1)
SOURCE_DATE_EPOCH=0 npm run build
det_out_003
Use seeded randomness in tests to ensure predictable data generation.
βœ… RULES (2)
Use same seed across test runs
Log and verify seed used per test
❌ ANTI-PATTERNS (1)
Calling Math.random() without seed during tests
πŸ’» CODE HINTS (1)
faker.seed(12345)
det_out_004
When serializing data (e.g. JSON), use canonical key ordering to ensure consistent output.
βœ… RULES (2)
Sort object keys alphabetically or via schema
Avoid arbitrary key order in JSON.stringify
❌ ANTI-PATTERNS (1)
Serializing plain objects with insertion-order keys in tests
πŸ’» CODE HINTS (1)
canonicalStringify(obj) // stable-stringify or similar
det_out_005
Compare outputs over time with diff tools to detect regressions in deterministic systems.
βœ… RULES (2)
Store golden master output for comparison
Report diff as test failure
❌ ANTI-PATTERNS (1)
Letting regressions ship unnoticed due to lack of diff check
πŸ’» CODE HINTS (1)
diff output.json golden.json
det_out_006
Ensure output does not depend on OS, timezone, locale, or env variables.
βœ… RULES (2)
Pin locale/timezone during output generation
Normalize file paths, line endings, timestamps
❌ ANTI-PATTERNS (1)
Output including current time or system-dependent path separator
πŸ’» CODE HINTS (1)
process.env.TZ = 'UTC';
πŸ§ͺ VALIDATION
Verify: same input always produces same output artifact, snapshot tests pass consistently, canonical formats used, seeded data consistent.
#25Fallback Strategy Matrix6 cells12 rules6 anti6 hints
Determines what happens when the primary path fails β€” fallback selection, degradation levels, and recovery priorities.
fallback_typedegradation_leveltrigger_conditionuser_impact
fallback_001
When API call fails, serve stale cache to avoid total failure.
βœ… RULES (2)
Check cache TTL before using
Log cache usage fallback
❌ ANTI-PATTERNS (1)
Serving expired cache silently without notice
πŸ’» CODE HINTS (1)
if (apiFail) return cache.get(key);
fallback_002
When config value is missing, fallback to a safe default.
βœ… RULES (2)
Define defaults explicitly in schema
Mark all defaulted fields as overrideable
❌ ANTI-PATTERNS (1)
Using undefined as default without logging
πŸ’» CODE HINTS (1)
const retries = config.retries ?? 3;
fallback_003
When repeated errors are detected in a feature, disable it entirely to reduce harm.
βœ… RULES (2)
Track consecutive failures and disable at threshold
Show clear UI messaging to user
❌ ANTI-PATTERNS (1)
Retrying broken feature endlessly
πŸ’» CODE HINTS (1)
if (failCount > 5) featureFlags.disable('checkout')
fallback_004
When backend service is down, serve static HTML as placeholder.
βœ… RULES (2)
Pre-render static versions of key pages
Avoid dynamic content during outage
❌ ANTI-PATTERNS (1)
Attempting SSR with offline backend
πŸ’» CODE HINTS (1)
return fs.readFileSync('fallback.html')
fallback_005
When some dependencies timeout, return partial data with warnings.
βœ… RULES (2)
Include status for each section
Warn users about missing parts
❌ ANTI-PATTERNS (1)
Returning empty response without context
πŸ’» CODE HINTS (1)
return { profile, orders: null, warning: 'Order service timeout' }
fallback_006
When fallback must be triggered manually (e.g. config override), allow admin to flip toggle.
βœ… RULES (2)
Expose admin panel with toggle access
Audit all manual overrides
❌ ANTI-PATTERNS (1)
Allowing silent fallback override without trace
πŸ’» CODE HINTS (1)
if (adminOverrides[feature]) return fallbackMode();
πŸ§ͺ VALIDATION
Verify: fallback activates only when trigger matches, degraded responses are logged, static content serves on failure, manual overrides are tracked and auditable.
#26Feature Toggle Matrix6 cells12 rules6 anti6 hints
Determines how features are toggled on/off at runtime β€” toggle types, lifecycle, cleanup, and testing strategies.
toggle_typelifecyclescopeevaluation_method
toggle_001
When releasing a new feature, wrap it in a temporary toggle that is removed shortly after launch.
βœ… RULES (2)
Set expiration or cleanup task post-launch
Track toggle age in dashboard
❌ ANTI-PATTERNS (1)
Leaving old release toggles in production forever
πŸ’» CODE HINTS (1)
if (flags.newFeature) showNewUI();
toggle_002
When a critical failure occurs, use an ops toggle (kill switch) to disable feature instantly.
βœ… RULES (2)
Expose toggle via admin or ops panel
Log all kill switch activations
❌ ANTI-PATTERNS (1)
Hard-coding kill logic in code without toggle
πŸ’» CODE HINTS (1)
if (opsFlags.disableCheckout) return 503;
toggle_003
When running A/B tests, use an experiment toggle tied to metrics collection and end date.
βœ… RULES (2)
Track experiment cohort via ID
Automatically expire toggle after test
❌ ANTI-PATTERNS (1)
Running experiments without end date
πŸ’» CODE HINTS (1)
if (expGroup === 'B') useVariant();
toggle_004
Use permission toggles to show/hide features based on user roles or entitlements.
βœ… RULES (2)
Check roles before exposing features
Define toggle state per permission level
❌ ANTI-PATTERNS (1)
Relying on UI-only checks without backend enforcement
πŸ’» CODE HINTS (1)
if (user.hasRole('editor')) showEdit();
toggle_005
Enforce maximum toggle age to avoid technical debt from stale flags.
βœ… RULES (2)
Set toggle TTL (e.g. 30 days)
Alert on expired toggles
❌ ANTI-PATTERNS (1)
Toggles lingering for months without cleanup plan
πŸ’» CODE HINTS (1)
toggle.ttl = 30 * 24 * 60 * 60;
toggle_006
Ensure all toggles are tested for both ON and OFF scenarios.
βœ… RULES (2)
Write explicit tests for both toggle states
Avoid assuming toggle default in tests
❌ ANTI-PATTERNS (1)
Missing test for disabled toggle state
πŸ’» CODE HINTS (1)
test('feature ON', () => {...}); test('feature OFF', () => {...});
πŸ§ͺ VALIDATION
Verify: toggles are removed after lifecycle ends, kill switches are accessible in emergencies, test coverage includes toggle ON/OFF, toggles scoped properly.
#27Configuration Hierarchy Matrix6 cells12 rules6 anti6 hints
Determines how configuration values are resolved across multiple sources with clear precedence and override rules.
source_typeprecedence_leveloverride_scopevalidation
config_001
When using env vars, ensure they override config files and defaults.
βœ… RULES (2)
Always resolve env vars last in the chain
Use dotenv or process.env mapping first
❌ ANTI-PATTERNS (1)
Allowing config file to override env var
πŸ’» CODE HINTS (1)
const port = process.env.PORT ?? config.port ?? 3000;
config_002
Use config files (e.g. JSON/YAML) for base configuration with overrides from env/runtime.
βœ… RULES (2)
Load config file before applying overrides
Support hierarchical config per environment
❌ ANTI-PATTERNS (1)
Editing deployed config file directly on server
πŸ’» CODE HINTS (1)
config = loadConfig('config.yaml')
config_003
Allow admin override of config at runtime through secure panel.
βœ… RULES (2)
Protect override path via authentication
Audit all changes and timestamps
❌ ANTI-PATTERNS (1)
Uncontrolled runtime config mutation via API
πŸ’» CODE HINTS (1)
POST /admin/config { key, value }
config_004
Never hardcode secrets or credentials into config files or source.
βœ… RULES (2)
Inject secrets via env vars or vaults
Validate at startup if secrets present
❌ ANTI-PATTERNS (1)
Pushing secret keys to git or config file
πŸ’» CODE HINTS (1)
const token = process.env.JWT_SECRET
config_005
Validate entire configuration schema at startup and reject if invalid.
βœ… RULES (2)
Use schema validator (e.g. Zod, Joi)
Exit process on invalid config
❌ ANTI-PATTERNS (1)
Continuing boot with partial or malformed config
πŸ’» CODE HINTS (1)
z.object({ port: z.number() }).parse(config);
config_006
Version your configuration schema and allow backward-compatible evolution.
βœ… RULES (2)
Add new fields as optional
Never remove or rename without version bump
❌ ANTI-PATTERNS (1)
Changing config shape silently
πŸ’» CODE HINTS (1)
schema_v1, schema_v2
πŸ§ͺ VALIDATION
Verify: configuration resolves in correct order, secrets are never exposed in code, overrides documented, invalid configs rejected at startup.
#28Default Behavior Matrix6 cells12 rules6 anti6 hints
Determines what default values and behaviors apply when no explicit configuration or input is provided.
default_sourcesafety_leveloverridabilitydocumentation
default_001
When access or capability is not explicitly granted, deny it by default for safety.
βœ… RULES (2)
Require explicit allowlist for access
Log all denied attempts
❌ ANTI-PATTERNS (1)
Defaulting to open access unless explicitly blocked
πŸ’» CODE HINTS (1)
if (!user.isAllowed(action)) throw Forbidden();
default_002
When paginating, default to a sensible number of items like 20 for good UX.
βœ… RULES (2)
Document default page size
Allow override via query param
❌ ANTI-PATTERNS (1)
Returning full dataset without pagination if page size not provided
πŸ’» CODE HINTS (1)
const size = req.q.size ?? 20;
default_003
Disallow magic values as defaults β€” force explicitness or document fallback.
βœ… RULES (2)
Replace hardcoded default paths or tokens with config-based ones
Log all fallbacks
❌ ANTI-PATTERNS (1)
Using '/tmp/foo' when config missing, without trace
πŸ’» CODE HINTS (1)
const path = config.path ?? fail('Missing config.path')
default_004
Use documented safe timeout and retry values if not provided by caller.
βœ… RULES (2)
Default timeout = 5s unless stated
Retry = 3 unless stated
❌ ANTI-PATTERNS (1)
Retrying indefinitely due to unset retry config
πŸ’» CODE HINTS (1)
const timeout = input.timeout ?? 5000;
default_005
Default timezone to UTC and locale to en-US if not explicitly set.
βœ… RULES (2)
Normalize all time operations to UTC internally
Format dates using fallback locale
❌ ANTI-PATTERNS (1)
Relying on OS timezone or locale without config
πŸ’» CODE HINTS (1)
process.env.TZ = 'UTC'
default_006
Block any behavior that activates based on undocumented defaults.
βœ… RULES (2)
Test coverage must assert defaults
Static analysis to detect magic defaults
❌ ANTI-PATTERNS (1)
Legacy fallback logic that is undocumented and invisible to devs
πŸ’» CODE HINTS (1)
throw new Error('Missing config.foo')
πŸ§ͺ VALIDATION
Verify: all defaults are documented and overrideable, deny-by-default enforced, no hidden implicit defaults, test assertions validate defaults.
#29Environment Awareness Matrix6 cells12 rules6 anti6 hints
Determines how the system adapts to different environments (dev/staging/prod) without leaking environment-specific logic into core code.
environment_typeadaptation_methodisolation_leveldetection
env_001
When running locally, load environment-specific config from dotenv or local files.
βœ… RULES (2)
Use dotenv per environment file
Never commit .env.local to version control
❌ ANTI-PATTERNS (1)
Hardcoding dev config in source files
πŸ’» CODE HINTS (1)
dotenv.config({ path: `.env.${env}` });
env_002
Enable debug tools (e.g. Redux DevTools) only in development mode.
βœ… RULES (2)
Wrap dev-only tools in environment checks
Exclude from production build
❌ ANTI-PATTERNS (1)
Bundling dev tools into production artifacts
πŸ’» CODE HINTS (1)
if (process.env.NODE_ENV === 'development') enableDebug();
env_003
Enable production-only optimizations like caching, minification, and tree-shaking.
βœ… RULES (2)
Minify assets in build step
Enable caching headers and CDNs
❌ ANTI-PATTERNS (1)
Using non-minified builds in production
πŸ’» CODE HINTS (1)
webpack.mode = 'production'
env_004
Ensure staging mirrors production environment in configuration and deployment.
βœ… RULES (2)
Deploy using same pipeline as prod
Use real integrations with safe data
❌ ANTI-PATTERNS (1)
Mocking critical services in staging
πŸ’» CODE HINTS (1)
deploy --env staging --profile prod
env_005
Avoid environment branching (e.g. if env==='prod') in core logic β€” isolate into config or flags.
βœ… RULES (2)
Move env-specific differences to config files
Use DI or flags instead of branching
❌ ANTI-PATTERNS (1)
if (env === 'prod') return fastLogic(); else return safeLogic();
πŸ’» CODE HINTS (1)
const strategy = config.executionMode
env_006
Use feature flags to toggle behaviors across environments instead of static branching.
βœ… RULES (2)
Read flags from config service or env
Log flag status at startup
❌ ANTI-PATTERNS (1)
Copy-pasting entire blocks for staging vs prod
πŸ’» CODE HINTS (1)
if (flags.useNewFlow) {...}
πŸ§ͺ VALIDATION
Verify: environment-specific logic isolated outside core, production build is optimized, staging mirrors prod, feature flags replace environment branches.
#30Core Abstraction Matrix6 cells12 rules7 anti6 hints
Determines what gets abstracted into reusable core primitives vs what stays as specific implementation β€” preventing both under-abstraction and over-abstraction.
abstraction_levelreusabilitycomplexity_coststability
abs_001
When the same logic is duplicated 3+ times, extract it into a utility function or module.
βœ… RULES (2)
Track copy-paste or pattern matches
Create shared abstraction only after third occurrence
❌ ANTI-PATTERNS (2)
Extracting logic after first duplication only (premature abstraction)
Allowing 5+ copies to live separately
πŸ’» CODE HINTS (1)
function formatPhone(...) {...}
abs_002
When depending on volatile implementation (e.g. external lib), wrap it behind a stable interface.
βœ… RULES (2)
Create interface first, then map implementation inside
Avoid leaking third-party specifics
❌ ANTI-PATTERNS (1)
Exposing raw third-party classes or types from core code
πŸ’» CODE HINTS (1)
interface Cache { get(); set(); } β†’ uses Redis inside
abs_003
Do not abstract prematurely β€” if a pattern is used once, keep it inline.
βœ… RULES (2)
Resist urge to generalize early
Wait for stable duplication signal
❌ ANTI-PATTERNS (1)
Creating factories/helpers for one-time use
πŸ’» CODE HINTS (1)
// inline for now; extract if reused
abs_004
When modeling core domain concepts, use named value objects like Money, Email, or UserId.
βœ… RULES (2)
Encapsulate validation and formatting
Compare by value, not identity
❌ ANTI-PATTERNS (1)
Passing raw strings or primitives through system
πŸ’» CODE HINTS (1)
class Email { constructor(value) { validate(value); } }
abs_005
Place utility abstractions (e.g. date, string, math) in isolated modules separate from domain logic.
βœ… RULES (2)
Group pure utilities by type
Keep utilities free of side effects
❌ ANTI-PATTERNS (1)
Placing utilities inside domain entity files
πŸ’» CODE HINTS (1)
utils/date/parseIso.ts
abs_006
Ensure abstractions don’t leak implementation details (leaky abstraction).
βœ… RULES (2)
Hide internal logic behind clean interface
Avoid passing config objects with irrelevant flags
❌ ANTI-PATTERNS (1)
Abstractions that require knowledge of internals to use correctly
πŸ’» CODE HINTS (1)
interface Storage { save(File): void } // hides cloud/storage choice
πŸ§ͺ VALIDATION
Verify: abstractions reused β‰₯3 times, no premature generalization, value objects replace primitives, volatile dependencies are wrapped, interfaces are stable and leak-free.
β–Ό πŸ“ L2 β€” Language 30 matrices
#31Syntax Tree Matrix6 cells12 rules6 anti6 hints
Determines how abstract syntax trees (AST) are structured, traversed, and used to represent program structure for analysis and transformation.
node_typetraversal_ordermutation_strategyrepresentation
ast_001
When analyzing or transforming expression trees, use depth-first traversal to resolve inner subexpressions first.
βœ… RULES (2)
Visit leaf nodes before parents
Post-order traversal is typical for evaluation
❌ ANTI-PATTERNS (1)
Evaluating parent before child in mathematical AST
πŸ’» CODE HINTS (1)
function traverse(node) { for (c of node.children) traverse(c); process(node); }
ast_002
When inspecting control structures across code blocks, use breadth-first traversal for structure-level analysis.
βœ… RULES (2)
Visit sibling nodes before descending
Use queue to traverse level by level
❌ ANTI-PATTERNS (1)
Using DFS for metrics that span sibling scopes
πŸ’» CODE HINTS (1)
queue = [root]; while (queue.length) { node = queue.shift(); queue.push(...node.children); }
ast_003
When processing literals (strings, numbers), keep AST nodes immutable to avoid accidental mutations during transformation.
βœ… RULES (2)
Mark node properties as readonly
Return new nodes instead of mutating existing
❌ ANTI-PATTERNS (1)
Modifying .value of literal node in-place
πŸ’» CODE HINTS (1)
const newNode = { ...oldNode, value: 'new' }
ast_004
When transforming or analyzing function declarations, use the visitor pattern to encapsulate logic per node type.
βœ… RULES (2)
Implement a visitFunction(node) method
Dispatch per type via accept() or switch
❌ ANTI-PATTERNS (1)
Using one large if/else block to handle all types
πŸ’» CODE HINTS (1)
visitor.visitFunction(node)
ast_005
To enable upward and downward traversal, include parent references in composite AST nodes.
βœ… RULES (2)
Set .parent when building AST
Avoid circular JSON by omitting parent in serialization
❌ ANTI-PATTERNS (1)
Assuming child→parent links exist when not assigned
πŸ’» CODE HINTS (1)
child.parent = current
ast_006
When persisting or transmitting an AST, convert to a JSON-safe serializable format.
βœ… RULES (2)
Strip functions and circular references
Use custom toJSON() method if needed
❌ ANTI-PATTERNS (1)
Calling JSON.stringify on full AST with circular refs
πŸ’» CODE HINTS (1)
JSON.stringify(ast, removeParentRefs)
πŸ§ͺ VALIDATION
Verify: depth/breadth traversal produces correct order, visitor pattern dispatches per node type, immutability enforced, parent-child links maintained, AST is serializable.
#32Parsing Strategy Matrix6 cells12 rules6 anti6 hints
Determines how source text is parsed into structured representations β€” parser types, error recovery, and grammar handling.
parser_typeerror_recoverygrammar_complexityoutput_format
parser_001
When building a hand-written parser for a small DSL, use recursive descent with manual error tracking and user-friendly messages.
βœ… RULES (2)
Write separate function per non-terminal
Bubble up error with position info
❌ ANTI-PATTERNS (1)
Failing silently on unexpected token
πŸ’» CODE HINTS (1)
function parseExpr() { if (match('+')) ... else error('Expected +') }
parser_002
When grammar is ambiguous or left-recursive, use PEG parsers with prioritized choices and automatic backtracking.
βœ… RULES (2)
Order alternatives from most specific to most general
Avoid left recursion by refactor
❌ ANTI-PATTERNS (1)
Grammar with ambiguous alternatives and unordered PEG
πŸ’» CODE HINTS (1)
Start ← If / While / Expr
parser_003
For robust parsing, recover from syntax errors by skipping tokens until a known valid recovery point.
βœ… RULES (2)
Define sync tokens like ; or } to resume
Limit max skip span to avoid infinite loop
❌ ANTI-PATTERNS (1)
Halting parse on first unexpected token
πŸ’» CODE HINTS (1)
while (!isSync(token)) advance();
parser_004
When parsing very large files or data streams, use a streaming parser that emits partial trees or events incrementally.
βœ… RULES (2)
Emit nodes as input is consumed
Avoid buffering entire file
❌ ANTI-PATTERNS (1)
Reading full GB-sized file into memory for parse
πŸ’» CODE HINTS (1)
parser.on('element', node => process(node))
parser_005
To resolve grammar ambiguity (e.g. dangling else), apply disambiguation rules or precedence annotations.
βœ… RULES (2)
Use left/right associativity rules
Define lookahead disambiguation
❌ ANTI-PATTERNS (1)
Grammar that parses same input multiple ways
πŸ’» CODE HINTS (1)
expr = expr '+' term / term
parser_006
To speed up parsing of repeated subtrees (e.g. templates), cache parse results by rule and input span.
βœ… RULES (2)
Use input index range as cache key
Clear cache per file or scope
❌ ANTI-PATTERNS (1)
Reparsing same input unnecessarily
πŸ’» CODE HINTS (1)
cache[key] = parseRule(input, start)
πŸ§ͺ VALIDATION
Verify: each parser strategy aligns with grammar style, error recovery is safe, ambiguity resolved consistently, large inputs streamed.
#33Tokenization Matrix6 cells12 rules6 anti6 hints
Determines how raw text is split into tokens β€” lexer rules, token types, whitespace handling, and streaming tokenization.
tokenizer_typewhitespace_handlingtoken_classificationstreaming_support
token_001
When implementing a simple tokenizer, use regex patterns and skip whitespace tokens by default.
βœ… RULES (2)
Match token types using ordered regex rules
Ignore whitespace unless configured otherwise
❌ ANTI-PATTERNS (1)
Capturing whitespace as generic token by mistake
πŸ’» CODE HINTS (1)
const tokens = input.match(/w+|[{}();]/g)
token_002
When indentation affects program structure (e.g. Python), use a stateful lexer that emits INDENT/DEDENT tokens.
βœ… RULES (2)
Track current indentation level
Emit DEDENT tokens as levels decrease
❌ ANTI-PATTERNS (1)
Flattening all whitespace before lexical analysis
πŸ’» CODE HINTS (1)
emit('INDENT'), emit('DEDENT')
token_003
When tokenizing string literals, recognize escape sequences and store value unescaped.
βœ… RULES (2)
Support standard escapes ( , ", \)
Track unterminated strings as lexer error
❌ ANTI-PATTERNS (1)
Leaving escape characters in token value
πŸ’» CODE HINTS (1)
{ type: 'STRING', value: 'line next' β†’ 'line next' }
token_004
When processing source code, identify and discard comments before token stream is emitted to parser.
βœ… RULES (2)
Recognize line and block comment syntax
Do not emit comment tokens downstream
❌ ANTI-PATTERNS (1)
Passing comment tokens to parser needlessly
πŸ’» CODE HINTS (1)
// comment or /* block */
token_005
When tokenizing large inputs, use a streaming tokenizer that splits input by buffer and handles whitespace-aware tokens incrementally.
βœ… RULES (2)
Buffer N characters, tokenize until whitespace break
Resume with buffer overlap for edge alignment
❌ ANTI-PATTERNS (1)
Loading entire file into memory before tokenizing
πŸ’» CODE HINTS (1)
tokenizer.feed(chunk)
token_006
Classify each token with a precise type to enable downstream semantic analysis and syntax highlighting.
βœ… RULES (2)
Emit token.type field (e.g. 'keyword', 'identifier')
Use consistent tag set for all tokens
❌ ANTI-PATTERNS (1)
Emitting raw strings without classification
πŸ’» CODE HINTS (1)
{ type: 'identifier', value: 'userName' }
πŸ§ͺ VALIDATION
Verify: whitespace handled per rules, escaped strings parsed correctly, comments stripped early, tokens consistently typed, and streaming tokenizers emit incrementally.
#34Expression Evaluation Matrix6 cells12 rules6 anti6 hints
Determines how expressions are evaluated β€” order of operations, lazy vs eager evaluation, and short-circuit behavior.
evaluation_strategyexpression_typeoptimizationerror_handling
expr_eval_001
When evaluating arithmetic expressions, apply eager evaluation to compute all subexpressions immediately.
βœ… RULES (2)
Evaluate left and right operands before applying operator
Respect operator precedence and associativity
❌ ANTI-PATTERNS (1)
Deferring numeric subexpression unnecessarily in math operations
πŸ’» CODE HINTS (1)
const result = (2 + 3) * (4 - 1);
expr_eval_002
When expression includes deferred or potentially unused branches, use lazy evaluation to avoid unnecessary computation.
βœ… RULES (2)
Wrap computation in function or thunk
Only evaluate when value is needed
❌ ANTI-PATTERNS (1)
Eagerly evaluating both branches of if-expression when condition is known
πŸ’» CODE HINTS (1)
const result = condition ? () => heavy() : () => light(); result();
expr_eval_003
When evaluating boolean expressions, apply short-circuit logic to skip right-hand evaluation when result is known from left.
βœ… RULES (2)
If left is false in AND (&&), skip right
If left is true in OR (||), skip right
❌ ANTI-PATTERNS (1)
Evaluating both sides of boolean operator even when left already determines result
πŸ’» CODE HINTS (1)
if (user && user.name) {...}
expr_eval_004
When using ternary operator, ensure only one of the two branches is evaluated based on condition.
βœ… RULES (2)
Use ternary for inline value selection
Avoid side effects in both branches
❌ ANTI-PATTERNS (1)
Putting function calls with side effects in both branches
πŸ’» CODE HINTS (1)
const label = isAdmin ? 'Admin' : 'User';
expr_eval_005
When re-evaluating pure expressions multiple times, apply memoization to cache result.
βœ… RULES (2)
Cache based on input args
Ensure expression is pure (no side effects)
❌ ANTI-PATTERNS (1)
Caching impure or time-sensitive expressions
πŸ’» CODE HINTS (1)
const memo = {}; function fib(n) { if (memo[n]) return memo[n]; ... }
expr_eval_006
When evaluating expressions with possible runtime errors (e.g. division), wrap in try/catch to ensure safe failure.
βœ… RULES (2)
Catch and handle runtime exceptions
Validate inputs before evaluation when possible
❌ ANTI-PATTERNS (1)
Assuming denominator is always non-zero in division
πŸ’» CODE HINTS (1)
try { const result = a / b; } catch (e) { handle(e); }
πŸ§ͺ VALIDATION
Verify: eager evaluation respects precedence, lazy evaluation avoids unnecessary execution, boolean expressions short-circuit correctly, only one ternary branch evaluated, memoization does not re-compute, and runtime errors are caught properly.
#35Operator Precedence Matrix6 cells12 rules6 anti8 hints
Determines how operator precedence and associativity are defined, resolved, and customized in expression parsing.
precedence_levelassociativitycustom_operatorsconflict_resolution
opprec_001
When parsing arithmetic expressions (PEMDAS), apply left-to-right associativity for operators of the same precedence level.
βœ… RULES (2)
Apply PEMDAS rules: (), **, *, /, +, -
Group left-to-right for *, /, +, -
❌ ANTI-PATTERNS (1)
Parsing 'a - b - c' as 'a - (b - c)'
πŸ’» CODE HINTS (1)
const result = a - b - c; // parsed as (a - b) - c
opprec_002
When handling assignment or exponentiation, apply right-to-left associativity for evaluation correctness.
βœ… RULES (2)
Use right-associativity for a = b = c
For a ** b ** c, evaluate rightmost first
❌ ANTI-PATTERNS (1)
Evaluating a = b = c as (a = b) = c
πŸ’» CODE HINTS (2)
const x = y = 10;
const z = 2 ** 3 ** 2; // β†’ 2 ** (3 ** 2) = 512
opprec_003
When defining custom operators (e.g. |> or <=>), assign explicit precedence and associativity.
βœ… RULES (2)
Define precedence level relative to existing operators
Set associativity to avoid ambiguity
❌ ANTI-PATTERNS (1)
Creating custom operators without defined order
πŸ’» CODE HINTS (1)
infixl 5 <=>
opprec_004
When parentheses are present, override normal precedence to evaluate enclosed expression first.
βœ… RULES (2)
Always resolve parentheses before other operators
Support nested parentheses resolution
❌ ANTI-PATTERNS (1)
Ignoring inner parentheses or treating as string
πŸ’» CODE HINTS (1)
const result = (a + b) * c;
opprec_005
When grammar defines ambiguous operator order, resolve using precedence/associativity rules or rewrite grammar.
βœ… RULES (2)
Use precedence climbing or operator precedence table
Rewrite ambiguous grammar rules
❌ ANTI-PATTERNS (1)
Accepting ambiguous parses without resolution
πŸ’» CODE HINTS (1)
expr = expr '+' term / term
opprec_006
Publish and maintain a precedence table for all supported operators for language developers and tool builders.
βœ… RULES (2)
List all operators by precedence and associativity
Update table as new operators added
❌ ANTI-PATTERNS (1)
Leaving precedence rules undocumented or inconsistent
πŸ’» CODE HINTS (2)
| Level | Operator | Assoc |
|-------|----------|--------|
πŸ§ͺ VALIDATION
Verify: operators respect declared precedence and associativity, parentheses override correctly, custom operators parsed with defined precedence, ambiguous cases resolved per spec, and developer-facing docs are accurate.
#36Scope Resolution Matrix6 cells12 rules6 anti6 hints
Determines how variable and function scopes are resolved β€” lexical vs dynamic scoping, scope chains, and shadowing rules.
scope_typeresolution_ordershadowing_policylifetime
scope_001
When using lexical scoping, resolve variable names based on their position in the source code, not the call stack.
βœ… RULES (2)
Look up variables in enclosing scopes at definition time
Use closure to retain outer variables
❌ ANTI-PATTERNS (1)
Expecting inner function to access caller's local variables
πŸ’» CODE HINTS (1)
function outer() { let x = 1; return function inner() { console.log(x); }; }
scope_002
When using function scope (e.g. var), variables are hoisted to the top of their function and can shadow outer variables.
βœ… RULES (2)
Declare variables with var hoist to top of function body
Inner vars shadow outer ones even if declared later
❌ ANTI-PATTERNS (1)
Assuming let/const hoisting works like var
πŸ’» CODE HINTS (1)
function f() { console.log(x); var x = 5; }
scope_003
When using block-scoped variables (let/const), reference them only after declaration to avoid ReferenceError from temporal dead zone.
βœ… RULES (2)
let/const are not accessible before declaration
TDZ applies from block entry to declaration
❌ ANTI-PATTERNS (1)
Accessing let/const before their declaration
πŸ’» CODE HINTS (1)
{ console.log(x); let x = 2; } // ReferenceError
scope_004
When resolving identifiers, follow the scope chain upward from current block to enclosing scopes until found.
βœ… RULES (2)
Look up variables from innermost to outermost scope
Stop when identifier is found in nearest scope
❌ ANTI-PATTERNS (1)
Skipping over inner shadowing declaration
πŸ’» CODE HINTS (1)
function a() { let x = 1; function b() { console.log(x); } b(); }
scope_005
When a variable name is declared in both inner and outer scope, use the inner one (shadowing outer).
βœ… RULES (2)
Nearest scope takes precedence
Outer variable becomes inaccessible in inner scope
❌ ANTI-PATTERNS (1)
Expecting outer variable when inner with same name exists
πŸ’» CODE HINTS (1)
let x = 1; { let x = 2; console.log(x); } // prints 2
scope_006
When a function closes over variables, those variables persist in memory as long as the closure is reachable.
βœ… RULES (2)
Closed-over variables stay alive with closure
Used for encapsulation or delayed execution
❌ ANTI-PATTERNS (1)
Expecting closed-over vars to be garbage collected independently
πŸ’» CODE HINTS (1)
function outer() { let count = 0; return () => count++; }
πŸ§ͺ VALIDATION
Verify: lexical scoping resolves via source structure, function scope hoists vars, block scope enforces TDZ, scope chains lookup inner to outer, shadowing respects inner-first, and closures retain variable lifetime correctly.
#37Variable Lifetime Matrix6 cells12 rules6 anti6 hints
Determines when variables are created, accessible, and destroyed β€” preventing use-after-free, stale references, and memory leaks.
creation_timeaccessibility_windowdestruction_triggerreference_safety
varlife_001
When using let/const in a block, variables are created at block entry but only accessible after declaration due to TDZ.
βœ… RULES (2)
let/const variables exist in memory from block entry
TDZ prohibits access before declaration line
❌ ANTI-PATTERNS (1)
Accessing block-scoped variable before its declaration (ReferenceError)
πŸ’» CODE HINTS (1)
{ console.log(a); let a = 1; } // ReferenceError
varlife_002
When using var inside a function, the variable is hoisted and accessible (as undefined) from the start of the function scope.
βœ… RULES (2)
var declarations hoisted to top of function scope
Accessing before assignment yields undefined
❌ ANTI-PATTERNS (1)
Assuming 'var' blocks TDZ β€” it does not
πŸ’» CODE HINTS (1)
function f() { console.log(x); var x = 2; } // logs undefined
varlife_003
When a closure captures a variable, its lifetime extends beyond the defining scope for as long as the closure is retained.
βœ… RULES (2)
Closure captures retain variables on heap
Garbage collected only after closure is dereferenced
❌ ANTI-PATTERNS (1)
Expecting closure variables to die with outer function return
πŸ’» CODE HINTS (1)
function outer() { let count = 0; return () => count++; }
varlife_004
When declaring global variables, they persist for the lifetime of the page or process and are rarely garbage collected automatically.
βœ… RULES (2)
Global variables are always reachable unless deleted explicitly
Can create memory leaks if used carelessly
❌ ANTI-PATTERNS (1)
Declaring large objects in global scope and not clearing manually
πŸ’» CODE HINTS (1)
window.myCache = {}; // persists until page unload
varlife_005
When variables are declared with let/const in a block, they are automatically destroyed when the block exits (unless captured).
βœ… RULES (2)
Block-scoped variables are eligible for GC once out of scope
Unless closure keeps reference, memory is reclaimed
❌ ANTI-PATTERNS (1)
Assuming block-scoped variables live until function exit
πŸ’» CODE HINTS (1)
{ let temp = compute(); } // temp eligible for GC
varlife_006
When dynamically allocated objects have no more references, they are garbage collected automatically regardless of scope.
βœ… RULES (2)
Memory is reclaimed by GC when object has zero references
Scope is irrelevant once references are gone
❌ ANTI-PATTERNS (1)
Assuming scope alone determines lifetime
πŸ’» CODE HINTS (1)
let obj = { x: 1 }; obj = null; // GC eligible
πŸ§ͺ VALIDATION
Verify: let/const inaccessible during TDZ, var hoisted but undefined, closure variables persist, global vars retained, block vars cleaned after exit, and GC removes dereferenced objects.
#38Closure Behavior Matrix6 cells12 rules6 anti6 hints
Determines how closures capture variables β€” by reference vs by value, stale closure prevention, and memory implications.
capture_modestaleness_riskmemory_impactuse_case
closure_001
When creating closures in JavaScript, variables are captured by reference, meaning changes after closure creation affect the captured value.
βœ… RULES (2)
Closures reflect the latest value of referenced variables
Capture by reference unless reassigned in inner scope
❌ ANTI-PATTERNS (1)
Expecting a snapshot of the variable's value at closure creation
πŸ’» CODE HINTS (1)
let x = 1; const fn = () => console.log(x); x = 2; fn(); // logs 2
closure_002
When using closures inside useEffect without dependency array, variables may go stale and hold outdated references.
βœ… RULES (2)
Always provide up-to-date dependencies in hook array
Consider using refs for mutable values
❌ ANTI-PATTERNS (1)
Using stale variables from closure due to missing deps
πŸ’» CODE HINTS (1)
useEffect(() => { console.log(user.name); }, [user.name]);
closure_003
When creating closures in a loop with var, all closures may reference the same final value unless let is used.
βœ… RULES (2)
Use let for loop counters to create per-iteration binding
Avoid var in closures inside loops
❌ ANTI-PATTERNS (1)
Using var i in for-loop β†’ closures all reference final i
πŸ’» CODE HINTS (1)
for (let i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);
closure_004
When closures retain access to large structures, they can prevent garbage collection and cause memory leaks.
βœ… RULES (2)
Avoid unnecessary captures in long-lived closures
Nullify references when no longer needed
❌ ANTI-PATTERNS (1)
Capturing DOM or large arrays in closures used in event handlers
πŸ’» CODE HINTS (1)
element.addEventListener('click', () => console.log(largeData));
closure_005
When using closures to encapsulate private state, the closure should expose only needed interfaces and avoid leaking internals.
βœ… RULES (2)
Use closures to hide implementation details
Expose limited API via return
❌ ANTI-PATTERNS (1)
Exposing inner state directly without control
πŸ’» CODE HINTS (1)
function counter() { let count = 0; return { inc: () => ++count }; }
closure_006
When closures are no longer needed (e.g. after unmount), dereference variables or cancel timers to allow GC cleanup.
βœ… RULES (2)
Clear timers and remove event listeners on unmount
Set captured variables to null when obsolete
❌ ANTI-PATTERNS (1)
Leaving captured vars alive due to event or interval closures
πŸ’» CODE HINTS (1)
useEffect(() => { const id = setInterval(fn, 1000); return () => clearInterval(id); }, [])
πŸ§ͺ VALIDATION
Verify: closures capture by reference, staleness avoided with dependency arrays, loop closures scoped per iteration, memory not leaked via persistent captures, encapsulation respected, and obsolete closures cleaned.
#39Type Coercion Matrix6 cells12 rules6 anti6 hints
Determines when and how implicit type conversions occur β€” preventing unexpected behavior from loose type handling.
coercion_directionsafety_leveldetection_methodprevention
coercion_001
When converting user input (string) to number, implicit coercion (e.g. via +input) may yield NaN or incorrect values.
βœ… RULES (2)
Always validate input string before coercion
Use Number() or parseFloat() explicitly
❌ ANTI-PATTERNS (1)
Using unary plus on non-numeric input
πŸ’» CODE HINTS (1)
const age = Number(input)
coercion_002
When checking truthiness in conditionals, values like '', 0, null, undefined are treated as falsy β€” may hide bugs.
βœ… RULES (2)
Check explicitly for 0/null if needed
Avoid overloading falsy check with multiple meanings
❌ ANTI-PATTERNS (1)
if (value) {...} without understanding falsy nuances
πŸ’» CODE HINTS (1)
if (value !== null && value !== 0)
coercion_003
When using ==, implicit coercion may yield surprising results β€” prefer === to avoid type conversion.
βœ… RULES (2)
Use === unless coercion is intentional and documented
Avoid relying on type juggling in conditionals
❌ ANTI-PATTERNS (1)
'5' == 5 β†’ true (type mismatch but coerced)
πŸ’» CODE HINTS (1)
if (a === b)
coercion_004
When parsing JSON, numbers and booleans are inferred β€” ensure schema validation to prevent misuse.
βœ… RULES (2)
Validate parsed object types explicitly
Avoid assuming all strings remain strings
❌ ANTI-PATTERNS (1)
Using parsed.value without type check
πŸ’» CODE HINTS (1)
const data = JSON.parse(json); if (typeof data.id === 'number') ...
coercion_005
When clarity is preferred, use explicit casting (e.g. String(), Number(), Boolean()) to avoid unintended coercion.
βœ… RULES (2)
Prefer constructor casting over implicit methods
Use String(num) instead of num + ''
❌ ANTI-PATTERNS (1)
Implicit casting via +, !!, or concatenation
πŸ’» CODE HINTS (1)
const name = String(userInput)
coercion_006
When maintaining large codebases, enforce lint rules to disallow implicit coercion and flag risky patterns.
βœ… RULES (2)
Enable eslint rules: eqeqeq, no-implicit-coercion
Flag +foo, !!bar, obj + '' as issues
❌ ANTI-PATTERNS (1)
Leaving implicit coercion unflagged in review
πŸ’» CODE HINTS (1)
// eslint: 'eqeqeq': 'error', 'no-implicit-coercion': 'error'
πŸ§ͺ VALIDATION
Verify: implicit coercion patterns are identified, risky == use flagged, explicit casting applied when needed, JSON parse values checked, and linter rules enforce safe behavior.
#40Type Safety Matrix6 cells12 rules7 anti6 hints
Determines how type safety is enforced β€” static typing, runtime checks, gradual typing, and type narrowing strategies.
enforcement_levelchecking_timenarrowing_strategystrictness
type_safety_001
When using TypeScript strict mode, enforce type constraints at compile time to eliminate type errors early.
βœ… RULES (2)
Enable strict mode in tsconfig
Avoid implicit any types
❌ ANTI-PATTERNS (2)
Leaving strict mode off (misses type errors)
Using implicit any
πŸ’» CODE HINTS (1)
// tsconfig.json {"compilerOptions": { "strict": true }}
type_safety_002
When inputs come from unknown sources (e.g. API), validate types at runtime using Zod or io-ts.
βœ… RULES (2)
Define runtime schema
Check inputs before use
❌ ANTI-PATTERNS (1)
Assuming external data conforms to static types
πŸ’» CODE HINTS (1)
z.object({ name: z.string() }).parse(input)
type_safety_003
When using union types, narrow types via control flow (e.g. typeof, in, discriminants).
βœ… RULES (2)
Use typeof, instanceof, or discriminant field
Separate logic paths by type
❌ ANTI-PATTERNS (1)
Accessing properties without narrowing first
πŸ’» CODE HINTS (1)
if (typeof x === 'string') { x.toUpperCase() }
type_safety_004
When possible, avoid using 'any' and prefer 'unknown' with refinement.
βœ… RULES (2)
Mark unknown as input and refine before use
Use never to signal unreachable code
❌ ANTI-PATTERNS (1)
Casting everything to any
πŸ’» CODE HINTS (1)
function handle(x: unknown) { if (typeof x === 'string') ... }
type_safety_005
When migrating from JavaScript to TypeScript, adopt gradual typing and annotate incrementally.
βœ… RULES (2)
Use allowJs in tsconfig
Add // @ts-check in JS files
❌ ANTI-PATTERNS (1)
Rewriting everything in one pass
πŸ’» CODE HINTS (1)
// @ts-check function add(a, b) { return a + b }
type_safety_006
When using union types, add a common discriminant field to enable safe type refinement.
βœ… RULES (2)
Use field like kind or type
Switch by tag value to access variant safely
❌ ANTI-PATTERNS (1)
Accessing fields without discriminant
πŸ’» CODE HINTS (1)
switch(obj.kind) { case 'A': obj.value }
πŸ§ͺ VALIDATION
Verify: static types enforced, runtime schema checked, unions narrowed, 'any' avoided, migration smooth, and discriminants used.
#41Generic Handling Matrix6 cells12 rules6 anti6 hints
Determines how generics are used to create reusable type-safe abstractions without losing type information.
generic_scopeconstraint_typeinference_behaviorcomplexity_limit
generic_001
When creating reusable identity-style functions, define generics without constraint to retain full type flexibility.
βœ… RULES (2)
Use <T> and return same T
Preserve literal types when passed
❌ ANTI-PATTERNS (1)
Using 'any' or over-constraining T
πŸ’» CODE HINTS (1)
function identity<T>(value: T): T { return value; }
generic_002
When defining reusable data structures, use generic interfaces with 'extends' constraints to enforce shape.
βœ… RULES (2)
Use <T extends object>
Allow structural typing via interface
❌ ANTI-PATTERNS (1)
Omitting extends leads to invalid usage
πŸ’» CODE HINTS (1)
interface ApiResponse<T extends object> { data: T; status: number; }
generic_003
When limiting T to known keys of another type, use 'extends keyof X' pattern.
βœ… RULES (2)
Bind T extends keyof U
Ensure type-safe property access
❌ ANTI-PATTERNS (1)
Allowing free-form string keys
πŸ’» CODE HINTS (1)
function getValue<T extends keyof U, U>(obj: U, key: T): U[T] { return obj[key]; }
generic_004
When possible, let TypeScript infer generic parameters from function arguments instead of explicit annotation.
βœ… RULES (2)
Omit <T> when TS can infer
Verify that inference maintains correct typing
❌ ANTI-PATTERNS (1)
Unnecessary type annotations on obvious calls
πŸ’» CODE HINTS (1)
const x = identity('hello')
generic_005
When building partial forms of types, use utility types like Partial<T>, Pick<T, K>, or Omit<T, K>.
βœ… RULES (2)
Use Partial for optional version
Use Pick/Omit to refine keys
❌ ANTI-PATTERNS (1)
Manually rewriting types when utility exists
πŸ’» CODE HINTS (1)
type UserPreview = Pick<User, 'id' | 'name'>
generic_006
When defining generics, avoid over-parameterizing with multiple unused type params.
βœ… RULES (2)
Keep generic arity minimal
Add only meaningful type parameters
❌ ANTI-PATTERNS (1)
<T, U, V> where only T is used
πŸ’» CODE HINTS (1)
function log<T>(item: T): void { console.log(item); }
πŸ§ͺ VALIDATION
Verify: generics have valid scope, constraints applied properly, inference works, utility types preferred, and complexity remains minimal.
#42Matrix 042 β€” Type Inference Matrix6 cells18 rules18 anti6 hints
Define how, when, and where type inference should be used or avoided across variables, functions, and data structures for clarity, safety, and maintainability.
inference_scopeexplicit_vs_implicitreadability_tradeofftooling_supporterror_surface_arearefactor_safety
LOCAL_VARIABLE_INFERENCE
When assigning simple values inside a function or block
βœ… RULES (3)
Let the compiler infer obvious types
Avoid explicit types when RHS is self-evident
Prefer const for primitives
❌ ANTI-PATTERNS (3)
Writing type annotations for literal values
Inferring type from complex ternary expression
Using var instead of let/const
πŸ’» CODE HINTS (1)
const count = 42; // inferred as number
FUNCTION_RETURN_TYPE_EXPLICITNESS
When declaring exported or public functions
βœ… RULES (3)
Specify return type explicitly
Let inference occur only internally
Avoid implicit 'any' returns
❌ ANTI-PATTERNS (3)
Relying on inferred return type in libraries
Exposing unstable return shapes
Skipping return keyword accidentally
πŸ’» CODE HINTS (1)
function getUser(): User { return ... }
OBJECT_LITERAL_INFERENCE_LIMITS
When assigning object literals to variables
βœ… RULES (3)
Use type assertion or interface when needed
Avoid inferring types from partial objects
Lock expected shape with as const where appropriate
❌ ANTI-PATTERNS (3)
Allowing excessive flexibility via inferred object
Mutating inferred shape in later code
Passing loose object into API
πŸ’» CODE HINTS (1)
const config: AppConfig = { ... }
GENERIC_FUNCTION_TYPE_HINTING
When defining functions that operate over generics
βœ… RULES (3)
Declare generic parameters explicitly
Avoid over-inference from usage context
Document generic constraints
❌ ANTI-PATTERNS (3)
Letting all types float as 'any'
Skipping generics when using map/filter
Assuming inference handles nested types
πŸ’» CODE HINTS (1)
function identity<T>(value: T): T { return value }
API_INPUT_TYPE_ENFORCEMENT
When consuming API or 3rd-party data
βœ… RULES (3)
Coerce to known schema type
Avoid direct usage without transformation
Prefer zod or schema parsers
❌ ANTI-PATTERNS (3)
Passing inferred response directly to app state
Assuming response always has expected shape
Using optional chaining to mask errors
πŸ’» CODE HINTS (1)
const parsed = schema.parse(response.data)
INFERENCE_FOR_LOOP_AND_CALLBACKS
When iterating collections or using callbacks
βœ… RULES (3)
Allow callback parameter inference
Annotate accumulator or external types
Use readonly/const with inferred loops
❌ ANTI-PATTERNS (3)
Over-specifying internal loop types
Letting map reduce to any
Skipping type guards in callbacks
πŸ’» CODE HINTS (1)
items.map(item => item.name)
πŸ§ͺ VALIDATION
Test inferred types across scope, refactor functions, enforce public return types, and ensure API inference is safely guarded.
#43Matrix 043 β€” Compile-Time vs Run-Time Matrix6 cells18 rules12 anti11 hints
Determines whether a given behavior or check should happen at compile-time or run-time based on safety, performance, and clarity.
evaluation_phasetooling_supportfailure_visibilityperformance_impact
TYPE_CHECK_STATIC
When defining function parameters and return types in TypeScript
βœ… RULES (3)
Use static typing via TypeScript annotations
Enable strict mode for full type safety
Prefer compile-time validation for predictable contracts
❌ ANTI-PATTERNS (2)
Relying solely on runtime checks
Disabling type checks with `any`
πŸ’» CODE HINTS (1)
function add(a: number, b: number): number { return a + b }
RUNTIME_VALIDATION_SCHEMA
When receiving external input (e.g. API, form)
βœ… RULES (3)
Use runtime validators like Zod or Joi
Parse and refine input before use
Log or throw on schema mismatch
❌ ANTI-PATTERNS (2)
Assuming input is trusted
Accessing fields without guard
πŸ’» CODE HINTS (2)
schema.parse(input)
if (!schema.safeParse(data).success) throw Error()
CONST_EVALUATION_BUILD
When evaluating expressions that can be resolved during compilation
βœ… RULES (3)
Mark values with `as const` or `readonly`
Use const enums or inline literals
Avoid recomputing constants at runtime
❌ ANTI-PATTERNS (2)
Computing static values inside runtime functions
Duplicating magic numbers
πŸ’» CODE HINTS (2)
const PI = 3.1415
const MAX_USERS = 100 as const
LAZY_EVAL_DEFERRED_RUNTIME
When a computation is expensive and not always needed
βœ… RULES (3)
Wrap logic in a function or getter
Cache result if deterministic
Ensure side effects are safe and isolated
❌ ANTI-PATTERNS (2)
Running heavy logic unconditionally
Mixing side-effects with lazy logic
πŸ’» CODE HINTS (2)
const data = () => computeExpensive()
let memo = null; if (!memo) memo = compute()
TSC_MACRO_EXPANSION
When using types as compile-time templates (e.g. mapped types)
βœ… RULES (3)
Use keyof, infer, and conditional types
Combine with utility types like Pick, Omit
Document generated type behavior
❌ ANTI-PATTERNS (2)
Trying to reflect type logic into runtime
Overcomplicating inferred types
πŸ’» CODE HINTS (2)
type Keys<T> = keyof T
type IdOnly<T> = Pick<T, 'id'>
RUNTIME_TYPEOF_GUARD
When working with values of unknown or mixed type
βœ… RULES (3)
Use typeof, instanceof, or custom predicate functions
Narrow types before access
Return early if type mismatch
❌ ANTI-PATTERNS (2)
Accessing properties without type guard
Assuming inferred types on unknown values
πŸ’» CODE HINTS (2)
if (typeof x === 'string') { x.toUpperCase() }
if (Array.isArray(val)) val.length
πŸ§ͺ VALIDATION
Verify: compile-time types enforced, schemas validated on input, constants precomputed, lazy logic evaluated safely, type macros expand, runtime guards prevent unsafe access.
#44Macro / Template Matrix6 cells18 rules12 anti7 hints
Determines when and how to use macros or static templates to expand code, types, or behavior at compile-time.
macro_typeexpansion_targetparameter_bindingcompile_time_scope
STATIC_TEMPLATE_LITERAL
When defining code or type variants that follow strict string formats
βœ… RULES (3)
Use TypeScript template literal types for union expansions
Bind prefix/suffix to ensure formatting
Prevent invalid format via inferred constraints
❌ ANTI-PATTERNS (2)
Using plain string without structure
Allowing open string unions with no pattern
πŸ’» CODE HINTS (1)
type Role = `role:${'admin' | 'user'}`
GENERIC_TYPE_TEMPLATE
When multiple types share shape but differ by content
βœ… RULES (3)
Use type parameter T to inject behavior
Keep structure fixed but make internals generic
Compose with mapped or conditional types if needed
❌ ANTI-PATTERNS (2)
Duplicating near-identical types
Using any instead of generic parameters
πŸ’» CODE HINTS (1)
type ApiResponse<T> = { data: T; status: number }
UTILITY_TYPE_COMPOSITION
When needing partial or derived versions of an object type
βœ… RULES (3)
Apply utility types instead of rewriting
Chain them to combine transformations
Prefer utility template over manual omission
❌ ANTI-PATTERNS (2)
Redefining the type manually
Mixing partial and full fields inconsistently
πŸ’» CODE HINTS (2)
Partial<User>
Pick<T, 'id'>
MAPPED_TYPE_GENERATOR
When transforming keys of a type into derived values
βœ… RULES (3)
Use [K in keyof T] syntax
Map to new shape or restriction
Preserve optionality or readonly when required
❌ ANTI-PATTERNS (2)
Iterating keys at runtime instead of type level
Using Record blindly when dynamic shape not desired
πŸ’» CODE HINTS (1)
{ [K in keyof T]: string }
ENUM_LIKE_CONST_OBJECT
When needing an enum-like structure without runtime overhead
βœ… RULES (3)
Define object with as const
Infer keys or values with keyof typeof
Avoid runtime enums if static shape suffices
❌ ANTI-PATTERNS (2)
Declaring TypeScript enums without needing runtime output
Forgetting as const on frozen objects
πŸ’» CODE HINTS (1)
const ROLES = { admin: 'ADMIN', user: 'USER' } as const
MACRO_SAFE_EXPANSION
When using macro-based plugins (e.g. babel-macros, tsc transformers)
βœ… RULES (3)
Apply macros only where readability is preserved
Test generated output as part of CI
Keep fallback path for debugging
❌ ANTI-PATTERNS (2)
Overusing macros in business logic
Embedding side-effects inside macro bodies
πŸ’» CODE HINTS (1)
macro(createStyled('button'))
πŸ§ͺ VALIDATION
Verify: templates expand safely, type reuse is maximized, literal formats enforced, mapped keys correct, macro output readable and testable.
#45AST Transformation Matrix6 cells12 rules6 anti6 hints
Determines how AST nodes are transformed for optimization, transpilation, or code modification β€” safely and reversibly.
transformation_typesafety_guaranteereversibilityscope_of_change
ast_001
When replacing one AST node with another, ensure type compatibility to preserve downstream compilation correctness.
βœ… RULES (2)
Preserve node kind (e.g., Expression -> Expression)
Validate parent compatibility
❌ ANTI-PATTERNS (1)
Replacing expression node with statement node
πŸ’» CODE HINTS (1)
path.replaceWith(t.identifier('x'))
ast_002
When removing a node, ensure its parent AST structure remains valid and relinked correctly.
βœ… RULES (2)
Reparent sibling nodes if needed
Remove from list not just nullify
❌ ANTI-PATTERNS (1)
Leaving orphaned commas or semicolons
πŸ’» CODE HINTS (1)
path.remove()
ast_003
When transforming entire subtree, ensure scope integrity (e.g., no shadowed vars or broken closures).
βœ… RULES (2)
Track scope changes during traversal
Validate rebindings and closures
❌ ANTI-PATTERNS (1)
Transforming without rechecking scope
πŸ’» CODE HINTS (1)
traverse(subtree, visitor)
ast_004
When generating new code, maintain accurate source maps for debugging post-transformation.
βœ… RULES (2)
Emit sourcemap with correct line/column mapping
Test sourcemap correctness via debugger
❌ ANTI-PATTERNS (1)
Omitting sourcemaps in dev builds
πŸ’» CODE HINTS (1)
generate(ast, { sourceMaps: true })
ast_005
When composing multiple transforms, apply them in controlled order to preserve semantic intent.
βœ… RULES (2)
Register transforms in stable order
Avoid overlapping transforms without isolation
❌ ANTI-PATTERNS (1)
Running unordered transforms with side effects
πŸ’» CODE HINTS (1)
applyTransforms([cleanup, rename, simplify])
ast_006
When a transform fails midway, rollback all AST changes safely to previous state.
βœ… RULES (2)
Track changes incrementally for rollback
Wrap in try/catch with state restore
❌ ANTI-PATTERNS (1)
Partially applied AST mutations with no undo
πŸ’» CODE HINTS (1)
try { transform() } catch { rollback() }
πŸ§ͺ VALIDATION
Verify: type-safe node replacements, parent links remain valid, scopes preserved, sourcemaps accurate, transforms composed orderly, rollback protects tree state.
#46Code Generation Matrix6 cells18 rules12 anti7 hints
Determines how and when code should be generated statically, dynamically, or via tooling to optimize maintainability, readability, and scalability.
generation_modetarget_artifacttemplate_sourceruntime_dependency
STATIC_TEMPLATE_GEN
When generating repeated code patterns with predictable shape
βœ… RULES (3)
Define template in source repo
Use compile-time tools (e.g. CLI, build step)
Commit generated output to version control
❌ ANTI-PATTERNS (2)
Generating templates at runtime unnecessarily
Duplicating pattern code manually
πŸ’» CODE HINTS (1)
generateComponent('UserCard')
RUNTIME_FACTORY_GEN
When object shapes must be constructed dynamically based on config
βœ… RULES (3)
Encapsulate logic in factory functions
Pass in schema or config object
Avoid hardcoding if-else blocks
❌ ANTI-PATTERNS (2)
Switching on string keys manually
Building object via inline conditional
πŸ’» CODE HINTS (1)
createInstance(config.type)
TYPE_DRIVEN_GEN
When types dictate the shape of forms, APIs, or serializers
βœ… RULES (3)
Extract metadata from types/interfaces
Use decorators or reflection if needed
Avoid desync between schema and implementation
❌ ANTI-PATTERNS (2)
Manual duplication of type definitions
Ignoring type evolution in generated code
πŸ’» CODE HINTS (1)
generateForm<T>()
SCHEMA_DRIVEN_GEN
When an external schema (e.g. JSON Schema, OpenAPI) defines system shape
βœ… RULES (3)
Validate schema before generation
Map schema nodes to typed artifacts
Version-control schema source
❌ ANTI-PATTERNS (2)
Generating from outdated or invalid schema
Skipping edge cases in schema map
πŸ’» CODE HINTS (2)
openapi-to-client
jsonschema-to-zod
MACRO_EXPAND_GEN
When compile-time macros produce expanded boilerplate
βœ… RULES (3)
Apply macro safely with readable expansion
Test generated code in CI
Fallback to manual if macro fails
❌ ANTI-PATTERNS (2)
Macros hiding side effects
Obscure macro expansions that hinder debug
πŸ’» CODE HINTS (1)
createStyled('button')
HYBRID_GEN_PIPELINE
When combining static and dynamic generation for flexibility
βœ… RULES (3)
Separate static build phase from runtime hooks
Allow overrides via config injection
Document generation boundaries
❌ ANTI-PATTERNS (2)
Tightly coupling static and runtime layers
Obscuring source of generated code
πŸ’» CODE HINTS (1)
loadTemplates(config.mode)
πŸ§ͺ VALIDATION
Verify: code generated in correct phase, templates resolved statically, factories produce runtime-correct objects, type/schema in sync, macro output readable, hybrid pipelines documented.
#47Formatting Rules Matrix6 cells18 rules12 anti7 hints
Determines when and how formatting rules should be enforced to ensure consistency, readability, and tooling interoperability.
indentation_styleline_widthstatement_terminationbracket_placement
CONSISTENT_INDENTATION
When multiple developers edit the same file
βœ… RULES (3)
Use spaces or tabs consistently across the project
Enforce via .editorconfig or formatter
Use 2 or 4 spaces, not mixed
❌ ANTI-PATTERNS (2)
Mixing tabs and spaces
Editor auto-converts indentation
πŸ’» CODE HINTS (1)
// .editorconfig indent_style = space indent_size = 2
MAX_LINE_WIDTH
When code lines exceed readable width in review or diff tools
βœ… RULES (3)
Limit to 80–100 characters per line
Break long expressions over multiple lines
Wrap chained methods or arguments
❌ ANTI-PATTERNS (2)
Single-line objects spanning 200+ characters
Deep nesting in one line
πŸ’» CODE HINTS (1)
print( long_expression + more_data )
TRAILING_SEMICOLONS
When using JavaScript or TypeScript
βœ… RULES (3)
Always include trailing semicolons
Avoid relying on ASI (Automatic Semicolon Insertion)
Lint for missing semicolons
❌ ANTI-PATTERNS (2)
Omitting semicolons on return or break lines
Config allows mixed semicolon usage
πŸ’» CODE HINTS (1)
const x = 1;
BRACE_PLACEMENT_STYLE
When declaring blocks (functions, conditionals)
βœ… RULES (3)
Choose either same-line or next-line brace style
Enforce with Prettier or ESLint
Stick to one style across all files
❌ ANTI-PATTERNS (2)
Inconsistent brace style across methods
Team members auto-fix to different styles
πŸ’» CODE HINTS (1)
function test() { return true; }
IMPORT_SORT_ORDER
When files have multiple import sources
βœ… RULES (3)
Group imports: std libs, third-party, local
Sort alphabetically within groups
Use tools like eslint-plugin-import
❌ ANTI-PATTERNS (2)
Unsorted imports from random modules
Blank lines between related imports
πŸ’» CODE HINTS (1)
import fs from 'fs'; import zlib from 'zlib'; import utils from './utils';
INLINE_VS_MULTILINE_OBJECTS
When declaring objects with multiple key-value pairs
βœ… RULES (3)
Inline only if object fits within line width
Multiline if object has >2 keys or nested structure
Align keys consistently in multiline
❌ ANTI-PATTERNS (2)
Single-line object with nested objects inside
Mixed inline and multiline patterns
πŸ’» CODE HINTS (2)
const user = { id: 1, name: 'Alice' };
const config = { host: 'localhost', port: 3000 };
πŸ§ͺ VALIDATION
Verify: indentation consistent, lines not too long, semicolons enforced, braces placed consistently, imports sorted, and objects formatted according to rule.
#48Matrix 048 β€” Linting Rules Matrix6 cells18 rules18 anti6 hints
Define how to configure, enforce, and manage linting rules to maintain code quality, consistency, and team alignment across projects.
rule_severity_levelrule_scopeauto_fix_capabilityteam_override_policyintegration_pointsuppression_strategy
REQUIRED_CORE_RULES
When ensuring critical quality rules are enforced in all environments
βœ… RULES (3)
Set severity to 'error'
Disallow override at team level
Integrate at commit/pre-push
❌ ANTI-PATTERNS (3)
Marking core rules as warnings
Allowing per-project disablement
Omitting core rules from CI
πŸ’» CODE HINTS (1)
eslint --config .eslintrc.core.json
TEAM_OVERRIDABLE_RULES
When teams need flexibility for local conventions
βœ… RULES (3)
Mark severity as 'warn' by default
Provide override hook in config
Document accepted variants
❌ ANTI-PATTERNS (3)
Blocking commit due to soft preferences
Hardcoding rule values globally
Undocumented overrides
πŸ’» CODE HINTS (1)
extends: ['eslint:recommended', './team-overrides.js']
AUTO_FIXABLE_STYLE_RULES
When applying code style rules that can be corrected automatically
βœ… RULES (3)
Enable auto-fix for all eligible rules
Run lint --fix on save or pre-commit
Avoid stylistic rules that can't auto-fix
❌ ANTI-PATTERNS (3)
Requiring manual fixes for indentation
Mixing fixable and non-fixable rules indistinctly
Overriding auto-fix with manual scripts
πŸ’» CODE HINTS (1)
eslint . --fix
SUPPRESSION_FOR_LEGACY_CODE
When dealing with unmodernized or imported codebases
βœ… RULES (3)
Use inline comments with justification
Suppress by file/line not global config
Track suppressions for cleanup
❌ ANTI-PATTERNS (3)
Disabling rules project-wide for legacy code
No comment context for suppressions
Leaving permanent suppressions
πŸ’» CODE HINTS (1)
// eslint-disable-next-line no-console β€” needed for legacy logging
LINT_INTEGRATION_IN_PIPELINE
When setting up CI/CD or local development workflows
βœ… RULES (3)
Run lint on commit, push, and PR
Fail build on error-severity rules
Publish lint reports to logs
❌ ANTI-PATTERNS (3)
Lint only on dev machines
Allow silent errors in CI
Missing reports on lint outcome
πŸ’» CODE HINTS (1)
lint-staged + GitHub Actions
DOCUMENT_RULE_DECISION_LOGIC
When team chooses to adopt, override, or ignore a rule
βœ… RULES (3)
Document rationale per rule in config
Version control rule decisions
Link to rule guide or example
❌ ANTI-PATTERNS (3)
Changing rules ad-hoc
No written trace of decisions
Inconsistent explanations across projects
πŸ’» CODE HINTS (1)
// rule: no-var β€” enforced to support let/const
πŸ§ͺ VALIDATION
Run test commits with rule violations. Confirm failures, auto-fix behavior, suppression, and override workflows behave as intended across environments.
#49Reserved Words Matrix6 cells18 rules12 anti10 hints
Determines how reserved words are handled to prevent naming collisions, syntactic ambiguity, or runtime errors.
language_modenaming_contextescape_strategyruntime_bindingtooling_conflictscope_level
VAR_RESERVED_JS_STRICT
When declaring variables in strict JavaScript mode
βœ… RULES (3)
Do not use reserved keywords like 'package', 'interface', 'private' as variable names
Enable 'strict mode' to catch early failures
Validate variable names against reserved list
❌ ANTI-PATTERNS (2)
let package = 1; // SyntaxError
var yield = 5; // invalid in strict mode
πŸ’» CODE HINTS (2)
const pkg = 1;
let ifaceName = 'IUser'
PROPERTY_NAME_ESCAPE
When using reserved words as object keys
βœ… RULES (3)
Use string literals as property names
Avoid using dot notation with reserved identifiers
Allow quoted access in schema-driven data
❌ ANTI-PATTERNS (2)
obj.delete = true;
user.function = 'x'
πŸ’» CODE HINTS (2)
obj['delete'] = true;
data['default']
TS_ENUM_CONFLICT_AVOIDANCE
When defining enum members in TypeScript
βœ… RULES (3)
Avoid enum keys named 'class', 'export', 'default'
Use suffix/prefix convention to avoid collision
Configure ESLint with no-reserved-keys plugin if needed
❌ ANTI-PATTERNS (2)
enum Type { class, return }
enum Export { default = 1 }
πŸ’» CODE HINTS (1)
enum TokenType { CLASS_KEY, RETURN_KEY }
SCOPE_SHADOW_RESERVED
When declaring block-level vars inside functions or closures
βœ… RULES (3)
Do not redeclare known identifiers like 'Promise', 'Symbol' in inner scopes
Use linter to detect shadowed reserved names
Scope analysis before name reuse
❌ ANTI-PATTERNS (2)
function() { let Promise = 'X' }
{ const Symbol = 'x' }
πŸ’» CODE HINTS (1)
let customPromise = 'something';
RESERVED_EXPORT_SAFE
When naming exports in a module
βœ… RULES (3)
Avoid exporting identifiers like 'await', 'static', 'globalThis'
Use alias export if necessary
Use build tool warnings to flag danger
❌ ANTI-PATTERNS (2)
export const await = 1;
export default function static() {}
πŸ’» CODE HINTS (2)
export { data as staticData };
export const userValue = 1;
TOOLCHAIN_RESERVED_COMPAT
When using reserved words in filenames, test ids, or component names
βœ… RULES (3)
Avoid using reserved names as file base (e.g. export.ts, package.ts)
Escape or rename test ids if tools use selectors
Validate all identifiers with linter or schema
❌ ANTI-PATTERNS (2)
export.ts as filename
test id='function'
πŸ’» CODE HINTS (2)
test id='funcBtn'
import tokenMap from './export-map'
πŸ§ͺ VALIDATION
Verify: all identifiers pass parser in strict mode, no collisions in object keys or exports, enum and filename names checked, and toolchain accepts generated output.
#50Naming Convention Matrix6 cells18 rules12 anti12 hints
Resolves how names should be formed across variables, functions, types, and files to ensure consistency and reduce ambiguity.
identifier_scopecasing_stylesemantic_prefixproject_layer
CONST_UPPERCASE
When defining global constants or enum-like values
βœ… RULES (3)
Use SCREAMING_SNAKE_CASE for constants
Declare with const and freeze if object
Place at top of module
❌ ANTI-PATTERNS (2)
camelCase for constants
Reassigning a constant object
πŸ’» CODE HINTS (2)
const MAX_RETRIES = 5;
const API_KEYS = Object.freeze({...})
CAMELCASE_VARIABLES
When declaring mutable local variables or function params
βœ… RULES (3)
Use camelCase for local vars
Avoid underscores or uppercase
Descriptive but concise names
❌ ANTI-PATTERNS (2)
snake_case for JS vars
Overly terse like x1, fn
πŸ’» CODE HINTS (2)
let retryCount = 0;
function sendEmail(userId) {}
PASCALCASE_TYPES
When defining interfaces, types, or classes
βœ… RULES (3)
Use PascalCase for all type-like names
Prefix with I only for legacy interfaces
One concept per type name
❌ ANTI-PATTERNS (2)
lowercase type names
Hungarian notation like strUser
πŸ’» CODE HINTS (2)
interface UserProfile { ... }
type OrderStatus = 'PENDING' | 'SHIPPED'
VERB_PREFIX_FUNCTIONS
When naming functions or methods
βœ… RULES (3)
Start with verb (get, set, fetch, handle)
Follow with object or noun
Reflect side-effect if applicable
❌ ANTI-PATTERNS (2)
Noun-only function names
Ambiguous verbs like do, process
πŸ’» CODE HINTS (2)
function fetchUser()
function handleError(err)
KEBAB_FILES
When naming frontend component or utility files
βœ… RULES (3)
Use kebab-case for file names
Reflect component or function purpose
Avoid suffixing with .util or .helper
❌ ANTI-PATTERNS (2)
PascalCase or snake_case files
Generic names like stuff.js
πŸ’» CODE HINTS (2)
user-profile.ts
email-sender.ts
PREFIX_BY_LAYER
When defining domain-specific modules in larger codebases
βœ… RULES (3)
Prefix or suffix names with layer tag (e.g. userService, authMiddleware)
Keep layer tags consistent across app
Avoid repeating module path in name
❌ ANTI-PATTERNS (2)
Flat names like utils.ts everywhere
Ambiguous short names across layers
πŸ’» CODE HINTS (2)
auth-controller.ts
user-repository.ts
πŸ§ͺ VALIDATION
Verify: casing styles match role, prefixes reflect function or layer, file names are predictable, constants stand out, and type/value separation is preserved.
#51Import / Export Matrix6 cells18 rules12 anti8 hints
Determines when to use default vs named imports/exports, and how to structure module boundaries and exposure.
export_styleimport_styletooling_supporttree_shakinginterop_modefile_granularity
DEFAULT_EXPORT_SINGLETON
When exposing a single main function or class from a module
βœ… RULES (3)
Use `export default` for one primary export
Avoid mixing default and named exports in same module
Name file after the default export
❌ ANTI-PATTERNS (2)
Multiple unrelated exports with a default
Anonymous default exports in large files
πŸ’» CODE HINTS (1)
export default function parseCSV() {}
NAMED_EXPORT_MULTIPLE
When exposing multiple utilities or constants
βœ… RULES (3)
Use `export {}` for all items
Avoid default if multiple exports exist
Group related exports in index file
❌ ANTI-PATTERNS (2)
Wildcard re-exports from deep paths
Default export + named mixed
πŸ’» CODE HINTS (2)
export const parse = () => {}
export function validate() {}
INDEX_REEXPORT_MODULE
When consolidating exports from multiple submodules
βœ… RULES (3)
Use `export * from './sub'` only at index.ts
Avoid deep relative imports from consumers
Flatten exports through central module
❌ ANTI-PATTERNS (2)
Re-exporting everything blindly
Circular re-export trees
πŸ’» CODE HINTS (1)
export * from './parser'
IMPORT_ALIASING_CONFLICT
When importing conflicting or same-named modules
βœ… RULES (3)
Use `import * as` or alias syntax
Disambiguate modules with similar symbols
Avoid shadowing built-ins
❌ ANTI-PATTERNS (2)
Bare imports of conflicting names
Renaming after import manually
πŸ’» CODE HINTS (2)
import * as userUtils from './user'
import { parse as parseYAML } from 'yaml'
IMPORT_ORDER_STYLE
When organizing import statements in files
βœ… RULES (3)
Group imports: built-in, external, internal
Sort alphabetically within groups
Separate groups with blank lines
❌ ANTI-PATTERNS (2)
Random import order
Grouped by developer preference only
πŸ’» CODE HINTS (1)
import fs from 'fs'; import lodash from 'lodash'; import utils from './utils'
TYPE_ONLY_IMPORTS
When importing only types in TypeScript
βœ… RULES (3)
Use `import type` when importing interfaces or types
Separate value and type imports
Enable `importsNotUsedAsValues` in tsconfig
❌ ANTI-PATTERNS (2)
Type-only imports as normal imports
Mixed imports with runtime and type
πŸ’» CODE HINTS (1)
import type { User } from './types'
πŸ§ͺ VALIDATION
Verify: default used only for singleton modules, named exports for multi-items, imports sorted and grouped, aliases resolve conflicts, index modules flatten paths, and type-only imports avoid bundling.
#52Module Boundary Matrix6 cells20 rules12 anti6 hints
To define precise language boundaries for splitting code into modules with minimal syntactic leakage.
Import DirectionalityPublic API SurfaceInternal Symbol VisibilityDependency Declaration StyleCross-Module Type SharingLanguage-Level EncapsulationSymbol Resolution Rules
ONE_WAY_IMPORT_ENFORCEMENT
When multiple modules interact and need to maintain directional dependency flow
βœ… RULES (4)
Allow imports only from explicitly lower layers
Disallow any back-imports, even transitively
Log or lint on violations of directionality
Document import hierarchy in README/module spec
❌ ANTI-PATTERNS (2)
Mutual imports between sibling modules
Using dynamic import hacks to bypass static rules
πŸ’» CODE HINTS (1)
Use static analysis tools like `eslint-plugin-import` or custom AST parsers
EXPLICIT_EXPORT_LIST
When a module offers functionality to external consumers
βœ… RULES (4)
Use explicit `export { X, Y }` syntax
Avoid `export *` unless re-exporting from a stable core
Group exports at top/bottom of module
Match exported names to semantic responsibilities
❌ ANTI-PATTERNS (2)
Leaking internal helpers via wildcard exports
Exporting functions that are only used internally
πŸ’» CODE HINTS (1)
Enforce export lists via module-level linter or bundler config
INTERNAL_SCOPE_GUARDING
When a module contains internal helpers or constants
βœ… RULES (3)
Prefix internal-only identifiers with underscore or special marker
Use `private` or equivalent scoping features where available
Never import internal symbols from another module directly
❌ ANTI-PATTERNS (2)
Accessing internal constants across modules
Using reflection or dynamic lookup to bypass encapsulation
πŸ’» CODE HINTS (1)
Encapsulate internal logic in closure or class-local scope
DECLARATIVE_DEPENDENCY_MAPPING
When modules depend on external or shared utilities
βœ… RULES (3)
Declare all imports at top of file, no inline requires
Use centralized dependency map (e.g. `deps.ts`) for shared dependencies
Disallow relative imports beyond N levels
❌ ANTI-PATTERNS (2)
Ad-hoc relative imports across deep folder structures
Undocumented runtime `require()` calls
πŸ’» CODE HINTS (1)
Generate dependency graph from import tree and validate
TYPE_ALIAS_BOUNDARY_CONTROL
When modules share complex types or interfaces
βœ… RULES (3)
Use `type` or `interface` aliases in a shared schema module
Clone types when crossing logical boundaries
Never import private implementation types
❌ ANTI-PATTERNS (2)
Sharing types from concrete classes or implementation details
Re-exporting types from nested modules without audit
πŸ’» CODE HINTS (1)
Use `Pick<>`, `Omit<>` or `Mapped Types` to project safe shapes
ENCAPSULATION_GRAMMAR_ENFORCEMENT
When language syntax offers encapsulation constructs
βœ… RULES (3)
Use `namespace`, `module`, or `package` declarations where applicable
Restrict symbol exposure to public interface only
Disallow access to symbols without declaration in module header
❌ ANTI-PATTERNS (2)
Global namespace pollution
Referencing symbols not declared in module scope
πŸ’» CODE HINTS (1)
Use `export` vs `local` declaration distinction rigorously
πŸ§ͺ VALIDATION
Run static analysis on module graphs and verify no boundary violations, circular imports, or unauthorized symbol leaks exist.
#53Namespace Matrix6 cells18 rules12 anti8 hints
Decides how and when to use namespace boundaries in code to control scope, exposure, and modularity.
namespace_kindvisibilitycollision_avoidancetooling_supportimport_granularityscope_boundary
INTERNAL_MODULE_TS
When organizing multiple related interfaces or constants in TypeScript
βœ… RULES (3)
Use `namespace` keyword in `.ts` only (not `.tsx`) files
Prefer for internal-only usage
Avoid global pollution by not exporting namespace itself
❌ ANTI-PATTERNS (2)
Using namespaces in modules with ES6 imports
Exporting full namespace globally
πŸ’» CODE HINTS (1)
namespace Validation { export interface Rule {} }
FILE_BASED_NAMESPACE
When using ES module system
βœ… RULES (3)
Structure folders to reflect module hierarchy
Avoid nested namespaces in code
Name folders meaningfully (e.g. user/settings)
❌ ANTI-PATTERNS (2)
Manual nested namespaces with export/import
Merging unrelated concepts in same folder
πŸ’» CODE HINTS (1)
import { Settings } from './user/settings'
NAMESPACE_ALIASES_IMPORT
When consuming multiple modules with overlapping symbols
βœ… RULES (3)
Use `import * as alias` for module grouping
Avoid naming collisions by referencing alias directly
Avoid destructuring conflicting names
❌ ANTI-PATTERNS (2)
Using bare import with overlapping names
Renaming each import manually
πŸ’» CODE HINTS (2)
import * as userAPI from './user'
userAPI.getUser()
DECLARATION_MERGING_NS
When extending types or functions with static attachments
βœ… RULES (3)
Declare namespace after function or class
Export shared constants/types within namespace
Avoid circular references inside
❌ ANTI-PATTERNS (2)
Declaring namespace before primary symbol
Merging unrelated logic just to reuse name
πŸ’» CODE HINTS (1)
function log() {} namespace log { export const LEVEL = 'info'; }
GLOBAL_NS_CONTAINMENT
When exposing globals in browser or legacy env
βœ… RULES (3)
Use single root namespace (e.g. window.App)
Assign all exports to namespace explicitly
Avoid polluting window directly
❌ ANTI-PATTERNS (2)
Multiple root namespaces like window.A, window.B
Assigning symbols to window without prefix
πŸ’» CODE HINTS (1)
window.MyApp = { utils: {}, config: {} }
TOOLCHAIN_GENERATED_NS
When using codegen tools (e.g. proto, GraphQL, OpenAPI)
βœ… RULES (3)
Use namespace aliases to group outputs
Do not flatten all generated symbols into global
Version-separate generated APIs if needed
❌ ANTI-PATTERNS (2)
Generated types polluting global TS scope
Mixing versions in same namespace
πŸ’» CODE HINTS (2)
import * as v1 from './generated/v1'
import * as v2 from './generated/v2'
πŸ§ͺ VALIDATION
Verify: namespace boundaries are respected, no conflicts exist across modules, symbol resolution works via aliasing or import, no accidental global exposure, and generated namespaces are encapsulated.
#54Reflection Matrix6 cells18 rules12 anti6 hints
Decide when and how to use reflective programming features safely within a language boundary.
runtime_type_introspectionmetadata_accessdynamic_invocationlanguage_safety_modeltooling_supporttestability
USE_REFLECTION_FOR_DIAGNOSTICS
When debugging or analyzing program state at runtime
βœ… RULES (3)
Limit reflection to logging, error messages, or development tools
Avoid using reflection data in decision-making logic
Ensure fallback behavior exists when reflection fails
❌ ANTI-PATTERNS (2)
Using reflection to branch core business logic
Catching all reflection exceptions silently
πŸ’» CODE HINTS (1)
Use `typeof`, `getType()`, or equivalent for safe diagnostics
ANNOTATION_DRIVEN_ACCESS
When runtime metadata is needed for behavior control
βœ… RULES (3)
Prefer declarative annotations over ad hoc metadata
Validate annotations statically when possible
Document all annotation-triggered behavior clearly
❌ ANTI-PATTERNS (2)
Hardcoding field/method names in reflection calls
Mixing multiple annotation schemas without registry
πŸ’» CODE HINTS (1)
Define central annotation schema in shared module
DYNAMIC_PROXY_USE_CASES
When interface implementations are created at runtime
βœ… RULES (3)
Restrict proxy use to logging, security, or transactions
Ensure proxies are transparent to calling code
Avoid performance-sensitive paths through proxies
❌ ANTI-PATTERNS (2)
Generating proxies inside core loops
Using proxies to fake interface compatibility
πŸ’» CODE HINTS (1)
Use language-native proxy factory methods with memoization
SAFE_DYNAMIC_INVOCATION
When invoking methods or accessing fields dynamically
βœ… RULES (3)
Check method existence before invocation
Use centralized wrapper for reflection access
Fail loudly on reflection miss, unless explicitly optional
❌ ANTI-PATTERNS (2)
Invoking methods without checking signature
Suppressing reflection errors silently
πŸ’» CODE HINTS (1)
Wrap reflection in helper utility with logging
LIMITED_REFLECTION_IN_PRODUCTION
When code is shipped to production environments
βœ… RULES (3)
Compile out or disable reflection-heavy features
Provide fallbacks for non-reflective platforms
Use build-time code generation where possible
❌ ANTI-PATTERNS (2)
Reflection that breaks under obfuscation or minification
Code paths that only work via reflection
πŸ’» CODE HINTS (1)
Generate metadata maps or serializers ahead of time
TESTING_REFLECTION_PATHS
When reflective logic affects application behavior
βœ… RULES (3)
Write explicit unit tests for each reflective path
Use mock metadata inputs in test cases
Validate reflection results under edge cases
❌ ANTI-PATTERNS (2)
Assuming reflection will work in all environments
Skipping tests for dynamically-loaded paths
πŸ’» CODE HINTS (1)
Use meta-testing utilities to simulate runtime structure
πŸ§ͺ VALIDATION
Run tests with reflection turned off or mocked to validate system robustness.
#55Meta-Programming Matrix6 cells18 rules12 anti6 hints
Decide when and how to use meta-programming constructs to generate, transform, or extend code safely.
code_generation_methodmacro_scopecompile_time_vs_runtimetemplate_injection_ruleslanguage_constraintsreadability_and_debuggability
STATIC_TEMPLATE_EXPANSION
When templates or macros generate boilerplate code
βœ… RULES (3)
Limit expansion depth to maintain traceability
Use naming conventions to distinguish generated symbols
Document macro input/output examples near definition
❌ ANTI-PATTERNS (2)
Macros that generate dozens of unrelated declarations
Uncommented template logic with nested conditions
πŸ’» CODE HINTS (1)
Use codegen with inline markers or comments for traceability
CONSTRAINED_RUNTIME_CODEGEN
When code is generated at runtime based on input or environment
βœ… RULES (3)
Validate all input before generating code
Instrument generated code with logging
Restrict dynamic codegen to controlled environments
❌ ANTI-PATTERNS (2)
Eval on user input without sanitization
Codegen that bypasses audit trails
πŸ’» CODE HINTS (1)
Wrap codegen in audit-logging proxy
MACRO_LAYER_SEPARATION
When macros operate across different semantic layers
βœ… RULES (3)
Scope macros to a single architectural layer
Avoid logic injection via macro expansion
Review macro expansion outputs during code review
❌ ANTI-PATTERNS (2)
Macros that mutate both business logic and UI
Cross-layer variable substitution
πŸ’» CODE HINTS (1)
Group macros by layer and prefix accordingly
SAFE_COMPILE_TIME_INJECTION
When injecting code during compilation or build step
βœ… RULES (3)
Use language-supported macros or decorators
Validate generated types using static analysis
Log injected code for review and traceability
❌ ANTI-PATTERNS (2)
Injecting code that disables type checks
Non-deterministic injection behavior
πŸ’» CODE HINTS (1)
Use build scripts that emit annotated code blocks
METADATA_DRIVEN_TEMPLATE_LOGIC
When templates are driven by metadata structures
βœ… RULES (3)
Keep template logic declarative, not imperative
Separate metadata source from template logic
Test templates with sample metadata variants
❌ ANTI-PATTERNS (2)
Embedding business logic in templates
Templates that mutate metadata during rendering
πŸ’» CODE HINTS (1)
Use JSON/YAML schemas to drive template rendering
DEBUGGABLE_METAPROGRAM_STRUCTURES
When generated code must be debugged or traced
βœ… RULES (3)
Emit source maps or equivalent mappings
Provide readable fallbacks for debugging
Tag generated blocks with metadata comments
❌ ANTI-PATTERNS (2)
Obscure error messages due to transformed names
Missing line mappings in stack traces
πŸ’» CODE HINTS (1)
Integrate codegen with IDE tooling and source maps
πŸ§ͺ VALIDATION
Run build and runtime tests with logging enabled to confirm generated code structure and safety.
#56Code Injection Matrix6 cells18 rules12 anti6 hints
Define safe patterns and boundaries for injecting code dynamically or at build-time into application structures.
injection_target_typetiming_of_injectionsource_of_injected_codemechanism_usedsecurity_sanitization_levelobservability_requirements
SAFE_STRING_TEMPLATE_INJECTION
When injecting strings into templated source files
βœ… RULES (3)
Use template delimiters that prevent accidental escapes
Escape all dynamic content before injection
Keep injected data separate from logic-bearing content
❌ ANTI-PATTERNS (2)
Injecting raw user input into templates
Using string concatenation to build source files
πŸ’» CODE HINTS (1)
Use tagged templates or interpolation-safe engines
RUNTIME_FUNCTION_BODY_INJECTION
When generating functions on the fly
βœ… RULES (3)
Limit injected logic to small, reviewed units
Wrap injected logic with standard entry/exit markers
Log all injections to centralized tracing system
❌ ANTI-PATTERNS (2)
Dynamically creating full modules at runtime
Injecting logic without test coverage
πŸ’» CODE HINTS (1)
Use Function constructor with well-audited input paths
CONFIG_DRIVEN_BUILD_INJECTION
When configuration files define what gets built
βœ… RULES (3)
Treat configs as declarative inputs, not code
Map config keys to whitelisted injection points
Validate configs against a formal schema
❌ ANTI-PATTERNS (2)
Allowing executable code inside config values
Overriding internal module behavior via config
πŸ’» CODE HINTS (1)
Use schema validators and inject via codegen only
SANITIZED_USER_SCRIPT_EXECUTION
When allowing users to inject or submit scripts
βœ… RULES (3)
Run scripts in sandboxed environments
Pre-parse and audit all injected scripts
Impose time/memory execution limits
❌ ANTI-PATTERNS (2)
Running scripts with full access to system APIs
No limits on recursive or infinite execution
πŸ’» CODE HINTS (1)
Use Web Workers or VM sandbox containers
INJECTION_WITH_OBSERVABILITY_TAGS
When injected code needs to be monitored post-deployment
βœ… RULES (3)
Tag all injected blocks with source identifier
Route runtime behavior through observable hooks
Record injection metadata for rollback/debugging
❌ ANTI-PATTERNS (2)
Opaque code blocks with no provenance
Silent injection from unknown sources
πŸ’» CODE HINTS (1)
Use build macros to inject trace IDs or source comments
AUDITABLE_PLUGIN_EXTENSION
When injecting behavior via plugins or external modules
βœ… RULES (3)
Require manifest for each plugin declaring capabilities
Enforce API contracts between host and plugin
Log plugin registration and lifecycle events
❌ ANTI-PATTERNS (2)
Dynamically loading plugins with unchecked privileges
No versioning or capability declaration for plugins
πŸ’» CODE HINTS (1)
Implement plugin loader with strict interface typing
πŸ§ͺ VALIDATION
Inject test stubs at each injection point and validate system behavior, audit logs, and rollback capability.
#57Dynamic Evaluation Matrix6 cells18 rules12 anti6 hints
Define boundaries, patterns, and safety rules for using dynamic evaluation in code execution.
evaluation_methodsource_of_codeexecution_contextsafety_guardsobservability_hooksperformance_constraints
SANDBOXED_EVAL_FOR_EXPRESSION
When evaluating user-defined expressions at runtime
βœ… RULES (3)
Limit evaluation scope to arithmetic or declarative expressions
Use whitelists for allowed operations and symbols
Run in isolated environment with no access to global state
❌ ANTI-PATTERNS (2)
Evaluating full code blocks from user input
Allowing eval access to runtime internals
πŸ’» CODE HINTS (1)
Use libraries like expr-eval, not raw eval
CONTEXT_BOUND_SCRIPT_EXECUTION
When executing small scripts within defined application contexts
βœ… RULES (3)
Inject only scoped APIs, no full runtime exposure
Timeout and resource-limit script execution
Audit script source and changes
❌ ANTI-PATTERNS (2)
Running scripts with unrestricted context
Skipping audit trails for script changes
πŸ’» CODE HINTS (1)
Use VM contexts with predefined API interfaces
CONTROLLED_BUILD_TIME_EVAL
When performing dynamic evaluation during build or compile phase
βœ… RULES (3)
Cache eval results to avoid build-time nondeterminism
Fail builds on unsafe eval attempts
Log eval source and output during CI
❌ ANTI-PATTERNS (2)
Using eval to bypass static checks
Evaluating content from external, unauthenticated sources
πŸ’» CODE HINTS (1)
Inject constants via compile-time macros
OBSERVABLE_EVAL_WRAPPERS
When evaluation is performed dynamically in long-lived processes
βœ… RULES (3)
Wrap eval calls with logging and metrics
Track origin of evaluated code
Expose eval entry points to observability stack
❌ ANTI-PATTERNS (2)
Blind eval usage in production services
No logging for dynamically generated code paths
πŸ’» CODE HINTS (1)
Use wrapper functions with tracing hooks
USER_SCRIPT_POLICY_ENFORCEMENT
When users are allowed to submit code for evaluation
βœ… RULES (3)
Check scripts against static and behavioral policies
Deny network, file, or unsafe system access
Isolate user scripts with per-tenant boundaries
❌ ANTI-PATTERNS (2)
Evaluating user code without sandboxing
Policy checks after script execution
πŸ’» CODE HINTS (1)
Run user scripts in jailed containers or browser sandboxes
PERF_BOUND_EVAL_SCENARIOS
When dynamic evaluation is used in high-frequency or critical paths
βœ… RULES (3)
Benchmark eval overhead in real conditions
Use caching or JIT compilation for stable scripts
Detect eval hotspots during profiling
❌ ANTI-PATTERNS (2)
Frequent re-eval of the same expression
Eval inside tight loops without caching
πŸ’» CODE HINTS (1)
Pre-compile expressions or use memoization wrappers
πŸ§ͺ VALIDATION
Replace eval paths with test stubs and observe system behavior under load and policy violations.
#58Static Analysis Matrix6 cells18 rules12 anti6 hints
Define how and when to apply static analysis tools to catch issues before runtime.
analysis_scopegranularity_leveltooling_integrationsignal_to_noise_balancedeveloper_feedback_cyclepolicy_enforcement_level
PRE_COMMIT_LINTING
When developers make code changes locally
βœ… RULES (3)
Run fast linters before code is committed
Block commit on high-severity violations
Auto-fix minor issues when safe to do so
❌ ANTI-PATTERNS (2)
Linting only after pushing to remote
Allowing noisy or slow pre-commit hooks
πŸ’» CODE HINTS (1)
Use tools like ESLint, Prettier, or Flake8 with pre-commit hooks
CI_STATIC_ANALYSIS_PIPELINE
When code is pushed to a shared repository
βœ… RULES (3)
Run full static analysis on each pull request
Fail CI on policy-violating issues
Store results for historical tracking
❌ ANTI-PATTERNS (2)
Running different tools locally and in CI
Ignoring analysis failures in CI
πŸ’» CODE HINTS (1)
Integrate tools like SonarQube or CodeQL into CI workflows
IDE_INTEGRATED_FEEDBACK
When developers are actively writing code
βœ… RULES (3)
Show inline warnings and suggestions
Enable auto-completion based on type analysis
Don’t interrupt user with blocking errors during typing
❌ ANTI-PATTERNS (2)
Requiring build to see static errors
Overwhelming UI with unfiltered messages
πŸ’» CODE HINTS (1)
Use language servers (LSPs) for real-time diagnostics
BASELINE_DRIVEN_WARNINGS
When legacy codebases generate too many warnings
βœ… RULES (3)
Capture current state as baseline
Only block regressions beyond baseline
Track warning trends over time
❌ ANTI-PATTERNS (2)
Trying to fix all legacy issues in one go
Ignoring large volumes of static warnings permanently
πŸ’» CODE HINTS (1)
Use warning baselines with suppression annotations
POLICY_ENFORCED_RULESETS
When organization mandates code safety or compliance
βœ… RULES (3)
Tag rules as β€˜must-fix’ vs β€˜nice-to-fix’
Make β€˜must-fix’ issues block merges
Periodically audit ruleset relevance
❌ ANTI-PATTERNS (2)
Treating all rules with equal severity
Disabling rules arbitrarily in code
πŸ’» CODE HINTS (1)
Use tiered severity levels in analysis configs
MULTI_LANGUAGE_ANALYSIS_SUPPORT
When working across multiple programming languages
βœ… RULES (3)
Use polyglot tools or aggregate reports
Normalize severity levels across tools
Ensure consistent CI integration per language
❌ ANTI-PATTERNS (2)
Running isolated tools per language with no aggregation
Allowing gaps in enforcement in less-used languages
πŸ’» CODE HINTS (1)
Use frameworks like Semgrep, Sonar, or custom aggregators
πŸ§ͺ VALIDATION
Inject known violations in test branches and confirm detection, blocking, or reporting behavior matches policy.
#59Transpilation Matrix6 cells18 rules12 anti6 hints
Define when and how to use transpilation to bridge language or syntax differences safely and transparently.
source_languagetarget_languagefeature_support_alignmenttoolchain_integrationdebugging_supportbuild_performance_impact
LANGUAGE_VERSION_BACKPORTING
When newer language features are not supported in target environments
βœ… RULES (3)
Only transpile syntax, not semantics
Match target runtime capabilities explicitly
Annotate backported sections with compatibility markers
❌ ANTI-PATTERNS (2)
Assuming transpilation will polyfill runtime behavior
Using untested features on older runtimes
πŸ’» CODE HINTS (1)
Use Babel presets like `@babel/preset-env` with target settings
CROSS_LANGUAGE_TARGETING
When code is written in one language but must run in another
βœ… RULES (3)
Choose transpilers that preserve semantics, not just syntax
Validate type and memory model compatibility
Provide bridge libraries for standard APIs
❌ ANTI-PATTERNS (2)
Blindly transpiling between structurally dissimilar languages
Relying on auto-generated glue code without audit
πŸ’» CODE HINTS (1)
Use tools like TypeScript-to-C, JS-to-WASM with interface bindings
DIFFERENTIAL_COMPILATION_TARGETS
When the same codebase targets multiple environments
βœ… RULES (3)
Use environment markers in code and build config
Avoid inline environment-specific hacks
Log final build target and feature flags
❌ ANTI-PATTERNS (2)
Using `if` conditions with environment variables inside logic
Manually editing build outputs per target
πŸ’» CODE HINTS (1)
Use conditional compilation macros or build-time flags
SOURCE_MAP_ALIGNMENT
When debugging transpiled code in production or dev tools
βœ… RULES (3)
Generate source maps for all transpiled files
Keep map references consistent across environments
Test source maps against real stack traces
❌ ANTI-PATTERNS (2)
Deploying without source maps
Mismatched versions between code and source maps
πŸ’» CODE HINTS (1)
Use `devtool: source-map` or equivalent in bundler config
TOOLCHAIN_INTEGRATION_CONSISTENCY
When integrating transpilers into dev and CI environments
βœ… RULES (3)
Lock transpiler versions in project config
Run identical toolchains locally and in CI
Cache transpilation results when possible
❌ ANTI-PATTERNS (2)
Version drift between developer and CI environments
Manual transpilation steps without automation
πŸ’» CODE HINTS (1)
Pin tool versions in package.json or CI workflows
TRANSPILATION_COST_ANALYSIS
When deciding whether to transpile large codebases
βœ… RULES (3)
Benchmark build times before and after transpilation
Monitor bundle size impact
Track developer feedback on workflow changes
❌ ANTI-PATTERNS (2)
Adding transpilation steps without measuring cost
Ignoring developer tooling performance degradation
πŸ’» CODE HINTS (1)
Use incremental builds and cache-aware compilers
πŸ§ͺ VALIDATION
Compare source and transpiled outputs across all environments and validate source maps and feature compatibility.
#60Language Interop Matrix6 cells18 rules12 anti8 hints
Determines how to interoperate safely and predictably between multiple languages in a single codebase or pipeline.
interop_directiontype_representationbinding_approacherror_translationruntime_contractbuild_toolchain
CALL_JS_FROM_PY
When invoking JavaScript functions from Python
βœ… RULES (3)
Use node bindings like PyNode or Eel
Serialize data using JSON only
Restrict JS to sandboxed scope
❌ ANTI-PATTERNS (2)
Direct eval of JS from Python strings
Implicit data coercion across bridge
πŸ’» CODE HINTS (1)
eel.expose(func); eel.someJSFunc()
CALL_RUST_FROM_TS
When calling high-perf logic written in Rust from a TypeScript app
βœ… RULES (3)
Use WebAssembly with type-safe bindings
Ensure memory-safe data transfer via buffer or struct
Use wasm-bindgen for TS support
❌ ANTI-PATTERNS (2)
Calling Rust via shell commands
Passing untyped blobs
πŸ’» CODE HINTS (2)
wasm-pack build
import * as math from 'pkg' // wasm
SHARE_TYPES_TS_JAVA
When a TS frontend and Java backend share data models
βœ… RULES (3)
Generate types from single schema (e.g. OpenAPI, GraphQL)
Use codegen tools like openapi-generator or GraphQL Codegen
Avoid parallel handwritten definitions
❌ ANTI-PATTERNS (2)
Manually duplicating model fields
Mismatch in enum variants
πŸ’» CODE HINTS (1)
openapi-generator-cli generate -g typescript-fetch
CALL_PY_FROM_TS
When frontend TS triggers AI or data ops in Python
βœ… RULES (3)
Expose Python via HTTP or WebSocket API
Use JSON as transport format
Log and trace request ID end-to-end
❌ ANTI-PATTERNS (2)
Running Python via shell from browser
Mixing binary formats ad hoc
πŸ’» CODE HINTS (1)
fetch('/predict', { method: 'POST', body: JSON.stringify(input) })
ISOLATED_INTEROP_VIA_FFI
When mixing languages in backend (e.g. C in Go)
βœ… RULES (3)
Use cgo, JNI, or ctypes with strict contract
Wrap native calls with retry/fallback
Guard FFI boundary with typed interface
❌ ANTI-PATTERNS (2)
Direct pointer passing without copy
Lack of bounds checks
πŸ’» CODE HINTS (1)
//export myFunction func myFunction() C.int
CONTRACT_VALIDATION_AT_BOUNDARY
When transferring data between languages
βœ… RULES (3)
Add schema validation at interop boundary
Prefer typed schema (e.g. JSON Schema, Protobuf)
Fail fast on mismatch
❌ ANTI-PATTERNS (2)
Blind parsing of input without validation
Assuming source language guarantees
πŸ’» CODE HINTS (2)
ajv.validate(schema, data)
protobufjs.decode(buffer)
πŸ§ͺ VALIDATION
Verify: interop boundaries guarded, schemas enforced, memory safe across bridge, runtime errors surfaced clearly, and types consistent across lang boundary.
β–Ό πŸ—„οΈ L3 β€” Data 30 matrices
#61Primitive Data Types Matrix6 cells12 rules6 anti6 hints
Determines when to use primitive types (string, number, boolean) vs domain types, how to handle null/undefined/empty, and what boundaries apply to each primitive.
primitive_typenullabilityboundarydomain_wrapping
prim_001
When using string fields, apply max length limits to prevent abuse and optimize storage.
βœ… RULES (2)
Document length constraints in schema
Reject input exceeding max length
❌ ANTI-PATTERNS (1)
Accepting unbounded strings in public APIs
πŸ’» CODE HINTS (1)
z.string().max(255)
prim_002
When using numeric types, define valid min/max ranges and precision.
βœ… RULES (2)
Use int vs float intentionally
Validate ranges in schema and runtime
❌ ANTI-PATTERNS (1)
Storing monetary values as float without precision enforcement
πŸ’» CODE HINTS (1)
z.number().min(0).max(10000)
prim_003
Boolean fields should be named with is/has/should prefixes for clarity.
βœ… RULES (2)
Use semantic naming that implies boolean nature
Avoid negated names like isNotX
❌ ANTI-PATTERNS (1)
Fields named active = false β€” unclear semantics
πŸ’» CODE HINTS (1)
hasAccess, isEnabled
prim_004
Define clear semantics for null, undefined, and empty string β€” do not treat them as equivalent.
βœ… RULES (2)
Distinguish between unset (undefined), cleared (null), and empty string
Validate presence intentionally
❌ ANTI-PATTERNS (1)
Treating all falsy values as identical
πŸ’» CODE HINTS (1)
if (value === undefined) β†’ not sent
prim_005
Avoid using magic numeric values as sentinels β€” use explicit enums or wrappers.
βœ… RULES (2)
Replace -1, 9999, etc. with named constants or status enums
Document meaning of all numeric codes
❌ ANTI-PATTERNS (1)
Using -1 to mean not found without documentation
πŸ’» CODE HINTS (1)
enum Status { Missing = -1 }
prim_006
Wrap important primitives like Email or Phone in domain-specific value objects for validation and clarity.
βœ… RULES (2)
Encapsulate format checks and equality logic
Avoid passing raw strings through layers
❌ ANTI-PATTERNS (1)
Using 'string' as type for email everywhere
πŸ’» CODE HINTS (1)
class Email { constructor(value: string) { validate(value); } }
πŸ§ͺ VALIDATION
Verify: all primitives have documented boundaries, string lengths and number ranges enforced, no unvalidated nulls, magic values are replaced by explicit types.
#62Composite Data Structures Matrix6 cells12 rules6 anti9 hints
Determines how simple data types combine into complex structures β€” arrays, maps, nested objects, trees, and graphs for linking terms to rich data objects.
structure_typenesting_depthaccess_patternmutability
cds_001
When maintaining an ordered list of homogeneous items, use a flat array with predictable index-based access.
βœ… RULES (2)
Use numeric indices for iteration
Preserve order during mutation (e.g. push, pop)
❌ ANTI-PATTERNS (1)
Using object keys for sequential access
πŸ’» CODE HINTS (2)
const items = ['a', 'b', 'c'];
items[1] // 'b'
cds_002
When needing efficient lookup by unique identifier, use a key-value map structure.
βœ… RULES (2)
Use keys as unique IDs
Access via constant-time key reference
❌ ANTI-PATTERNS (1)
Searching array linearly for matching ID
πŸ’» CODE HINTS (2)
const userMap = { '42': {name: 'Alice'} };
userMap['42'].name
cds_003
When modeling entities with nested sub-entities (e.g. user.address.city), use a multi-level object.
βœ… RULES (2)
Structure data hierarchically
Use optional chaining for deep access
❌ ANTI-PATTERNS (1)
Flattening nested entities into flat key-value pairs
πŸ’» CODE HINTS (1)
user.address?.city
cds_004
When data has a parent-child hierarchy (e.g. menus, comments), use a tree structure with recursive depth.
βœ… RULES (2)
Each node contains children[]
Traverse recursively or with DFS/BFS
❌ ANTI-PATTERNS (1)
Representing hierarchy via flat arrays only with parentId fields
πŸ’» CODE HINTS (1)
function traverse(node) { for (let c of node.children) traverse(c); }
cds_005
When data items reference each other in many-to-many fashion (e.g. social networks), use a graph with arbitrary links.
βœ… RULES (2)
Track nodes and adjacency list or matrix
Avoid cycles if graph must be DAG
❌ ANTI-PATTERNS (1)
Duplicating linked data instead of referencing
πŸ’» CODE HINTS (1)
const graph = { A: ['B', 'C'], B: ['C'], C: [] };
cds_006
When representing fixed-length heterogeneous values (e.g. [string, number]), use typed tuples for positional access and typing.
βœ… RULES (2)
Define types per index position
Restrict mutations to allowed types and length
❌ ANTI-PATTERNS (1)
Using arrays with variable length and mixed types without tuple typing
πŸ’» CODE HINTS (2)
type UserTuple = [string, number];
const user: UserTuple = ['Alice', 42];
πŸ§ͺ VALIDATION
Verify: structure is appropriate for data relationships β€” flat for ordered items, map for lookups, nested for hierarchy, tree for parent-child, graph for links, tuple for fixed heterogeneity.
#63Matrix 063 β€” Immutable Data Matrix6 cells18 rules18 anti6 hints
Define when and how to enforce immutability on data structures to prevent unintended mutation, simplify reasoning, and improve concurrency safety.
immutability_scopeenforcement_mechanismcopy_strategyperformance_impactlanguage_supportnested_vs_shallow
SHALLOW_IMMUTABILITY_IN_COMPONENTS
When managing state in UI components
βœ… RULES (3)
Freeze top-level object or use readonly types
Rely on structural sharing for updates
Use shallow comparison for diffing
❌ ANTI-PATTERNS (3)
Mutating props directly
Relying on deep cloning for every update
Bypassing immutability via references
πŸ’» CODE HINTS (1)
Object.freeze(obj) or {...obj, key: newValue}
DEEP_IMMUTABILITY_IN_DOMAIN_MODELS
When working with core domain entities in shared libraries
βœ… RULES (3)
Use recursive freezing or generated readonly types
Enforce immutability at type level
Avoid exposing internal structure
❌ ANTI-PATTERNS (3)
Exposing mutable fields from value objects
Assuming shallow freeze suffices
Allowing downstream mutation
πŸ’» CODE HINTS (1)
Readonly<T> recursively or Object.freezeDeep(obj)
COPY_ON_WRITE_FOR_STATE_MANAGEMENT
When using Redux or similar state containers
βœ… RULES (3)
Never mutate state directly
Create new objects on change
Use Immer or equivalent for ergonomics
❌ ANTI-PATTERNS (3)
Mutating draft state without Immer
Returning same reference after modification
Disabling immutability checks in dev mode
πŸ’» CODE HINTS (1)
state => ({ ...state, value: x }) or produce(draft => { draft.value = x })
ENFORCED_IMMUTABILITY_VIA_TYPES
When working in TypeScript or typed environments
βœ… RULES (3)
Use Readonly<T> and const assertions
Prefer tuples over arrays when possible
Avoid any type leakage in APIs
❌ ANTI-PATTERNS (3)
Using 'any' or untyped returns
Mutating readonly fields via casting
Violating const context
πŸ’» CODE HINTS (1)
const user = {name: 'a'} as const; ReadonlyArray<T>
IMMUTABLE_COLLECTION_LIBRARIES
When handling large data structures with performance needs
βœ… RULES (3)
Leverage libraries like Immutable.js, Mori, or immer
Use structural sharing to avoid full copies
Benchmark memory tradeoffs
❌ ANTI-PATTERNS (3)
Deep cloning large trees
Using JSON.parse(JSON.stringify(obj))
Forgetting equality semantics of library types
πŸ’» CODE HINTS (1)
Map().set('x', 1); List([...])
SAFE_DEFAULTS_FOR_EXTERNAL_INPUTS
When ingesting data from APIs or user input
βœ… RULES (3)
Clone or validate input objects on arrival
Expose readonly views to consumers
Never store raw input references
❌ ANTI-PATTERNS (3)
Passing raw input into state
Storing user objects without cleanup
Relying on caller to enforce safety
πŸ’» CODE HINTS (1)
sanitize(input); return Object.freeze(clean)
πŸ§ͺ VALIDATION
Run mutation tests, use type-checkers and devtools to catch state changes. Confirm that external consumers cannot alter protected structures.
#64Mutable Data Matrix6 cells18 rules12 anti6 hints
Define when and how mutable data structures can be used safely without sacrificing predictability or clarity.
data_lifetime_scopeconcurrency_modelmutation_visibilityupdate_frequencydata_ownershiprollback_strategy
LOCALIZED_MUTATION
When a function modifies data only within its local stack frame
βœ… RULES (3)
Ensure mutated data is not shared outside the function
Use const-by-default and mark mutable explicitly
Avoid returning mutated references
❌ ANTI-PATTERNS (2)
Returning references to mutated local variables
Reassigning parameters passed by reference without copy
πŸ’» CODE HINTS (1)
Use local variables with clear lifetime annotations
SHARED_STATE_WITH_GUARDS
When multiple parts of the system access shared mutable state
βœ… RULES (3)
Use locks, atomic refs, or actors to serialize access
Minimize surface area of shared state
Separate read/write paths if possible
❌ ANTI-PATTERNS (2)
Allowing unsynchronized concurrent writes
Exposing shared state directly to consumers
πŸ’» CODE HINTS (1)
Wrap shared state in concurrency-safe primitives
EVENTUAL_CONSISTENCY_STRUCTURES
When data replication or caching introduces mutation delay
βœ… RULES (3)
Document consistency expectations per field
Use versioning or timestamps for conflict resolution
Expose last-updated metadata to consumers
❌ ANTI-PATTERNS (2)
Assuming immediate propagation of mutations
Mixing strong and weak consistency within same API
πŸ’» CODE HINTS (1)
Use CRDTs or eventual consistency-aware caches
REACTIVE_MUTABLE_BINDINGS
When UI or reactive components observe mutable model state
βœ… RULES (3)
Bind only to immutable projections or observable interfaces
Batch updates to avoid redundant reactions
Detach bindings when components unmount
❌ ANTI-PATTERNS (2)
Direct DOM mutation alongside reactive updates
Two-way bindings without explicit sync points
πŸ’» CODE HINTS (1)
Use observable proxies or state hooks with memoization
MUTABLE_BUFFER_STRUCTURES
When working with performance-critical buffers (e.g. I/O or graphics)
βœ… RULES (3)
Use low-level types with fixed allocation strategies
Document mutation boundaries clearly
Ensure alignment with consumer expectations
❌ ANTI-PATTERNS (2)
Overwriting buffer content without consumer synchronization
Assuming mutation order will be respected implicitly
πŸ’» CODE HINTS (1)
Use ring buffers or typed arrays with boundary guards
TRANSACTIONAL_MUTATION_PATHS
When changes to mutable state must be atomic or revertible
βœ… RULES (3)
Group mutations within explicit transactions
Log changes for recovery if needed
Fail-fast on transactional boundary violations
❌ ANTI-PATTERNS (2)
Mixing transactional and non-transactional writes
Silent failure to rollback after partial mutation
πŸ’» CODE HINTS (1)
Use command pattern or state snapshots for rollback
πŸ§ͺ VALIDATION
Use stress tests and mutation logs to validate state integrity under concurrent and rollback scenarios.
#65Data Normalization Matrix6 cells12 rules6 anti6 hints
Determines when to normalize data (eliminate redundancy) vs denormalize (optimize reads), and how to identify and resolve duplication in data structures.
normalization_formduplication_typeread_write_ratiocost
norm_001
When a table includes repeating groups (e.g. tags1, tags2), restructure to achieve 1NF.
βœ… RULES (2)
Move repeating values to a separate linked table
Ensure atomicity of each column
❌ ANTI-PATTERNS (1)
Storing multiple values in one column (comma-separated or nested)
πŸ’» CODE HINTS (1)
tags(id, post_id, tag_name)
norm_002
When part of a composite key determines non-key attributes, move those to separate table (2NF).
βœ… RULES (2)
Split tables based on full functional dependency
Retain only dependent columns per key
❌ ANTI-PATTERNS (1)
Storing author_name alongside post_id + comment_id key
πŸ’» CODE HINTS (1)
comments(post_id, comment_id, content); authors(author_id, name)
norm_003
When a non-key column depends on another non-key column, extract it to meet 3NF.
βœ… RULES (2)
Identify transitive dependencies
Split into separate related tables
❌ ANTI-PATTERNS (1)
Storing city and zipcode redundantly when only zipcode is needed
πŸ’» CODE HINTS (1)
zipcode(zipcode, city); user(address, zipcode)
norm_004
When read performance is prioritized, denormalize selective fields to reduce joins.
βœ… RULES (2)
Duplicate only non-volatile fields
Weigh redundancy vs performance
❌ ANTI-PATTERNS (1)
Denormalizing all fields without constraint
πŸ’» CODE HINTS (1)
orders(id, user_id, user_email_cached)
norm_005
Detect hidden duplication across schema and resolve via refactoring.
βœ… RULES (2)
Scan for similar column names across tables
Abstract repeated structures into shared entities
❌ ANTI-PATTERNS (1)
user_fullname and customer_fullname storing same logic separately
πŸ’» CODE HINTS (1)
person(id, fullname) β†’ used by both user/customer
norm_006
When schema introduces too many joins for basic reads, consider selective denormalization.
βœ… RULES (2)
Avoid more than 3 joins for common queries
Profile query cost regularly
❌ ANTI-PATTERNS (1)
Joins across 6+ tables for a single dashboard view
πŸ’» CODE HINTS (1)
Duplicate display name into summary view table
πŸ§ͺ VALIDATION
Verify: schema adheres to normalization rules where applicable, duplication reduced, joins optimized, denormalized fields documented and validated.
#66Data Denormalization Matrix6 cells18 rules12 anti6 hints
Guide decisions on when to denormalize data for performance, simplicity, or resilience reasons.
query_frequency_patternstorage_vs_compute_tradeoffupdate_complexityconsistency_requirementsread_path_latencydata_duplication_acceptability
HIGH_READ_OPTIMIZATION
When a dataset is read frequently with complex joins
βœ… RULES (3)
Denormalize read-heavy access paths
Preserve only essential relational links
Avoid redundant large object duplication
❌ ANTI-PATTERNS (2)
Denormalizing write-heavy paths unnecessarily
Duplicating nested objects without size limits
πŸ’» CODE HINTS (1)
Use materialized views or read models for joins
LATENCY_CRITICAL_ENDPOINTS
When specific endpoints require sub-millisecond response times
βœ… RULES (3)
Precompute data used in latency-critical APIs
Avoid fan-out calls at request time
Flatten structures for fast lookups
❌ ANTI-PATTERNS (2)
Using nested lookups in high-QPS APIs
Performing filtering via post-processing
πŸ’» CODE HINTS (1)
Leverage denormalized indexes or columnar stores
RESILIENCE_TO_UPSTREAM_FAILURES
When system must operate under partial data availability
βœ… RULES (3)
Replicate essential upstream fields locally
Cache derived values with TTL
Mark stale data explicitly in schema
❌ ANTI-PATTERNS (2)
Relying on live joins across failure boundaries
Failing hard on missing upstream attributes
πŸ’» CODE HINTS (1)
Use snapshot replication strategies with staleness indicators
WRITE_PATH_COST_CONTROL
When denormalized structures introduce write amplification
βœ… RULES (3)
Track number of dependent write targets per change
Use event-based propagation instead of sync updates
Avoid chaining updates across denormalized graphs
❌ ANTI-PATTERNS (2)
Updating multiple records synchronously on every change
Embedding mutable aggregates with high churn
πŸ’» CODE HINTS (1)
Use append-only logs to decouple updates
AUDITABILITY_AND_SNAPSHOTTING
When full historical view or rollback is required
βœ… RULES (3)
Log source of each denormalized field
Retain original normalized input for comparison
Version denormalized records explicitly
❌ ANTI-PATTERNS (2)
Overwriting denormalized values without history
Failing to record merge origin
πŸ’» CODE HINTS (1)
Combine denormalization with audit log or shadow store
MIXED_MODEL_READ_OPTIMIZATION
When dataset serves both transactional and analytical needs
βœ… RULES (3)
Use denormalized views for analytics, normalized for writes
Sync denormalized views periodically or via CDC
Separate OLTP and OLAP read paths at architecture level
❌ ANTI-PATTERNS (2)
Trying to serve all workloads from same model
Blending denormalized and normalized access in same code path
πŸ’» CODE HINTS (1)
Leverage dual-storage systems or federated query engines
πŸ§ͺ VALIDATION
Run read/write benchmark tests and simulate upstream failures to evaluate tradeoffs of denormalized layout.
#67Schema Design Matrix7 cells14 rules7 anti7 hints
Structures data schema β€” entities, relationships, normalization level, constraints β€” for integrity, performance, and evolution.
normalizationstorage_typeschema_rigidityscaletemporal
schema_001
When designing normalized relational schemas, ensure all non-key attributes depend only on the key.
βœ… RULES (2)
Use separate tables for each entity
Enforce foreign key constraints to model relationships
❌ ANTI-PATTERNS (1)
Repeating groups or derived fields inside entity table
πŸ’» CODE HINTS (1)
users(id PK, name), orders(id PK, user_id FK)
schema_002
When optimizing for read-heavy document access, embed related data within parent documents.
βœ… RULES (2)
Embed only if sub-entity lifecycle is tightly coupled
Accept higher write/update complexity for faster reads
❌ ANTI-PATTERNS (1)
Embedding large arrays or frequently-updated sub-documents
πŸ’» CODE HINTS (1)
user: { name, orders: [{ id, total }] }
schema_003
When operating in distributed systems, use UUID v4 or ULID for primary keys to avoid coordination.
βœ… RULES (2)
Avoid sequential auto-increment IDs across distributed nodes
Ensure uniqueness with UUID or ULID libraries
❌ ANTI-PATTERNS (1)
Using database sequences or auto-increment in multi-writer architecture
πŸ’» CODE HINTS (1)
id: uuid_generate_v4()
schema_004
When evolving schema over time, add optional+nullable fields and avoid breaking changes.
βœ… RULES (2)
Never remove or retype columns without full migration
Use nullable or defaulted new fields for evolution
❌ ANTI-PATTERNS (1)
Renaming fields in-place (breaks existing consumers)
πŸ’» CODE HINTS (1)
ALTER TABLE users ADD COLUMN middle_name TEXT DEFAULT NULL;
schema_005
When preserving historical audit or soft delete capability, use timestamp columns instead of hard deletes.
βœ… RULES (2)
Add deleted_at timestamp to all soft-deletable tables
Ensure all queries filter out deleted rows by default
❌ ANTI-PATTERNS (1)
DELETE FROM table WHERE ... without backup or trail
πŸ’» CODE HINTS (1)
WHERE deleted_at IS NULL
schema_006
When designing relational schemas, create indexes to support common queries and enforce integrity.
βœ… RULES (2)
Index foreign key columns and frequently filtered fields
Use unique indexes for candidate keys
❌ ANTI-PATTERNS (1)
Missing index on join key or lookup field
πŸ’» CODE HINTS (1)
CREATE INDEX idx_user_email ON users(email);
schema_007
When deciding whether to embed or reference in document stores, prefer embed for always-read-together data.
βœ… RULES (2)
Embed if subdocument is small and tightly coupled
Reference by ID if subdocument has independent lifecycle
❌ ANTI-PATTERNS (1)
Over-referencing within document DB, leading to joins
πŸ’» CODE HINTS (1)
{ _id, name, address: { city, country } } vs address_id reference
πŸ§ͺ VALIDATION
Verify: all entities have explicit PK strategy, relationships have FK constraints, indexes cover common queries, schema changes backward compatible, soft delete filters applied globally.
#68Optional vs Required Fields Matrix6 cells18 rules12 anti6 hints
Determine when a data field should be optional versus required across schemas, APIs, and storage.
field_semanticsconsumer_dependencydefault_value_behaviorschema_evolution_policyruntime_validation_scopeimpact_of_absence
ALWAYS_REQUIRED_CORE_IDENTITY
When a field is essential for entity identification or referencing
βœ… RULES (3)
Mark identifiers as required at all layers (schema, API, DB)
Reject objects missing required identity fields
Do not allow default or placeholder values for identity
❌ ANTI-PATTERNS (2)
Using 'null' or 0 as temporary ID
Allowing creation of objects without ID fields
πŸ’» CODE HINTS (1)
Use schema enforcement and database constraints
CONSUMER_DEPENDENT_OPTIONALITY
When different consumers rely on different subsets of fields
βœ… RULES (3)
Define optionality in context-specific schemas
Annotate consumer usage expectations explicitly
Avoid assuming field usage without consumer signal
❌ ANTI-PATTERNS (2)
Marking all fields as required to satisfy one client
Assuming all consumers use all fields equally
πŸ’» CODE HINTS (1)
Use schema composition or extension per context
EVOLVABLE_OPTIONAL_BACKFIELDS
When adding new fields to existing deployed schemas
βœ… RULES (3)
Add fields as optional by default in evolving APIs
Ensure defaults are handled gracefully
Annotate versioning or availability expectations
❌ ANTI-PATTERNS (2)
Adding required fields to stable schemas
Failing to provide fallbacks or default behaviors
πŸ’» CODE HINTS (1)
Use feature flags or default resolvers in readers
CONTEXTUAL_REQUIREDNESS
When a field is conditionally required based on other field values
βœ… RULES (3)
Use conditional validation logic outside base schema
Define dependent requirements in business logic layer
Document field dependencies in schema metadata
❌ ANTI-PATTERNS (2)
Encoding all conditional logic into core schema
Relying on consumers to infer requirements
πŸ’» CODE HINTS (1)
Implement rule engines or context-aware validators
SOFT_REQUIRED_RUNTIME_ENFORCEMENT
When a field must be filled during processing but not at rest
βœ… RULES (3)
Validate requiredness dynamically based on lifecycle stage
Log missing field cases for downstream inspection
Avoid hard schema failures on transient states
❌ ANTI-PATTERNS (2)
Schema-level enforcement of fields only needed at runtime
Blocking storage of incomplete but valid intermediate states
πŸ’» CODE HINTS (1)
Use runtime validators or task pipeline validators
NULLABLE_BUT_MEANINGFUL
When the absence of a value carries business semantics
βœ… RULES (3)
Document null semantics clearly in schema
Distinguish between null, undefined, and omitted
Use explicit enum or wrapper to represent intent
❌ ANTI-PATTERNS (2)
Treating null as equivalent to 'missing' or 'default'
Overloading null with multiple meanings
πŸ’» CODE HINTS (1)
Use Optional<T> wrappers or tagged union types
πŸ§ͺ VALIDATION
Run schema evolution and client contract tests to validate optional/required integrity across consumers.
#69Default Values Matrix6 cells18 rules12 anti6 hints
Guide decisions on when and how to assign default values to data fields across systems.
default_value_sourcefield_type_and_semanticsoverride_policyschema_versioningconsistency_across_environmentsruntime_vs_compile_time_defaults
SCHEMA_DEFINED_DEFAULTS
When default values are specified in data schemas
βœ… RULES (3)
Define defaults in formal schema definitions (e.g. JSON Schema, Avro)
Avoid relying on consumer-side injection
Make defaults explicit even if nullable
❌ ANTI-PATTERNS (2)
Setting default values only in UI forms
Assuming all consumers honor defaulting logic
πŸ’» CODE HINTS (1)
Use 'default' keyword in schema and validate output
APPLICATION_LOGIC_DEFAULTING
When defaults are assigned at runtime during object creation
βœ… RULES (3)
Centralize default logic in model constructors or factories
Log when defaults are applied
Allow overrides from caller if present
❌ ANTI-PATTERNS (2)
Scattering default logic across layers
Overwriting valid input values with defaults
πŸ’» CODE HINTS (1)
Use defaulting utilities or builder patterns
DEPLOYMENT_ENVIRONMENT_DEFAULTS
When defaults vary across environments or configurations
βœ… RULES (3)
Store env-specific defaults in config files or secret stores
Inject via config loaders, not hardcoded paths
Document all env-specific values and fallbacks
❌ ANTI-PATTERNS (2)
Embedding environment logic into business code
Assuming local dev values match production
πŸ’» CODE HINTS (1)
Use config injection frameworks with layered fallback
NULL_SAFE_DEFAULTING
When field may be null and default is needed for logic continuity
βœ… RULES (3)
Use language constructs for null-coalescing or optional chaining
Avoid double-defaulting (e.g. in schema and code)
Make intent of fallback explicit in logic
❌ ANTI-PATTERNS (2)
Applying default at read time without documenting fallback
Assuming all nulls should be defaulted
πŸ’» CODE HINTS (1)
Use ??, ?:, or Optional.orElse() idioms
AUDITABLE_DEFAULT_OVERRIDES
When defaults may be overridden by user input or downstream systems
βœ… RULES (3)
Store metadata indicating default override
Expose diffs in logs or UI where appropriate
Retain original defaulted value if needed for rollback
❌ ANTI-PATTERNS (2)
Silently overriding defaults with no trace
Failing to distinguish user-provided vs default-derived values
πŸ’» CODE HINTS (1)
Use versioned configs or metadata fields for override trace
COMPILE_TIME_CONSTANT_DEFAULTS
When safe and static values can be embedded at build time
βœ… RULES (3)
Declare constants in generated code or static blocks
Avoid hardcoding context-dependent values
Document rationale for compile-time injection
❌ ANTI-PATTERNS (2)
Using compile-time defaults for values expected to change
Embedding secrets or credentials into code
πŸ’» CODE HINTS (1)
Use constexpr, const, or build-time templates
πŸ§ͺ VALIDATION
Inject test records omitting defaulted fields and validate whether expected values appear consistently across all pipeline stages.
#70Nullability Matrix6 cells18 rules12 anti6 hints
Define clear policies for when null values are allowed, forbidden, or carry meaning across data systems.
field_semanticssystem_null_supportdata_source_trustbusiness_meaning_of_nullconsumer_handling_guaranteeslanguage_type_model
STRICT_NON_NULL_ENFORCEMENT
When a field is semantically mandatory for system correctness
βœ… RULES (3)
Disallow nulls at schema and runtime validation
Use non-nullable types in static languages
Fail fast if null is encountered unexpectedly
❌ ANTI-PATTERNS (2)
Allowing nulls for required fields to bypass errors
Silently defaulting nulls to arbitrary values
πŸ’» CODE HINTS (1)
Use types like string (non-null), not string?
NULL_MEANS_UNKNOWN
When data absence reflects epistemic uncertainty
βœ… RULES (3)
Use null to explicitly signal unknown value
Document that consumer must not infer meaning
Disallow conflation with empty string or 0
❌ ANTI-PATTERNS (2)
Using 0, false, or '' in place of null for unknown
Treating null as error state
πŸ’» CODE HINTS (1)
Use Option/Maybe types or tagged unions
NULL_MEANS_NOT_APPLICABLE
When a field is structurally present but not relevant in context
βœ… RULES (3)
Use null to indicate contextual inapplicability
Avoid inventing out-of-band values to simulate NA
Inform downstream systems to skip logic paths
❌ ANTI-PATTERNS (2)
Faking 'none' with default dates or negative numbers
Using NA strings instead of null
πŸ’» CODE HINTS (1)
Leverage nullable types with NA-checking guards
NULLABLE_FOR_EVOLUTION
When fields are introduced over time and need backward compatibility
βœ… RULES (3)
Add new fields as nullable by default
Avoid enforcing presence too early in lifecycle
Phase in validation gradually across versions
❌ ANTI-PATTERNS (2)
Releasing breaking changes with required fields
Treating null as default without consumer alignment
πŸ’» CODE HINTS (1)
Use version-aware readers with field fallback
NULL_TRACING_AND_AUDITABILITY
When it's critical to know why a field is null
βœ… RULES (3)
Log null origin and reason explicitly
Expose null provenance to downstream consumers
Differentiate null cause in error reports
❌ ANTI-PATTERNS (2)
Dropping nulls without trace
Filling nulls blindly with synthetic defaults
πŸ’» CODE HINTS (1)
Include metadata fields like null_reason or null_source
NULLABLE_FOR_LAZY_LOADING
When field population is deferred to post-fetch stages
βœ… RULES (3)
Mark lazily loaded fields as nullable in contracts
Ensure consumers handle null until resolved
Avoid assuming presence until explicitly loaded
❌ ANTI-PATTERNS (2)
Accessing nullable fields without checks
Treating null as 'never populated' vs 'not yet'
πŸ’» CODE HINTS (1)
Use accessors that auto-load or raise if unresolved
πŸ§ͺ VALIDATION
Inject nulls under each semantic condition and verify consumer behavior, logging, and decision paths.
#71Collection Semantics Matrix6 cells18 rules12 anti6 hints
Define the expected behavior and properties of data collections in different system contexts.
ordering_guaranteesuniqueness_constraintsnullability_of_elementscollection_type_intentmutation_behavioraccess_pattern
ORDERED_LIST_STRICT
When order of elements is meaningful and must be preserved
βœ… RULES (3)
Use list/array types with stable sorting
Document order semantics in API contracts
Avoid operations that implicitly re-order
❌ ANTI-PATTERNS (2)
Using sets when order is significant
Sorting during read without documenting side effect
πŸ’» CODE HINTS (1)
Use explicit index-based manipulation or stable sort
UNIQUE_SET_MEMBERSHIP
When only unique items should exist in a collection
βœ… RULES (3)
Use set types or hash-backed collections
Validate uniqueness on insert
Avoid reliance on order in iteration
❌ ANTI-PATTERNS (2)
Enforcing uniqueness via manual iteration
Relying on insertion order in unordered sets
πŸ’» CODE HINTS (1)
Use built-in Set/HashSet types or deduplication helpers
NULLABLE_COLLECTION_ELEMENTS
When elements within a collection may be missing or incomplete
βœ… RULES (3)
Document null handling expectations explicitly
Avoid assuming all elements are usable
Filter or guard nulls during processing
❌ ANTI-PATTERNS (2)
Blindly mapping over collections without null checks
Throwing errors on first null element
πŸ’» CODE HINTS (1)
Use compactMap/filterNotNull before processing
SEMANTICALLY_TYPED_COLLECTIONS
When the collection type signals meaning beyond data structure
βœ… RULES (3)
Name collection fields after their semantic role
Avoid generic names like 'items' or 'list'
Model nested collections explicitly
❌ ANTI-PATTERNS (2)
Using loosely-typed arrays for heterogeneous data
Packing multiple semantics into one list
πŸ’» CODE HINTS (1)
Use custom collection wrapper types
MUTABLE_COLLECTION_PROTOCOL
When collections are updated over time within a session or transaction
βœ… RULES (3)
Wrap mutations with audit or change log
Avoid exposing mutable collections directly
Use methods with controlled side effects
❌ ANTI-PATTERNS (2)
Modifying collections in-place across threads
Leaking references to mutable collections
πŸ’» CODE HINTS (1)
Use immutable snapshots or diff-on-write strategies
INDEXED_ACCESS_CONTRACTS
When consumers rely on fixed positions or indexes in the collection
βœ… RULES (3)
Document indexing assumptions clearly
Avoid reordering collections after initial population
Return safe defaults or errors on out-of-bounds
❌ ANTI-PATTERNS (2)
Indexing into unordered or unstable lists
Relying on implicit index meanings without validation
πŸ’» CODE HINTS (1)
Use index guards and boundary assertions
πŸ§ͺ VALIDATION
Run automated tests that validate element order, uniqueness, null safety, and mutation consistency under concurrent and sequential access.
#72Ordering Guarantees Matrix6 cells18 rules12 anti6 hints
Specify the level and type of ordering required in data storage, processing, and transmission.
ordering_typescope_of_guaranteeenforcement_mechanismbreak_condition_behaviorrecovery_strategyconsumer_assumption_model
TOTAL_ORDER_ENFORCEMENT
When all items must be seen in a single, globally consistent sequence
βœ… RULES (3)
Use global sequence numbers or logical clocks
Reject or reorder out-of-order arrivals
Checkpoint position on successful processing
❌ ANTI-PATTERNS (2)
Using timestamps as sole ordering mechanism
Merging uncoordinated ordered streams without reconciliation
πŸ’» CODE HINTS (1)
Use Kafka log offsets or Lamport clocks
PARTITIONED_ORDER_PRESERVATION
When ordering must be maintained within independent subsets
βœ… RULES (3)
Partition data deterministically by key
Process and emit results per partition in order
Preserve ordering through queue or stream semantics
❌ ANTI-PATTERNS (2)
Hashing keys inconsistently across stages
Interleaving partitioned outputs in final consumer
πŸ’» CODE HINTS (1)
Use consistent hashing with keyed message queues
ORDERED_DELIVERY_TO_CONSUMERS
When consumers rely on data arriving in strict order
βœ… RULES (3)
Buffer and sort if delivery order is not guaranteed
Acknowledge only after full in-order processing
Communicate delivery ordering contract in API
❌ ANTI-PATTERNS (2)
Pushing unordered messages to stateful consumers
Assuming network transport preserves order
πŸ’» CODE HINTS (1)
Use in-order delivery channels or reassembly buffers
CAUSAL_ORDER_REQUIREMENT
When the order must reflect cause-effect relationships
βœ… RULES (3)
Track dependencies explicitly in messages
Delay processing until all prerequisites are satisfied
Use vector clocks for fine-grained causality tracking
❌ ANTI-PATTERNS (2)
Inferring causality from timestamp proximity
Processing without checking causal closure
πŸ’» CODE HINTS (1)
Implement vector clock tracking or dependency graphs
BEST_EFFORT_SEMANTIC_ORDER
When strict order isn't feasible but a logical grouping helps reasoning
βœ… RULES (3)
Tag messages with semantic group identifiers
Use soft ordering cues for display or batch logic
Warn when semantic order cannot be met
❌ ANTI-PATTERNS (2)
Guaranteeing order without infrastructure support
Interpreting unordered delivery as strict failure
πŸ’» CODE HINTS (1)
Use semantic sort keys or display-order metadata
NO_ORDER_EXPECTATION
When order is irrelevant and must not be assumed
βœ… RULES (3)
Declare explicitly that no ordering is guaranteed
Ensure consumers tolerate arbitrary order
Avoid coupling processing logic to arrival sequence
❌ ANTI-PATTERNS (2)
Implicit reliance on ordered APIs
Applying ordered logic in unordered contexts
πŸ’» CODE HINTS (1)
Use unordered collections and batch processing abstractions
πŸ§ͺ VALIDATION
Simulate delivery disorder and confirm consumer resilience, reordering correctness, and causal constraint enforcement.
#73Key-Value Modeling Matrix6 cells18 rules12 anti6 hints
Guide modeling decisions when representing structured or semi-structured data as key-value pairs.
key_naming_strategyvalue_type_uniformityschema_discoverabilitymutation_frequencyquery_pattern_alignmentconsumer_flexibility
FIXED_SCHEMA_FLAT_KEYS
When keys are known and stable ahead of time
βœ… RULES (3)
Use flat keys with strict naming conventions
Validate structure using predefined schema
Reject unknown keys at ingestion
❌ ANTI-PATTERNS (2)
Allowing arbitrary keys in structured tables
Using dynamic keys where fixed structure exists
πŸ’» CODE HINTS (1)
Use JSON Schema or protobuf with field name mapping
DYNAMIC_KEY_ENUMERATION
When keys are dynamic but values follow a fixed pattern
βœ… RULES (3)
Constrain keys via naming regex or prefix convention
Expose list of known keys via metadata
Avoid nesting dynamic keys in deep hierarchies
❌ ANTI-PATTERNS (2)
Unbounded key growth with no index
Hardcoding dynamic keys in consumer logic
πŸ’» CODE HINTS (1)
Use map<string, ValueType> with external key registry
SEMI_STRUCTURED_METADATA
When key-value pairs encode auxiliary or optional metadata
βœ… RULES (3)
Separate core fields from metadata blob
Restrict metadata value size and types
Avoid logic branching on metadata content
❌ ANTI-PATTERNS (2)
Using metadata to store primary entity info
Allowing arbitrary deep structures in metadata
πŸ’» CODE HINTS (1)
Use `extras` or `custom_fields` object with key whitelist
MUTABLE_KEY_VALUE_CONFIGS
When key-value structures hold runtime-tunable settings
βœ… RULES (3)
Log all config key changes with timestamps
Validate value types and allowed ranges on change
Document defaults and override precedence
❌ ANTI-PATTERNS (2)
Allowing silent config changes without audit
Mixing user and system overrides in same map
πŸ’» CODE HINTS (1)
Use config store with layered resolution logic
SPARSE_FEATURE_ENCODING
When modeling sparse features or presence-only attributes
βœ… RULES (3)
Store only present features with compact encoding
Use uniform value types for fast parsing
Index presence bits separately if needed
❌ ANTI-PATTERNS (2)
Representing absence with null-filled schema
Forcing sparse data into wide static columns
πŸ’» CODE HINTS (1)
Use feature_map[key] = true or feature_vector encoding
CONSUMER_DEFINED_ACCESS_PATTERNS
When consumers vary in how they interpret keys and values
βœ… RULES (3)
Expose key-value specs per consumer class
Avoid embedding consumer logic in producer
Support filtering and projection at access layer
❌ ANTI-PATTERNS (2)
Hardcoding consumer usage into central schema
Breaking compatibility across consumer versions
πŸ’» CODE HINTS (1)
Use schema overlays or views per consumer
πŸ§ͺ VALIDATION
Run schema compatibility and query resolution tests with synthetic dynamic key scenarios to confirm indexing and contract integrity.
#74Indexing Strategy Matrix6 cells18 rules12 anti6 hints
Guide decisions on when and how to apply indexes to data structures for optimized access.
access_frequencydata_volumemutation_ratequery_patternindex_typestorage_constraints
PRIMARY_KEY_INDEXING
When unique identification of records is mandatory
βœ… RULES (3)
Index primary key with strong uniqueness guarantees
Enforce index at storage layer (e.g., database)
Avoid updates that mutate primary key values
❌ ANTI-PATTERNS (2)
Using composite keys where single field suffices
Allowing nulls in indexed primary keys
πŸ’» CODE HINTS (1)
Use B-Tree or hash index depending on key type
SECONDARY_FILTER_INDEXES
When filtering queries commonly use non-primary fields
βœ… RULES (3)
Index commonly filtered columns explicitly
Measure impact of multi-column indexes
Drop unused indexes after analysis
❌ ANTI-PATTERNS (2)
Adding indexes reactively without query analysis
Over-indexing low-selectivity fields
πŸ’» CODE HINTS (1)
Use query planner to test index coverage
TIME_SERIES_APPEND_INDEXES
When data is ingested in chronological order and queried by time
βœ… RULES (3)
Use clustered or partitioned indexes by time
Avoid random writes that break order
Evict expired data from index range proactively
❌ ANTI-PATTERNS (2)
Sharding time series across overlapping partitions
Indexing fine-grained time down to milliseconds unnecessarily
πŸ’» CODE HINTS (1)
Use LSM-tree or time-sharded bucket strategies
FULL_TEXT_SEARCH_INDEXES
When searching unstructured textual content
βœ… RULES (3)
Tokenize input with consistent analyzer
Index key text fields with inverted index
Preprocess stopwords and normalization rules
❌ ANTI-PATTERNS (2)
Applying full-text index to numeric or low-entropy fields
Storing full documents in index structure
πŸ’» CODE HINTS (1)
Use engines like Elasticsearch or Postgres GIN
HYBRID_COMPOSITE_INDEXES
When queries filter and sort across multiple dimensions
βœ… RULES (3)
Align index field order with query prefix filters
Avoid over-extending composite index width
Benchmark index vs. non-index scan performance
❌ ANTI-PATTERNS (2)
Adding all query fields into composite index blindly
Using composite indexes without usage validation
πŸ’» CODE HINTS (1)
Use covering indexes for known multidimensional patterns
SPARSE_OR_PARTIAL_INDEXES
When only a subset of records needs indexing
βœ… RULES (3)
Use partial indexes with WHERE clause
Index only non-null or frequently accessed subsets
Combine with TTL or archival rules where relevant
❌ ANTI-PATTERNS (2)
Creating full index on sparse-access fields
Indexing nullable fields with high cardinality
πŸ’» CODE HINTS (1)
Use PostgreSQL partial indexes or MongoDB sparse index
πŸ§ͺ VALIDATION
Run query benchmarks and index size comparison tests across typical workloads to validate ROI of index usage.
#75Data Lookup Complexity Matrix6 cells18 rules12 anti6 hints
Determine the appropriate data structure or access path based on lookup complexity tradeoffs.
query_frequencykey_distributiondata_volumelatency_sensitivityupdate_vs_read_ratioaccess_pattern_complexity
CONSTANT_TIME_HASH_LOOKUP
When key access is uniformly distributed and predictable
βœ… RULES (3)
Use hash maps when keys are well-distributed
Ensure hash function minimizes collisions
Size map appropriately to avoid rehashing
❌ ANTI-PATTERNS (2)
Using hash map with high collision domains
Storing large values directly in hash table
πŸ’» CODE HINTS (1)
Use HashMap, dict, or unordered_map equivalents
LOGARITHMIC_LOOKUP_WITH_BALANCED_TREE
When data must remain sorted for range queries
βœ… RULES (3)
Use balanced trees (e.g., AVL, Red-Black, B-Tree)
Avoid unbounded insertions that degrade balance
Rotate or rebalance periodically in dynamic scenarios
❌ ANTI-PATTERNS (2)
Forcing sort operations on unsorted data structures
Using tree structure when key comparisons are expensive
πŸ’» CODE HINTS (1)
Use std::map, TreeMap, or BTreeMap
LINEAR_SCAN_FOR_SMALL_OR_RARE_QUERIES
When datasets are small or queries are infrequent
βœ… RULES (3)
Use linear scan for fewer than ~100 elements
Prefer flat arrays over linked structures
Optimize loop body rather than index structure
❌ ANTI-PATTERNS (2)
Adding index logic to infrequently accessed data
Using linked lists with poor cache performance
πŸ’» CODE HINTS (1)
Use `find()` or loop over flat slice/vector
SHARD_AND_LOOKUP_BY_KEY_RANGE
When data exceeds memory limits and must be distributed
βœ… RULES (3)
Shard by consistent hash or key range
Route requests using shard index or router
Avoid cross-shard joins in lookup paths
❌ ANTI-PATTERNS (2)
Random shard allocation without lookup determinism
Duplicating data across inconsistent partitions
πŸ’» CODE HINTS (1)
Use sharded map or distributed hash table
MULTI_KEY_LOOKUP_PATHS
When queries depend on combinations of keys or dimensions
βœ… RULES (3)
Use compound indexes or inverted structures
Support partial matches where viable
Pre-materialize joins if joins are stable
❌ ANTI-PATTERNS (2)
Repeated joins on the fly for every query
Sparse indexes with low hit rate
πŸ’» CODE HINTS (1)
Use multi-index DBs or materialized key projections
HIERARCHICAL_LOOKUP_TRAVERSAL
When data is naturally nested or tree-structured
βœ… RULES (3)
Use path-based lookup or depth index
Cache frequent subpaths
Avoid flattening tree when hierarchy adds meaning
❌ ANTI-PATTERNS (2)
Flattening tree for convenience at query cost
Serializing tree to text blobs for lookup
πŸ’» CODE HINTS (1)
Use trie, prefix-tree, or document-based DB with path indexes
πŸ§ͺ VALIDATION
Benchmark lookup latency and memory usage across structures with synthetic workloads representative of target queries.
#76Serialization Matrix6 cells13 rules6 anti6 hints
Determines how data structures are converted to/from text or binary formats β€” field ordering, special type handling, and information preservation.
formattype_handlingfield_orderinginformation_loss
ser_001
When serializing objects by default in JSON, ensure primitives are preserved correctly.
βœ… RULES (2)
Use JSON.stringify() for primitives and plain objects
Avoid circular structures
❌ ANTI-PATTERNS (1)
Trying to serialize non-serializable fields like functions or closures
πŸ’» CODE HINTS (1)
JSON.stringify({ id: 1, name: 'Alice' })
ser_002
When deterministic output is required, serialize JSON with sorted keys.
βœ… RULES (2)
Sort object keys alphabetically before serialization
Use canonical serializer for hashing
❌ ANTI-PATTERNS (1)
Using native JSON.stringify with non-deterministic key order
πŸ’» CODE HINTS (1)
canonicalStringify(obj)
ser_003
When handling special types (Date, BigInt, binary), use explicit transformation before JSON serialization.
βœ… RULES (3)
Convert Date to ISO string
BigInt to string or custom format
Base64 encode binary
❌ ANTI-PATTERNS (1)
Letting JSON.stringify crash on BigInt
πŸ’» CODE HINTS (1)
JSON.stringify({ created: date.toISOString(), size: big.toString() })
ser_004
When serializing complex objects, implement custom toJSON() or fromJSON() methods to control shape.
βœ… RULES (2)
Expose only relevant fields
Hide internal state or metadata
❌ ANTI-PATTERNS (1)
Dumping entire internal class state as-is
πŸ’» CODE HINTS (1)
toJSON() { return { id: this.id, name: this.name }; }
ser_005
When data must round-trip (serialize β†’ deserialize), ensure lossless format and decoding.
βœ… RULES (2)
Preserve full precision of numbers and timestamps
Include type metadata if needed
❌ ANTI-PATTERNS (1)
Losing timezone or millisecond precision in date fields
πŸ’» CODE HINTS (1)
parse(dateStr).toISOString() === original
ser_006
When evolving a serialized format, maintain backward compatibility via version tagging.
βœ… RULES (2)
Add version field to serialized payload
Support fallback readers for old versions
❌ ANTI-PATTERNS (1)
Breaking decoder when new fields are added
πŸ’» CODE HINTS (1)
{ version: 2, payload: {...} }
πŸ§ͺ VALIDATION
Verify: all formats are parseable, canonical serialization is deterministic, BigInt and Date handled explicitly, round-tripping preserves structure, backward compatibility tests pass.
#77Deserialization Matrix6 cells18 rules12 anti6 hints
Establish safe and consistent patterns for converting serialized data into structured in-memory objects.
data_source_trustschema_stabilityfield_type_expectationerror_handling_strategyperformance_constraintssecurity_hardening
STRICT_SCHEMA_VALIDATION
When deserializing from known and versioned formats
βœ… RULES (3)
Validate all fields against schema before use
Reject unknown or extra fields unless explicitly allowed
Fail fast on schema mismatch
❌ ANTI-PATTERNS (2)
Permissive parsing of arbitrary structures
Auto-expanding object models based on input
πŸ’» CODE HINTS (1)
Use libraries with strict mode or schema binding
TRUSTED_SOURCE_SHORTCUTS
When input is generated internally and schema-controlled
βœ… RULES (3)
Bypass redundant validation when version is pinned
Log assumption of trust explicitly
Fallback to safe defaults if decoding fails
❌ ANTI-PATTERNS (2)
Trusting source without provenance verification
Skipping validation in critical edge paths
πŸ’» CODE HINTS (1)
Use typed decoders with context-aware optimizations
DEFENSIVE_EXTERNAL_DESERIALIZATION
When deserializing data from third-party or external clients
βœ… RULES (3)
Disallow polymorphic type resolution from payload
Cap memory and nesting depth during parse
Audit field bindings for injection vectors
❌ ANTI-PATTERNS (2)
Allowing external control of deserialization type
Unbounded recursion or deeply nested structures
πŸ’» CODE HINTS (1)
Use safe JSON/YAML/XML parsers with configurable limits
VERSIONED_SCHEMA_SUPPORT
When serialized formats evolve over time
βœ… RULES (3)
Support multiple schema versions in decoder
Use feature flags or version tags for logic branching
Log parsing logic version during decode
❌ ANTI-PATTERNS (2)
Hardcoding schema to a single version
Mixing decoding logic across versions without isolation
πŸ’» CODE HINTS (1)
Use schema registry or version-mapped decoding layer
PARTIAL_FAILURE_TOLERANCE
When partial data is better than total failure
βœ… RULES (3)
Collect and report field-level decoding errors
Populate default or sentinel values when recoverable
Provide error summary alongside object
❌ ANTI-PATTERNS (2)
Failing whole object on single field error
Silent nulls on broken fields
πŸ’» CODE HINTS (1)
Use `Result<T, Error>` or field-level wrappers
ISOLATED_SANDBOX_DESERIALIZATION
When high-risk payloads require untrusted deserialization
βœ… RULES (3)
Perform deserialization in sandboxed runtime
Disallow reflection or dynamic code during parse
Limit CPU, memory, and IO available during operation
❌ ANTI-PATTERNS (2)
Running deserialization inline in critical services
Allowing payload-based code execution paths
πŸ’» CODE HINTS (1)
Use subprocess workers or VM-based parsing engines
πŸ§ͺ VALIDATION
Inject malformed payloads with version, nesting, and type attacks to verify enforcement of schema, limits, and sandboxing.
#78Data Versioning Matrix6 cells12 rules6 anti6 hints
Determines how data structures are versioned over time β€” version fields, compatibility rules, and migration strategies at the schema level.
version_strategycompatibility_directionmigration_typebreaking_threshold
ver_001
Add explicit version field in every serialized record to manage schema evolution.
βœ… RULES (2)
Always include 'version' as top-level field
Default version to 1 if not specified
❌ ANTI-PATTERNS (1)
Relying on implicit version inference from field presence
πŸ’» CODE HINTS (1)
{ version: 2, data: {...} }
ver_002
When evolving schema, add fields as optional to maintain backward compatibility.
βœ… RULES (2)
Mark new fields as optional in parser
Avoid reordering required fields
❌ ANTI-PATTERNS (1)
Adding required fields in newer versions
πŸ’» CODE HINTS (1)
type V2 = { name: string; nickname?: string }
ver_003
Make readers forward-compatible by ignoring unknown fields.
βœ… RULES (2)
Use tolerant parser that accepts extras
Log presence of unknown fields optionally
❌ ANTI-PATTERNS (1)
Failing schema validation on unexpected keys
πŸ’» CODE HINTS (1)
allowUnknown: true
ver_004
Migrate data on-the-fly during read operations instead of mutating persisted storage.
βœ… RULES (2)
Transform old schema to new shape at runtime
Avoid mutating source data
❌ ANTI-PATTERNS (1)
Running destructive migrations on production data
πŸ’» CODE HINTS (1)
if (record.version === 1) return upgradeV1(record);
ver_005
Allow breaking changes only under version bump and compatibility boundary.
βœ… RULES (2)
Document breaking change and bump version
Coordinate consumers in advance
❌ ANTI-PATTERNS (1)
Changing field type without notice or version update
πŸ’» CODE HINTS (1)
schema-v2.json
ver_006
Use schema registry to manage multiple schema versions and route accordingly.
βœ… RULES (2)
Register each version explicitly
Use version number to select parser
❌ ANTI-PATTERNS (1)
Loading schemas from local without central version tracking
πŸ’» CODE HINTS (1)
registry.get(version).parse(payload)
πŸ§ͺ VALIDATION
Verify: version field present in all records, unknown fields ignored when allowed, migrations transform safely, registry supports version routing.
#79Backward-Compatible Data Matrix6 cells18 rules12 anti6 hints
Define principles for evolving data structures without breaking existing readers or consumers.
field_addition_policyfield_removal_strategydefault_value_handlingschema_version_signalingreader_tolerance_levelscontract_test_coverage
APPEND_ONLY_FIELD_EVOLUTION
When introducing new fields to live data models
βœ… RULES (3)
Add new fields as optional or nullable
Document semantic impact of new field presence
Ensure defaults are safely ignorable by legacy code
❌ ANTI-PATTERNS (2)
Adding required fields without version control
Assuming all clients auto-adapt to new fields
πŸ’» CODE HINTS (1)
Use feature detection or null-coalescing readers
GRACEFUL_FIELD_DEPRECATION
When retiring or discouraging old fields
βœ… RULES (3)
Mark deprecated fields with warnings, not removal
Support dual-write during migration phases
Audit usage in downstream systems before removal
❌ ANTI-PATTERNS (2)
Deleting fields that are still read by consumers
Silently zeroing out deprecated values
πŸ’» CODE HINTS (1)
Emit telemetry on deprecated field access
SCHEMA_VERSION_TAGGING
When consumers may read multiple schema formats
βœ… RULES (3)
Include version in data payload or envelope
Branch decoder logic per version contract
Store decoder metrics per schema revision
❌ ANTI-PATTERNS (2)
Inferring schema version from field shape
Using implicit versioning via consumer assumptions
πŸ’» CODE HINTS (1)
Use `schema_version` field or MIME-type header
TOLERANT_READER_DESIGN
When readers must operate across schema variations
βœ… RULES (3)
Ignore unknown fields unless explicitly required
Use default values for missing optional fields
Avoid binding readers to rigid object models
❌ ANTI-PATTERNS (2)
Throwing errors on unknown or missing fields
Using strict unmarshalling with tight coupling
πŸ’» CODE HINTS (1)
Use dynamic decoders or field maps
CONTRACT_TESTED_MIGRATIONS
When evolving schema in systems with external dependencies
βœ… RULES (3)
Test all schema changes against known consumer contracts
Snapshot consumer expectations for CI validation
Use canary rollout to detect field-related issues
❌ ANTI-PATTERNS (2)
Deploying schema changes without contract validation
Assuming internal test coverage applies to external APIs
πŸ’» CODE HINTS (1)
Use Pact or protobuf compatibility checks
DUAL_READ_WRITE_PATHS
When transitioning between schema models with active traffic
βœ… RULES (3)
Write data in both old and new schema formats
Read from both schemas until confidence is achieved
Log divergence between representations during overlap
❌ ANTI-PATTERNS (2)
Cutting over to new format without migration period
Allowing new writes to block old readers
πŸ’» CODE HINTS (1)
Use toggle-based schema writers with telemetry
πŸ§ͺ VALIDATION
Run regression tests and consumer-driven contract validation on all schema evolutions before deployment.
#80Constraint Source Matrix6 cells12 rules6 anti6 hints
Determines where constraints originate β€” business logic, UI patterns, legal/compliance, backend storage, or external APIs.
source_typeconstraint_originownershipvolatility
source_001
When a rule is part of domain behavior (e.g. age must be >18), it originates in product/business logic layer.
βœ… RULES (2)
Document rule in product spec
Apply consistently in frontend + backend
❌ ANTI-PATTERNS (1)
Scattered enforcement across layers
πŸ’» CODE HINTS (1)
if (age < 18) throw Error('Must be over 18')
source_002
When UI restricts certain input patterns (e.g. no emojis), constraint originates in usability or branding pattern.
βœ… RULES (2)
Validate pattern at input level
Style violation inline
❌ ANTI-PATTERNS (1)
Blocking backend without clear UI indication
πŸ’» CODE HINTS (1)
pattern=/^[a-zA-Z0-9 ]+$/
source_003
When a field must follow a legal rule (e.g. 9-digit SSN), constraint source is compliance team or external law.
βœ… RULES (2)
Reference external compliance spec
Log rule origin for audit
❌ ANTI-PATTERNS (1)
Altering legal constraint for convenience
πŸ’» CODE HINTS (1)
if (!/^\d{9}$/.test(ssn)) throw Error('Invalid SSN')
source_004
When DB column type (e.g. VARCHAR(50)) imposes constraint, rule source is schema definition.
βœ… RULES (2)
Align UI maxLength with DB schema
Reject oversized values at backend
❌ ANTI-PATTERNS (1)
Frontend allows long strings β†’ backend truncates silently
πŸ’» CODE HINTS (1)
<input maxlength='50' />
source_005
When external system defines input shape (e.g. payment gateway allows only 10 chars), rule source is API contract.
βœ… RULES (2)
Read and apply from external API docs
Validate before request sent
❌ ANTI-PATTERNS (1)
Trial/error against external APIs
πŸ’» CODE HINTS (1)
if (input.length > 10) error('Too long for Stripe')
source_006
When admin defines limit dynamically (e.g. max users per org), constraint is user-configured.
βœ… RULES (2)
Load config before applying
Expose limit in UI for awareness
❌ ANTI-PATTERNS (1)
Hardcoding admin-editable limits
πŸ’» CODE HINTS (1)
if (org.users > config.maxUsers) showError()
πŸ§ͺ VALIDATION
Verify: each constraint has traceable source, documented reason, mapped to enforcement point (UI/server), and reflected in config/schema if relevant.
#81Constraint Boundary Matrix6 cells12 rules6 anti6 hints
Determines where constraints are enforced β€” client vs. server, schema vs. code, sync vs. async, pre vs. post mutation.
constraint_locationtiminglayerresilience
constraint_001
When input must be validated before form submission, enforce rules on client synchronously (e.g. length, pattern).
βœ… RULES (2)
Run before submit button activates
Keep logic fast and UI-bound
❌ ANTI-PATTERNS (1)
Relying only on backend for simple length checks
πŸ’» CODE HINTS (1)
onBlur = validateField
constraint_002
When critical logic (e.g. permission, duplicates) must be guaranteed, enforce on server after submission.
βœ… RULES (2)
Repeat all critical constraints server-side
Return actionable errors
❌ ANTI-PATTERNS (1)
Trusting only client
πŸ’» CODE HINTS (1)
POST /submit β†’ validate β†’ persist
constraint_003
When frontend and backend share types (e.g. with TypeScript or JSON schema), validate using same source in both.
βœ… RULES (2)
Generate validators from shared schema
Avoid drift in logic
❌ ANTI-PATTERNS (1)
Forked validation logic across environments
πŸ’» CODE HINTS (1)
validate(input, schema)
constraint_004
When validation requires external resource (e.g. username availability), trigger async call after user stops typing.
βœ… RULES (2)
Use debounce before request
Avoid blocking full form submission
❌ ANTI-PATTERNS (1)
Async validation on every keystroke
πŸ’» CODE HINTS (1)
debounce(() => checkName(name), 500)
constraint_005
When mutation can cause new invalid state (e.g. balance < 0), validate after side effect and revert if needed.
βœ… RULES (2)
Wrap mutation in try/catch
Include rollback logic
❌ ANTI-PATTERNS (1)
No check after dangerous mutation
πŸ’» CODE HINTS (1)
try { applyTransfer() } catch { rollback() }
constraint_006
When server cannot enforce (e.g. browser API constraints), use best-effort client-only checks for resilience.
βœ… RULES (2)
Warn but don't block
Use browser features like input type
❌ ANTI-PATTERNS (1)
Trying to enforce server-level integrity on weak client-side checks
πŸ’» CODE HINTS (1)
<input type='email' required />
πŸ§ͺ VALIDATION
Verify: client sync constraints enforce basic rules, server guards critical rules, shared schemas match, async API-based validation debounced, mutation rollback safe, client-only checks enhance UX.
#82Data Validation Boundaries Matrix6 cells12 rules6 anti6 hints
Determines where raw external data is validated and transformed into trusted domain objects β€” the exact boundary between untrusted input and validated internal data.
boundary_locationvalidation_depthtransformationtrust_level
valbound_001
When receiving external input at the API layer, apply schema validation immediately to ensure payload shape is correct before proceeding.
βœ… RULES (2)
Use a typed schema (e.g. Zod) to enforce structure
Reject malformed requests with 400
❌ ANTI-PATTERNS (1)
Passing raw req.body to business logic without validation
πŸ’» CODE HINTS (1)
const parsed = schema.safeParse(req.body);
valbound_002
When loading data from the database, validate fields recursively to detect stale or malformed records.
βœ… RULES (2)
Wrap DB models with validators before using in logic
Log or quarantine bad records
❌ ANTI-PATTERNS (1)
Trusting DB values as always valid
πŸ’» CODE HINTS (1)
const user = validateUser(await db.find(...))
valbound_003
When importing data from CSV or JSON files, parse and validate every record deeply β€” and reject bad rows before they enter the system.
βœ… RULES (2)
Validate each row with schema
Report or skip invalid rows
❌ ANTI-PATTERNS (1)
Bulk-inserting file content without row checks
πŸ’» CODE HINTS (1)
rows.filter(schema.safeParse).map(transform)
valbound_004
When receiving data from internal microservices, re-validate as if it were external to avoid cascading corruption.
βœ… RULES (2)
Do not assume upstream service always sends valid shape
Treat all inbound service data as untrusted
❌ ANTI-PATTERNS (1)
Skipping validation on trusted internal RPC payloads
πŸ’» CODE HINTS (1)
const invoice = invoiceSchema.parse(serviceResponse)
valbound_005
When transforming raw input into domain entities, use constructors or factory functions to encapsulate validation logic.
βœ… RULES (2)
Do not allow direct mutation of raw fields
Use private constructors and expose validators
❌ ANTI-PATTERNS (1)
Constructing domain object via object literal without validation
πŸ’» CODE HINTS (1)
const email = EmailAddress.create(raw.email)
valbound_006
When defining trust zones, ensure all data entering the trusted zone has passed strict validation and transformation.
βœ… RULES (2)
Mark data as trusted only after schema + semantic validation
Prevent raw values from flowing into core logic
❌ ANTI-PATTERNS (1)
Leaking raw external input into logic assuming it's trusted
πŸ’» CODE HINTS (1)
assertTrusted(validatedData); coreLogic(validatedData);
πŸ§ͺ VALIDATION
Verify: all input paths validate before entering core, file/db/service inputs are rechecked, raw-to-domain flows pass through encapsulation, and trust zone never receives unchecked data.
#83Referential Integrity Matrix6 cells18 rules12 anti6 hints
Define when and how to enforce or relax referential integrity constraints across related data entities.
enforcement_scopedeletion_cascade_policyreference_validation_timingforeign_key_representationperformance_vs_consistency_tradeoffcross_boundary_reference_model
STRICT_FOREIGN_KEY_CONSTRAINTS
When relational integrity is critical for correctness
βœ… RULES (3)
Declare foreign keys with ON DELETE/UPDATE constraints
Enforce at database or ORM level
Audit constraint failures and reject on violation
❌ ANTI-PATTERNS (2)
Disabling FK checks for performance without fallback
Silently accepting missing referenced records
πŸ’» CODE HINTS (1)
Use `FOREIGN KEY` with CASCADE or RESTRICT
LAZY_REFERENCE_RESOLUTION
When references may point to delayed or eventual entities
βœ… RULES (3)
Mark reference as soft or eventual
Validate reference at use-time, not ingest-time
Flag unresolved references for cleanup pass
❌ ANTI-PATTERNS (2)
Blocking writes due to unavailable references
Treating unresolved refs as valid forever
πŸ’» CODE HINTS (1)
Use nullable FK or logical ID without hard constraint
ASYNC_REFERENCE_VALIDATION
When immediate validation is too costly or slow
βœ… RULES (3)
Validate references in background jobs
Mark data as 'unverified' until check passes
Allow speculative insertion with rollback if invalid
❌ ANTI-PATTERNS (2)
Assuming all data is verified at rest
Allowing broken links to accumulate silently
πŸ’» CODE HINTS (1)
Use retry queue or post-ingestion integrity scan
DENORMALIZED_REFERENCE_EMBEDDING
When data access is read-heavy and reference resolution is costly
βœ… RULES (3)
Replicate only stable reference fields
Refresh embedded values via sync loop or trigger
Keep source of truth linked explicitly
❌ ANTI-PATTERNS (2)
Embedding volatile fields without update strategy
Breaking reference tracking by removing original key
πŸ’» CODE HINTS (1)
Use materialized views or embedded documents
POLYMORPHIC_REFERENCE_HANDLING
When a reference may point to multiple entity types
βœ… RULES (3)
Tag reference with target type discriminator
Validate target existence and type dynamically
Avoid hardcoding logic per reference type
❌ ANTI-PATTERNS (2)
Using a single field for multiple relationship types without tagging
Assuming all references resolve the same way
πŸ’» CODE HINTS (1)
Use polymorphic relation frameworks or union refs
CROSS_BOUNDARY_REFERENCE_LOGIC
When references span microservices or storage domains
βœ… RULES (3)
Use logical identifiers and contract validation
Replicate IDs and metadata as needed
Validate references via service contracts, not DB joins
❌ ANTI-PATTERNS (2)
Using DB foreign keys across bounded contexts
Blocking cross-service writes on remote integrity checks
πŸ’» CODE HINTS (1)
Use ID mapping tables or reference registries
πŸ§ͺ VALIDATION
Run consistency checkers across all reference paths, simulate deletions and updates, and confirm cleanup or rejection logic activates correctly.
#84Data Ownership Matrix6 cells18 rules12 anti6 hints
Define responsibilities and guarantees for ownership, custody, and authority over data entities.
ownership_scopemutation_rightsread_visibilitycross_domain_coordinationconflict_resolutionlifecycle_stewardship
SINGLE_WRITER_MODEL
When one system is the authoritative source for data mutations
βœ… RULES (3)
Route all updates through single owner service
Reject conflicting external mutations
Replicate via read-only channels only
❌ ANTI-PATTERNS (2)
Allowing multiple sources to write same record
Syncing bidirectionally without reconciliation
πŸ’» CODE HINTS (1)
Use write APIs protected by ownership token
MULTI_TENANT_OWNERSHIP_TRACKING
When multiple tenants own distinct subsets of the same data model
βœ… RULES (3)
Tag all records with tenant ownership identifier
Filter queries by tenant context
Prevent cross-tenant writes or leakage
❌ ANTI-PATTERNS (2)
Storing tenant-blind data in shared tables
Mixing data ownership context within a session
πŸ’» CODE HINTS (1)
Use per-tenant data partitioning or row-level ACLs
SHARED_OWNERSHIP_WITH_CONSENSUS
When multiple systems have legitimate rights to mutate a record
βœ… RULES (3)
Use versioned writes or CRDTs to track state
Record mutation provenance and timestamps
Resolve conflicts via deterministic merge strategy
❌ ANTI-PATTERNS (2)
Allowing last-write-wins across uncoordinated systems
Dropping conflicting writes silently
πŸ’» CODE HINTS (1)
Use operational transforms or merge queues
DERIVED_DATA_CUSTODIANSHIP
When a system manages data derived from but not owning the original source
βœ… RULES (3)
Link derived data back to original owner
Sync on upstream mutation events
Mark derived data as stale if upstream is unavailable
❌ ANTI-PATTERNS (2)
Treating derived copy as independent without source
Losing source linkage in transformation
πŸ’» CODE HINTS (1)
Use lineage metadata and source UUID embedding
CROSS_DOMAIN_OWNERSHIP_NEGOTIATION
When data ownership must be transferred across services or orgs
βœ… RULES (3)
Record ownership transfer events with timestamps
Confirm receipt and acceptance by new owner
Pause mutation rights during transition if needed
❌ ANTI-PATTERNS (2)
Implicit ownership changes with no trace
Race conditions during transfer window
πŸ’» CODE HINTS (1)
Use transfer logs and ownership status flags
DATA_STEWARDSHIP_ACROSS_LIFECYCLE
When ownership includes responsibility for retention, deletion, and compliance
βœ… RULES (3)
Define stewardship policies by data type
Log lifecycle actions and policy enforcement
Delegate archival and deletion to custodial agent
❌ ANTI-PATTERNS (2)
Leaving expired data in place without review
Blurring lines between ownership and custody
πŸ’» CODE HINTS (1)
Use policy engine to drive data lifecycle operations
πŸ§ͺ VALIDATION
Simulate conflicting writes, ownership transfers, and downstream mutations to confirm policy enforcement, visibility, and auditability.
#85Data Copy vs Reference Matrix6 cells18 rules12 anti11 hints
Helps engineers decide whether to copy or reference data when passing, storing, or manipulating it across contexts.
data_mutabilityownership_modelstructure_depthperformance_risklifecycle_durationconcurrency_level
COPY_IMMUTABLE_VALUE
When passing immutable values across short-lived functions
βœ… RULES (3)
Copy primitives or frozen objects
Allow inline destructuring
Use spread operator for shallow copy only
❌ ANTI-PATTERNS (2)
Deep cloning large immutable trees
Passing frozen objects as-is when mutation might happen
πŸ’» CODE HINTS (2)
const next = { ...prev }
const { a, b } = obj
REFERENCE_SHARED_STATE
When maintaining reactive state across components
βœ… RULES (3)
Reference shared object if all readers are trusted
Use state library with signal tracking
Prevent writes unless in owner context
❌ ANTI-PATTERNS (2)
Blind mutation of shared objects
Passing reference across uncoordinated threads
πŸ’» CODE HINTS (2)
useSharedState()
const ctx = React.useContext(AppContext)
DEEP_COPY_ON_PERSIST
When storing complex objects for later reload
βœ… RULES (3)
Use structuredClone or serialization
Strip functions and non-serializable values
Avoid copying transient fields
❌ ANTI-PATTERNS (2)
Saving shallow copies of mutable data
Rehydrating data with lingering closures
πŸ’» CODE HINTS (2)
JSON.parse(JSON.stringify(obj))
structuredClone(obj)
REF_IF_READONLY_BULK
When reading large arrays or trees without modification
βœ… RULES (3)
Pass reference if access is readonly
Use Object.freeze to signal intent
Avoid mapping just to return original
❌ ANTI-PATTERNS (2)
Cloning read-only arrays before display
Mapping arrays for identity
πŸ’» CODE HINTS (1)
const list = getCatalog(); render(list)
COPY_BEFORE_MUTATE
When modifying data passed from external source
βœ… RULES (3)
Clone input if mutation is required
Track provenance of incoming data
Use deep copy if nested mutation needed
❌ ANTI-PATTERNS (2)
Mutating props in React
Overwriting Redux state directly
πŸ’» CODE HINTS (2)
const local = [...incoming]
deepClone(obj)
SHARE_REF_FOR_STREAMING
When piping large buffers or binary data across stages
βœ… RULES (3)
Pass buffer by reference
Use views for offset manipulation
Document ownership if async
❌ ANTI-PATTERNS (2)
Copying full buffer on each hop
Mutating shared chunk without locking
πŸ’» CODE HINTS (2)
processChunk(buf)
new Uint8Array(shared, offset, length)
πŸ§ͺ VALIDATION
Verify: copies made before mutation, references preserved for readonly, deep clones for persistence, buffer passed by ref, and React/Redux integrity maintained.
#86Memory Layout Matrix6 cells18 rules12 anti6 hints
Guide structuring of data in memory for performance, alignment, and cache utilization tradeoffs.
access_patternstructure_alignmentdata_localityallocation_strategycache_behaviorrepresentation_flexibility
STRUCT_OF_ARRAYS_LAYOUT
When bulk operations are performed on individual fields
βœ… RULES (3)
Split struct fields into parallel arrays
Align arrays to hardware-friendly boundaries
Access via index instead of pointer traversal
❌ ANTI-PATTERNS (2)
Packing fields together when only one is hot
Accessing multiple SoA blocks with divergent strides
πŸ’» CODE HINTS (1)
Use SoA patterns in tight numeric loops
ARRAY_OF_STRUCTS_LAYOUT
When whole objects are loaded or passed together
βœ… RULES (3)
Pack related fields contiguously
Minimize padding with manual field ordering
Use aligned structs with compact footprint
❌ ANTI-PATTERNS (2)
Using AoS in scattered update scenarios
Ignoring padding cost in large arrays
πŸ’» CODE HINTS (1)
Use AoS when object-centric logic dominates
CACHE_AWARE_LAYOUT_OPTIMIZATION
When performance is limited by cache misses
βœ… RULES (3)
Group hot fields together near each other
Separate cold fields into overflow structs
Profile cache hit ratios and tune layout accordingly
❌ ANTI-PATTERNS (2)
Random access across large object graphs
Interleaving hot and cold fields without profiling
πŸ’» CODE HINTS (1)
Use cache line annotations or profiling visualizers
BITFIELD_AND_COMPACT_LAYOUTS
When memory size is constrained or bit-level layout matters
βœ… RULES (3)
Use bitfields for booleans or small enums
Avoid unaligned access or cross-word overlap
Document layout guarantees and side effects
❌ ANTI-PATTERNS (2)
Overpacking that causes performance penalty
Using compiler-specific bitfield ordering semantics
πŸ’» CODE HINTS (1)
Use structs with uintN_t fields and bitmasks
POINTER_FREE_FLAT_LAYOUTS
When avoiding pointer chasing improves performance or serialization
βœ… RULES (3)
Use offset-based references or indexes
Avoid runtime heap allocations during traversal
Align layout with serialization format where possible
❌ ANTI-PATTERNS (2)
Heap-allocating every node or edge
Mixing raw pointers with serialized offsets
πŸ’» CODE HINTS (1)
Use arena allocators or flatbuffers
RUNTIME_FLEXIBLE_REPRESENTATION
When layout must vary at runtime based on mode or config
βœ… RULES (3)
Use tagged unions or mode enums
Factor out common fields into shared headers
Ensure ABI safety when switching layout logic
❌ ANTI-PATTERNS (2)
Branching on layout without explicit mode tagging
Letting clients infer layout from data values
πŸ’» CODE HINTS (1)
Use variant types or layout descriptors
πŸ§ͺ VALIDATION
Run memory profiler with access patterns across layout modes and measure cache hit/miss, alignment faults, and throughput.
#87Compression Matrix6 cells18 rules12 anti6 hints
Guide decisions on when and how to apply compression based on data type, latency tolerance, and access patterns.
compression_goaldata_entropy_levelaccess_frequencylatency_budgetstorage_mediumdecompression_cost
LOSSLESS_COMPRESSION_FOR_STORAGE
When long-term archival is needed with bit-exact recovery
βœ… RULES (3)
Use general-purpose compressors like gzip/zstd
Balance ratio vs decompression speed
Avoid recompressing already-compressed formats
❌ ANTI-PATTERNS (2)
Compressing JPEG or MP4 with generic algorithms
Choosing maximum compression when access is frequent
πŸ’» CODE HINTS (1)
Use zstd --fast or gzip -6 for general archiving
LOW_LATENCY_COMPRESSION_FOR_IO_BOUND
When data transfer is bottlenecked by IO and must remain fast
βœ… RULES (3)
Use fast codecs like LZ4 or Snappy
Keep block sizes small for streaming
Avoid complex entropy models
❌ ANTI-PATTERNS (2)
Using Brotli or bzip2 for hot IO paths
Batching excessively large payloads
πŸ’» CODE HINTS (1)
Use Snappy framed stream format or LZ4 blocks
COLUMNAR_COMPRESSION_FOR_ANALYTICS
When storing column-based data for scanning/filtering
βœ… RULES (3)
Use columnar formats like Parquet or ORC
Apply per-column encoding (e.g., RLE, dictionary)
Segment large files for parallel decompression
❌ ANTI-PATTERNS (2)
Storing tabular data as compressed JSON blobs
Mixing row and column formats arbitrarily
πŸ’» CODE HINTS (1)
Use Arrow or Delta Lake for columnar pipeline
LOSSY_COMPRESSION_FOR_MEDIA
When human-perceived quality is sufficient for use
βœ… RULES (3)
Choose codec by modality (e.g., JPEG for photos, AAC for audio)
Expose quality factor or bitrate knob
Avoid recompression chains that degrade cumulatively
❌ ANTI-PATTERNS (2)
Re-encoding JPEG as lossy WebP repeatedly
Compressing lossy β†’ lossless β†’ lossy
πŸ’» CODE HINTS (1)
Use ffmpeg with tuned CRF or quality presets
REALTIME_COMPRESSION_PIPELINE
When compression must happen inline with realtime stream
βœ… RULES (3)
Use non-blocking, chunk-based encoders
Balance throughput vs latency with buffer sizing
Preallocate buffers and avoid reallocs in hot path
❌ ANTI-PATTERNS (2)
Encoding entire stream as one blob
Triggering GC or malloc in critical loop
πŸ’» CODE HINTS (1)
Use ring buffers or async compression queues
STRUCTURE_AWARE_COMPRESSION
When data has predictable patterns or redundancy
βœ… RULES (3)
Analyze structure before choosing compression method
Apply dictionary, delta, or RLE where appropriate
Encode schema alongside data for self-description
❌ ANTI-PATTERNS (2)
Applying opaque compression to semi-structured formats
Compressing without analyzing field-level variance
πŸ’» CODE HINTS (1)
Use Avro, Protobuf with field-aware compression extensions
πŸ§ͺ VALIDATION
Benchmark compression ratio, encoding/decoding speed, and memory usage across representative datasets per category.
#88Encoding Matrix6 cells18 rules12 anti6 hints
Define how information is represented in memory or transmission to preserve structure, safety, and fidelity.
encoding_targethuman_readabilitybinary_vs_texterror_detectionround_trip_safetyschema_dependency
BINARY_COMPACT_ENCODING
When efficiency and size are top priorities
βœ… RULES (3)
Use varints, fixed-width fields, or delta encoding
Avoid unnecessary padding or headers
Encode length or version explicitly if required
❌ ANTI-PATTERNS (2)
Using verbose formats like XML in tight bandwidth contexts
Storing integers as UTF-8 strings
πŸ’» CODE HINTS (1)
Use Protocol Buffers, FlatBuffers, or Cap’n Proto
HUMAN_FRIENDLY_TEXT_ENCODING
When data will be read or edited by humans
βœ… RULES (3)
Use readable delimiters and indentation
Prefer UTF-8, ASCII-safe output
Escape control characters and special symbols
❌ ANTI-PATTERNS (2)
Minified or machine-only formats for config or logs
Requiring tooling to understand encoding
πŸ’» CODE HINTS (1)
Use JSON, YAML, or TOML with pretty-printing
ROUND_TRIP_SAFE_ENCODING
When serialized data must be deserialized losslessly
βœ… RULES (3)
Preserve numeric precision and type annotations
Avoid implicit coercion between string and number types
Include field presence even for empty/null values
❌ ANTI-PATTERNS (2)
Silently dropping fields or coercing types
Reconstructing objects from incomplete schema
πŸ’» CODE HINTS (1)
Use Avro or schema-annotated JSON formats
ENCODING_WITH_BUILTIN_CHECKSUMS
When data corruption or tampering must be detectable
βœ… RULES (3)
Append CRC or hash at field or block level
Fail parsing when checksum fails
Log validation failures for forensic purposes
❌ ANTI-PATTERNS (2)
Trusting payload integrity without validation
Logging invalid data as valid
πŸ’» CODE HINTS (1)
Use CBOR with checksum extension or custom wrapper
SELF_DESCRIBING_ENCODING
When decoders may not have prior knowledge of structure
βœ… RULES (3)
Embed field names, types, or version info
Allow optional fields and forward compatibility
Support fallbacks for unknown fields
❌ ANTI-PATTERNS (2)
Using pure binary formats without tags
Requiring out-of-band schema for decoding
πŸ’» CODE HINTS (1)
Use JSON-LD, Avro, or CBOR with tags
STRUCTURE_PRESERVING_ENCODED_FORMS
When data relationships must be maintained after encoding
βœ… RULES (3)
Represent pointers/refs as IDs or paths
Use explicit parent-child or edge encodings
Preserve shared vs copied node distinctions
❌ ANTI-PATTERNS (2)
Flattening nested data without identifiers
Encoding graphs as plain key-value maps
πŸ’» CODE HINTS (1)
Use RDF, GraphSON, or linked JSON structures
πŸ§ͺ VALIDATION
Deserialize encoded samples and check integrity, structure, field fidelity, and error detection behavior.
#89Binary vs Text Data Matrix6 cells18 rules12 anti6 hints
Decide when to represent data as binary vs text based on access, size, safety, and integration needs.
human_interaction_requirementsperformance_profilestorage_format_constraintsparsing_and_encoding_complexityintegration_contextsecurity_and_safety
TEXT_FOR_HUMAN_INSPECTABILITY
When data is frequently read/edited by humans
βœ… RULES (3)
Use UTF-8 or ASCII-safe formats
Avoid obfuscation or compression by default
Expose structure via indentation or delimiters
❌ ANTI-PATTERNS (2)
Encoding fields in base64 without reason
Minifying files used in ops or CI flows
πŸ’» CODE HINTS (1)
Use YAML, JSON, INI, or plaintext logs
BINARY_FOR_COMPACTNESS_AND_SPEED
When data volume or access latency is a bottleneck
βœ… RULES (3)
Use binary layout to avoid parse overhead
Choose endian-safe representation
Benchmark size and decode performance
❌ ANTI-PATTERNS (2)
Using verbose serialization in performance-critical path
Forgetting cross-platform compatibility for binary layout
πŸ’» CODE HINTS (1)
Use Protobuf, Flatbuffers, Cap’n Proto
TEXT_WHEN_INTEGRATING_WITH_UNIX_TOOLS
When data must flow through shell pipelines or logs
βœ… RULES (3)
Avoid encoding text into binary payloads
Structure lines for line-based filtering
Escape control characters if embedded
❌ ANTI-PATTERNS (2)
Dumping binary blobs into line-oriented logs
Embedding shell-breaking bytes in output
πŸ’» CODE HINTS (1)
Use newline-delimited JSON or CSV
BINARY_FOR_MEDIA_AND_SENSOR_STREAMS
When handling images, audio, telemetry, or raw byte streams
βœ… RULES (3)
Avoid transcoding unless absolutely required
Stream as raw bytes or containerized frames
Annotate format and encoding in headers
❌ ANTI-PATTERNS (2)
Converting binary to hex/base64 for internal-only transport
Wrapping media in text-based containers unnecessarily
πŸ’» CODE HINTS (1)
Use JPEG, WAV, MPEG, or packed binary protocols
TEXT_FOR_FUTURE_COMPATIBILITY
When format longevity and schema evolution are concerns
βœ… RULES (3)
Use key-value or tag-based formats
Parse ignoring unknown fields
Use extensible schemas or versioned payloads
❌ ANTI-PATTERNS (2)
Relying on rigid positional binary layout
Failing when unknown fields are encountered
πŸ’» CODE HINTS (1)
Use JSON, XML, or text+versioned wrapper
BINARY_WITH_SAFE_DECODING_GUARDS
When decoding binary data from untrusted or user-controlled sources
βœ… RULES (3)
Validate input size and structure before decode
Fail gracefully on boundary violations
Use structured parsing, not memcpy hacks
❌ ANTI-PATTERNS (2)
Blindly casting byte slices to structs
Skipping bounds checks for speed
πŸ’» CODE HINTS (1)
Use safe decoding libraries or sandboxed deserializers
πŸ§ͺ VALIDATION
Compare encoded size, parse latency, inspectability, and schema resilience across text vs binary options under test data.
#90Mass Ingestion & Context Bridge Matrix6 cells12 rules6 anti6 hints
Determines how massive term databases (600K+ entries) are ingested, indexed, scored for relevance, and bridged into the Matrix Context Engine for real-time injection into layouts.
ingestion_methodindexing_strategyrelevance_scoringinjection_target
massctx_001
When ingesting 600K+ terms from local IndexedDB, stream terms in chunks (e.g. 10K) to avoid blocking the main thread and support resumable ingestion.
βœ… RULES (2)
Use a cursor over IndexedDB object store
Ingest 10,000 terms per animation frame slice
❌ ANTI-PATTERNS (1)
Loading entire dataset into memory in one shot
πŸ’» CODE HINTS (1)
cursor.continue(); request.onsuccess = e => buffer.push(e.result);
massctx_002
To enable keyword lookup over massive datasets, construct an inverted index mapping tokens to term IDs.
βœ… RULES (2)
Tokenize all terms using standard tokenizer
Build mapping: token β†’ Set(termIDs)
❌ ANTI-PATTERNS (1)
Linear scan of terms array on every query
πŸ’» CODE HINTS (1)
index['component'] = new Set([id1, id2, id3])
massctx_003
When ranking matched terms by relevance, use BM25 scoring algorithm for context-sensitive ranking.
βœ… RULES (2)
Store term frequency (tf) and document frequency (df) per token
Calculate BM25 with tuned k1, b params
❌ ANTI-PATTERNS (1)
Sorting matches by raw frequency only
πŸ’» CODE HINTS (1)
score = bm25(tf, df, docLen, avgDocLen)
massctx_004
When context budget is limited (e.g. 1024 tokens), select top-K scoring terms to inject into Matrix Context Engine.
βœ… RULES (2)
Sort all candidates by score descending
Keep adding until budget exhausted
❌ ANTI-PATTERNS (1)
Injecting all matches regardless of token cost
πŸ’» CODE HINTS (1)
candidates.sort(byScore).slice(0, K)
massctx_005
When bridging to the Matrix Context Engine, respect the max injection window (e.g. 1024 tokens) by estimating token length of each term.
βœ… RULES (2)
Estimate token count per term (e.g. tiktoken or GPT tokenizer)
Reject terms that exceed remaining window
❌ ANTI-PATTERNS (1)
Overfilling injection buffer beyond model context size
πŸ’» CODE HINTS (1)
if (usedTokens + term.tokens <= 1024) inject(term)
massctx_006
When injecting terms into layout-aware environments, bind each term to its UI component (e.g. grid cell, tooltip, side panel) via the Maestro bridge.
βœ… RULES (2)
Maintain term β†’ component mapping dictionary
Dispatch injected terms to registered layout receivers
❌ ANTI-PATTERNS (1)
Dumping terms into UI without contextual binding
πŸ’» CODE HINTS (1)
componentMap[term.id] = 'SidebarList'; layout.inject(term)
πŸ§ͺ VALIDATION
Verify: chunking avoids memory spikes, inverted index supports fast lookup, BM25 scores are calculated correctly, context budget not exceeded, terms injected to correct layout targets via Maestro.
β–Ό πŸ”„ L4 β€” State 30 matrices
#91Stateless vs Stateful Matrix6 cells12 rules6 anti6 hints
Determines when a component or service should be stateless vs stateful β€” and the implications for scaling, testing, and complexity.
statefulnesspersistence_needscaling_impacttesting_complexity
state_001
When implementing business logic that only depends on input, use stateless pure functions.
βœ… RULES (2)
Do not reference external state
Return same output for same input
❌ ANTI-PATTERNS (1)
Reading config or DB inside function pretending to be pure
πŸ’» CODE HINTS (1)
function add(a, b) { return a + b; }
state_002
When designing services that must scale horizontally, keep them stateless with no session.
βœ… RULES (2)
Avoid per-user memory
Use token-based auth instead of sessions
❌ ANTI-PATTERNS (1)
Storing session data in server memory
πŸ’» CODE HINTS (1)
Authorization: Bearer <token>
state_003
When building UI components (e.g. modals), store temporary state locally in the component.
βœ… RULES (2)
Use React useState or equivalent
Keep state scoped to UI logic only
❌ ANTI-PATTERNS (1)
Storing UI-only state in global store
πŸ’» CODE HINTS (1)
const [open, setOpen] = useState(false);
state_004
For caching or user session needs, stateful service may be necessary (e.g. Redis, in-memory cache).
βœ… RULES (2)
Use per-user cache with TTL
Invalidate cache on logout or expiry
❌ ANTI-PATTERNS (1)
Mixing cache and persistence logic in same service
πŸ’» CODE HINTS (1)
cache.set(userId, data, { ttl: 3600 })
state_005
Convert stateful logic into stateless by externalizing state to database, cache or client.
βœ… RULES (2)
Move state reads/writes to explicit store
Inject state source into logic
❌ ANTI-PATTERNS (1)
Hardcoding state mutation into core business logic
πŸ’» CODE HINTS (1)
function process(input, state) {...}
state_006
Decide whether to use stateful/stateless based on horizontal scaling needs.
βœ… RULES (2)
Stateless scales linearly, stateful requires sticky sessions or coordination
Profile per use case
❌ ANTI-PATTERNS (1)
Forcing stateful design into stateless architecture or vice versa
πŸ’» CODE HINTS (1)
deploy --replicas=5 // stateless
πŸ§ͺ VALIDATION
Verify: stateless functions do not touch external state, services use external stores for session, stateful logic is isolated, scaling strategy fits state model.
#92Local State Matrix6 cells11 rules6 anti6 hints
Determines when state should be local to a component vs lifted to a parent or global store β€” preventing both over-sharing and prop-drilling.
scopelifting_triggersharing_patterncomplexity
local_001
When state is only used in a single component, keep it local.
βœ… RULES (2)
Use useState or local reducer
Keep logic simple and isolated
❌ ANTI-PATTERNS (1)
Lifting state to parent when no one else uses it
πŸ’» CODE HINTS (1)
const [open, setOpen] = useState(false);
local_002
When multiple sibling components need access to the same state, lift it to their nearest common parent.
βœ… RULES (2)
Move state up one level
Pass via props or context
❌ ANTI-PATTERNS (1)
Each sibling managing its own conflicting copy
πŸ’» CODE HINTS (1)
<Parent><A val={v} /><B val={v} /></Parent>
local_003
When state is passed down more than 2 levels, consider lifting to context.
βœ… RULES (2)
Avoid deep prop chains
Use context for medium-depth sharing
❌ ANTI-PATTERNS (1)
prop1 β†’ child β†’ grandchild β†’ great-grandchild
πŸ’» CODE HINTS (1)
createContext / useContext
local_004
Keep state local but notify parent via callback when update is needed upstream.
βœ… RULES (1)
Use local useState, call props.onChange on update
❌ ANTI-PATTERNS (1)
Pushing local state fully up when only reporting is needed
πŸ’» CODE HINTS (1)
props.onChange(localValue)
local_005
When state is used across routes or pages, promote to global store (e.g. Redux, Zustand).
βœ… RULES (2)
Keep global state minimal and essential
Avoid pushing temporary state globally
❌ ANTI-PATTERNS (1)
Global store bloated with UI-only state
πŸ’» CODE HINTS (1)
useStore(state => state.cart)
local_006
Co-locate state near its usage to reduce cognitive overhead and improve maintainability.
βœ… RULES (2)
Keep state and handler together
Avoid global coupling
❌ ANTI-PATTERNS (1)
Declaring state far from where it's used
πŸ’» CODE HINTS (1)
const [tab, setTab] = useState('overview')
πŸ§ͺ VALIDATION
Verify: state is not over-lifted, co-located state matches usage context, prop drilling limited to 2 levels max, global state used only when needed.
#93Global State Matrix6 cells18 rules12 anti6 hints
Define when and how global state is appropriate, and what guardrails are required for safe usage.
lifetime_and_scopeconcurrency_controlmutation_visibilityinitialization_and_shutdowntesting_and_mockingdiagnostic_observability
IMMUTABLE_GLOBAL_CONFIG
When system-wide constants or config values are needed
βœ… RULES (3)
Load from env or file exactly once
Prevent mutation after init phase
Expose via read-only API or singleton accessor
❌ ANTI-PATTERNS (2)
Allowing late or runtime modification
Reloading config into shared global
πŸ’» CODE HINTS (1)
Use static final objects or const-qualified bindings
SINGLETON_SERVICE_REGISTRY
When components need to discover shared infrastructure services
βœ… RULES (3)
Register dependencies explicitly during boot
Expose registry via controlled accessor
Support pluggable/testable overrides
❌ ANTI-PATTERNS (2)
Creating implicit global singletons on first access
Hard-wiring service discovery via static calls
πŸ’» CODE HINTS (1)
Use DI containers or service locator with lifecycle guards
THREAD_SAFE_MUTABLE_GLOBAL_STATE
When shared writable state is required (e.g., caches, metrics)
βœ… RULES (3)
Use atomic types or locks for mutation
Document and bound lifecycle of shared state
Reset or clear between test runs
❌ ANTI-PATTERNS (2)
Modifying global maps or counters without locking
Accessing mutable globals across thread boundaries unsafely
πŸ’» CODE HINTS (1)
Use synchronized blocks, RW locks, or lock-free primitives
ASYNC_CONTEXT_PROPAGATION
When global state must carry across async/task boundaries
βœ… RULES (3)
Use context-local storage or scoped propagation APIs
Avoid reliance on thread-local in async flows
Clear context after task boundary
❌ ANTI-PATTERNS (2)
Using thread-local in coroutine or async environments
Letting global context leak across unrelated requests
πŸ’» CODE HINTS (1)
Use async context wrappers or ContinuationLocal equivalents
TEST_ISOLATED_GLOBAL_MOCKING
When tests must intercept or override global state
βœ… RULES (3)
Reset or restore global after test
Wrap global in swappable interface
Avoid static final dependencies in test paths
❌ ANTI-PATTERNS (2)
Leaking global state across test cases
Hard-to-reset statics in test environments
πŸ’» CODE HINTS (1)
Use dependency injectors or test registries
OBSERVABLE_GLOBAL_DIAGNOSTICS
When global state is needed for telemetry, metrics, or inspection
βœ… RULES (3)
Expose read-only views for inspection
Avoid mutation via diagnostic interfaces
Log usage and provide dumps or snapshots
❌ ANTI-PATTERNS (2)
Letting observers mutate global state
Coupling production logic to debug flags
πŸ’» CODE HINTS (1)
Use metrics registry or diagnostic snapshot providers
πŸ§ͺ VALIDATION
Instrument global state access under load and async test scenarios; verify thread safety, context integrity, and test isolation.
#94Derived State Matrix6 cells18 rules12 anti6 hints
Define patterns for computing, caching, and validating derived state from base data sources.
derivation_triggerstaleness_policycaching_scopeconsistency_vs_costinvalidation_strategyobservability_of_change
LAZY_DERIVATION_ON_ACCESS
When derived values are expensive and infrequently used
βœ… RULES (3)
Cache result per input version
Avoid repeated derivation for same inputs
Expose derived output via memoized accessor
❌ ANTI-PATTERNS (2)
Recomputing on every access
Caching globally instead of per input context
πŸ’» CODE HINTS (1)
Use `useMemo`, `computed`, or lazy getters
EAGER_DERIVATION_ON_MUTATION
When downstream components depend on derived state immediately
βœ… RULES (3)
Trigger recomputation after any base mutation
Store derived output separately if expensive
Invalidate dependents or rerender on change
❌ ANTI-PATTERNS (2)
Letting downstream read stale derived data
Blocking mutation until all derivations complete
πŸ’» CODE HINTS (1)
Use signals, observers, or subscriptions
SCHEDULED_BACKGROUND_DERIVATION
When full recomputation is too expensive for real-time
βœ… RULES (3)
Run derivation on interval or idle window
Track freshness and show staleness in UI
Allow manual refresh as fallback
❌ ANTI-PATTERNS (2)
Assuming background derivation always finishes on time
Showing stale results as if fresh
πŸ’» CODE HINTS (1)
Use cron, revalidation TTLs, or idle queue triggers
DERIVATION_WITH_LOCAL_CACHING
When derivation is user-specific or session-scoped
βœ… RULES (3)
Cache derived values per user/session key
Evict on logout or TTL expiration
Bind derivation to reactive source context
❌ ANTI-PATTERNS (2)
Using global cache for per-user derived state
Holding unbounded per-user cache entries
πŸ’» CODE HINTS (1)
Use per-user store or request context cache
DERIVATION_FROM_STREAMED_INPUTS
When base state is a live stream or event source
βœ… RULES (3)
Use reducers or aggregators on stream
Emit derived state diffs not full snapshots
Throttle or debounce high-frequency updates
❌ ANTI-PATTERNS (2)
Recomputing entire state on each event
Dropping events during burst without accounting
πŸ’» CODE HINTS (1)
Use `scan`, `reduce`, or windowed aggregators
EXPLICIT_INVALIDATION_FOR_EXTERNAL_CHANGES
When external systems may alter base state unexpectedly
βœ… RULES (3)
Listen to mutation or notification channels
Tag derived values with source version or hash
Invalidate and refetch on mismatch
❌ ANTI-PATTERNS (2)
Trusting cache when other writers may mutate base
No logging or detection of invalid cache
πŸ’» CODE HINTS (1)
Use ETag headers, pub/sub invalidation, or webhook triggers
πŸ§ͺ VALIDATION
Simulate base mutations, external changes, and stream bursts; verify derived state freshness, cache behavior, and reactive propagation.
#95State Initialization Matrix6 cells18 rules12 anti6 hints
Define safe and predictable strategies for initializing state across systems and components.
initialization_triggerdefault_value_sourceside_effect_tolerancerepeatability_requirementasynchronous_availabilityreset_behavior
STATIC_BOOTSTRAP_STATE
When initial state can be computed or embedded at build time
βœ… RULES (3)
Embed values directly into binary or static config
Ensure values do not require runtime dependencies
Use only for globally shared constants or templates
❌ ANTI-PATTERNS (2)
Generating dynamic content at build stage
Coupling static config to environment-specific paths
πŸ’» CODE HINTS (1)
Use consts, baked files, or pre-resolved JSON
ON_DEMAND_STATE_INSTANTIATION
When state is only needed conditionally or after some interaction
βœ… RULES (3)
Delay allocation until access path triggers
Initialize with fallback or null-safe wrapper
Prevent multiple instantiations if singleton-like
❌ ANTI-PATTERNS (2)
Preloading all possible state eagerly
Letting lazy creation race across threads
πŸ’» CODE HINTS (1)
Use `useLazyRef`, factory method, or deferred constructor
RESETTABLE_LOCAL_STATE
When per-session or per-user state must be cleared periodically
βœ… RULES (3)
Scope state to context or identity
Provide explicit clear/reset hook
Log reset events for audit/debug
❌ ANTI-PATTERNS (2)
Letting global state persist across sessions
Forgetting to reset on user switch
πŸ’» CODE HINTS (1)
Use closures, `useState`, or request-bound storage
ASYNC_STATE_INITIALIZATION
When state depends on remote fetch or async operation
βœ… RULES (3)
Expose async init lifecycle or loading status
Avoid access before data arrives
Provide retry path or fallback
❌ ANTI-PATTERNS (2)
Assuming state is ready synchronously
Hiding load failures without error surface
πŸ’» CODE HINTS (1)
Use `suspense`, observable streams, or loading gates
ENVIRONMENT_DRIVEN_INITIALIZATION
When initial state must vary across deployments or roles
βœ… RULES (3)
Read from env vars, config maps, or launch args
Avoid hardcoding env-specific logic
Log resolved config source and value
❌ ANTI-PATTERNS (2)
Embedding environment flags inside logic branches
Allowing unvalidated overrides from env
πŸ’» CODE HINTS (1)
Use config loader or DI initializer
TEST_ISOLATED_STATE_SCOPES
When tests must create isolated or ephemeral state
βœ… RULES (3)
Scope state to per-test container or transaction
Use mock or stubbed values where needed
Clean up at end of test with teardown hook
❌ ANTI-PATTERNS (2)
Reusing shared state across tests
Leaving state unreset between test cases
πŸ’» CODE HINTS (1)
Use `beforeEach`, sandboxed context, or DI test harness
πŸ§ͺ VALIDATION
Test all initialization paths under concurrency, async latency, and environment overrides; confirm repeatability, freshness, and isolation.
#96State Reset Matrix6 cells18 rules12 anti6 hints
Define clear semantics and triggers for resetting application state across scopes and scenarios.
reset_triggerscope_of_resetpersistence_and_restore_policyuser_feedback_requirementsfailure_mode_handlingobservability_and_logging
USER_INITIATED_SOFT_RESET
When a user explicitly requests a reset during session
βœ… RULES (3)
Prompt confirmation if destructive
Reset only session-scoped or local state
Leave durable storage untouched
❌ ANTI-PATTERNS (2)
Clearing database or external records on UI reset
Failing to log user-initiated reset events
πŸ’» CODE HINTS (1)
Use `resetForm()`, session.clear(), or local reactive reset
AUTOMATIC_RESET_ON_CONTEXT_SWITCH
When user identity, tenant, or environment changes
βœ… RULES (3)
Detect identity/environment boundary crossing
Clear state derived from prior context
Reinitialize based on new scope
❌ ANTI-PATTERNS (2)
Carrying stale filters, selections, or auth into new session
Failing to log scope transitions
πŸ’» CODE HINTS (1)
Use effect hooks, auth change listeners, or route guards
FAILURE_TRIGGERED_STATE_PURGE
When system error or corruption requires safe fallback
βœ… RULES (3)
Detect and classify failure type
Purge or rollback affected state slice
Log failure and reset metadata
❌ ANTI-PATTERNS (2)
Retrying broken state blindly
Restoring from unverified checkpoints
πŸ’» CODE HINTS (1)
Use circuit breaker pattern or error boundaries with reset logic
PROGRAMMATIC_RESET_FROM_UPSTREAM_EVENT
When upstream service or dependency signals reset need
βœ… RULES (3)
Subscribe to reset event or webhook
Translate to local reset semantics
Log propagation and confirm downstream reset
❌ ANTI-PATTERNS (2)
Ignoring upstream invalidation triggers
Triggering resets without scoping downstream impact
πŸ’» CODE HINTS (1)
Use pub/sub or observer propagation
FULL_ENVIRONMENT_REINITIALIZATION
When application instance must be restarted or reloaded
βœ… RULES (3)
Clear all caches, memory stores, and reactive state
Restart long-lived background tasks
Log full boot cycle and init time
❌ ANTI-PATTERNS (2)
Skipping global reinit on full reset
Letting pre-reset tasks linger
πŸ’» CODE HINTS (1)
Use `app.reset()`, service container teardown, or module reload
TEST_SCOPED_STATE_RESET
When tests must reset environment between cases
βœ… RULES (3)
Clear all global and singleton state before each test
Restore mock/fake state for each run
Log which test triggered reset for traceability
❌ ANTI-PATTERNS (2)
Leaking state across test boundaries
Skipping teardown on failed tests
πŸ’» CODE HINTS (1)
Use `beforeEach`, `afterEach`, or sandbox reset APIs
πŸ§ͺ VALIDATION
Trigger all reset scenarios under user, failure, and test conditions; verify log coverage, isolation guarantees, and reinitialization behavior.
#97State Synchronization Matrix6 cells18 rules12 anti6 hints
Define when, how, and under what consistency models to synchronize distributed or local state changes.
synchronization_triggerdirectionalityconsistency_guaranteetransport_mechanismconflict_resolution_policyrecovery_and_retry_model
REALTIME_PUSH_SYNCHRONIZATION
When low-latency propagation of state is required
βœ… RULES (3)
Trigger sync via pub/sub or websocket
Push deltas, not full snapshots
Ensure delivery guarantees via retries or ACKs
❌ ANTI-PATTERNS (2)
Polling for changes at high frequency
Sending full state for every change
πŸ’» CODE HINTS (1)
Use GraphQL subscriptions, Redis pub/sub, or WebSockets
PERIODIC_PULL_SYNCHRONIZATION
When updates can be delayed without user-facing inconsistency
βœ… RULES (3)
Define polling interval based on staleness tolerance
Use timestamps or version to detect updates
Throttle fetches under high load
❌ ANTI-PATTERNS (2)
Fixed interval polling regardless of activity
Forcing full sync when nothing has changed
πŸ’» CODE HINTS (1)
Use ETags, `If-Modified-Since`, or sync cursors
BIDIRECTIONAL_STATE_REPLICATION
When two systems can both mutate shared state
βœ… RULES (3)
Track origin and timestamp/version for each update
Resolve conflicts via CRDTs, merge rules, or last-writer-wins
Ensure idempotent operations across retries
❌ ANTI-PATTERNS (2)
Syncing in both directions with no conflict model
Overwriting blindly without detecting concurrent updates
πŸ’» CODE HINTS (1)
Use operational transforms or vector clocks
ASYNC_EVENTUAL_CONSISTENCY
When strict ordering is not required, but data must converge
βœ… RULES (3)
Propagate updates asynchronously
Handle reordering and duplication defensively
Use reconciliation passes periodically
❌ ANTI-PATTERNS (2)
Assuming immediate consistency after async write
Ignoring inconsistencies in long-lived replicas
πŸ’» CODE HINTS (1)
Use message queues with deduplication and TTLs
ONE_WAY_SNAPSHOT_SYNCHRONIZATION
When syncing from source of truth to consumers only
βœ… RULES (3)
Export periodic full snapshot or delta
Include checksum or schema version
Revalidate consumer cache on mismatch
❌ ANTI-PATTERNS (2)
Letting consumer state drift without check
Allowing consumer mutation without invalidation
πŸ’» CODE HINTS (1)
Use S3 versioned snapshots, REST pull with digest headers
FAILURE_RECOVERY_RESYNCHRONIZATION
When synchronization was interrupted or failed
βœ… RULES (3)
Detect missed or failed sync attempts
Trigger catch-up or full reload based on staleness
Log recovery actions and success/failure
❌ ANTI-PATTERNS (2)
Ignoring missed updates after reconnect
Failing silently on sync failure
πŸ’» CODE HINTS (1)
Use sync checkpointing and recovery replays
πŸ§ͺ VALIDATION
Simulate bi-directional updates, network partitions, and rollback scenarios to validate eventual convergence, ordering, and conflict resolution.
#98State Consistency Matrix6 cells18 rules12 anti6 hints
Define acceptable consistency guarantees and coordination strategies between distributed or replicated states.
consistency_modelmutation_visibilitysynchronization_mechanismwrite_conflict_resolutionread_staleness_toleranceconsistency_scope
STRONG_CONSISTENCY_ENFORCEMENT
When correctness requires all nodes to see the same state at all times
βœ… RULES (3)
Use consensus protocols for coordination
Block reads/writes until quorum is achieved
Detect and resolve write conflicts before commit
❌ ANTI-PATTERNS (2)
Serving reads from stale replicas in critical paths
Assuming local commit equals global consensus
πŸ’» CODE HINTS (1)
Use Raft, Paxos, or CP systems (e.g. etcd, Zookeeper)
EVENTUAL_CONSISTENCY_MODELS
When availability and partition tolerance matter more than strict ordering
βœ… RULES (3)
Ensure data convergence under normal conditions
Use idempotent operations and last-writer-wins by default
Expose staleness metadata where useful
❌ ANTI-PATTERNS (2)
Treating eventual models as immediately consistent
Letting replicas diverge without repair mechanism
πŸ’» CODE HINTS (1)
Use Dynamo-style systems or CRDTs with gossip protocols
READ_YOUR_WRITES_CONSISTENCY
When clients must observe their own writes reliably
βœ… RULES (3)
Route reads to the same replica that served the write
Tag requests with session consistency tokens
Failover to stronger consistency on read-after-write path
❌ ANTI-PATTERNS (2)
Distributing reads randomly after write
Assuming eventual consistency will hide anomalies
πŸ’» CODE HINTS (1)
Use session tokens, stickiness, or causal links
MONOTONIC_READS_GUARANTEE
When clients require non-regression of visible state
βœ… RULES (3)
Track last-seen version per client
Avoid routing to older replicas once a newer has been seen
Replicate monotonic version chain across regions
❌ ANTI-PATTERNS (2)
Serving stale reads after client saw fresher state
Resetting version tracking on reconnect
πŸ’» CODE HINTS (1)
Use vector clocks or hybrid logical timestamps
CAUSAL_CONSISTENCY_TRACKING
When changes must be seen in a cause-before-effect order
βœ… RULES (3)
Track causality via version vectors or dependency chains
Apply updates in topologically sorted order
Propagate dependencies alongside data writes
❌ ANTI-PATTERNS (2)
Applying dependent updates before their parents
Assuming timestamp order equals causality
πŸ’» CODE HINTS (1)
Use causal consistency engines or graph-based resolution
PARTITION_SCOPED_STRONG_CONSISTENCY
When global consistency is too costly, but local consistency is required
βœ… RULES (3)
Use partitioning scheme that aligns with transactional scope
Apply consensus within partition only
Document consistency boundary for consumers
❌ ANTI-PATTERNS (2)
Assuming cross-partition reads are consistent
Mixing read/writes across consistency scopes without fencing
πŸ’» CODE HINTS (1)
Use sharded Raft or partitioned transaction logs
πŸ§ͺ VALIDATION
Simulate multi-replica updates, client failovers, and version propagation to verify consistency guarantees and boundary behaviors.
#99State Transition Matrix6 cells13 rules6 anti6 hints
Defines valid state transitions β€” which to which, conditions, side-effects per transition.
formalitycomplexityreversibilityside_effectsvalidation
state_001
When using a linear finite state machine, define an enum of states and explicit transition map with strict rejection of invalid moves.
βœ… RULES (3)
Enumerate all states as constants
Define transition map: from β†’ to
Reject transitions not in the map
❌ ANTI-PATTERNS (1)
Allowing any-to-any state jumps by default
πŸ’» CODE HINTS (1)
if (!transitions[current].includes(next)) throw new Error('Invalid transition');
state_002
When branching is allowed, check guard conditions before accepting transitions.
βœ… RULES (2)
Each transition must have guard logic
Reject if precondition not met
❌ ANTI-PATTERNS (1)
Blindly allowing branching transitions without guards
πŸ’» CODE HINTS (1)
if (!canProceed(user)) return reject('Not allowed');
state_003
When a transition occurs, execute entry/exit side-effects (e.g. logging, API call).
βœ… RULES (2)
Invoke onEnter and onExit hooks for each state
Only run effects for valid transitions
❌ ANTI-PATTERNS (1)
Triggering side-effects on failed transitions
πŸ’» CODE HINTS (1)
await states[to].onEnter?.();
state_004
When using flags (e.g. isLoading, isError), replace with explicit state enumeration to prevent Boolean soup.
βœ… RULES (2)
Model status as single state string
Allow transitions only between valid states
❌ ANTI-PATTERNS (1)
if (isLoading && !isError) ... // too many combinations
πŸ’» CODE HINTS (1)
const state = 'loading' | 'success' | 'error';
state_005
When using terminal states (e.g. completed, failed), prevent any further transitions once entered.
βœ… RULES (2)
Mark final states explicitly
Disable transitions out of final state
❌ ANTI-PATTERNS (1)
Allowing retries or navigation from final states
πŸ’» CODE HINTS (1)
if (isFinal(current)) throw new Error('No further transitions');
state_006
When modeling complex processes, use hierarchical states with nested sub-states and localized transitions.
βœ… RULES (2)
Define parent/child relationships explicitly
Sub-states inherit parent context
❌ ANTI-PATTERNS (1)
Flat list of states for deeply nested flows
πŸ’» CODE HINTS (1)
state: { parent: 'payment', substate: 'awaiting_card' }
πŸ§ͺ VALIDATION
Verify: all states enumerated, every transition has explicit from/to/condition, invalid transitions rejected, no boolean soup, terminal states have no outgoing transitions, side-effects execute only during valid transitions.
#100Finite State Machine Matrix6 cells12 rules6 anti7 hints
Determines how finite state machines are defined and used β€” states, transitions, guards, actions, and preventing invalid state combinations.
fsm_typetransition_controlguard_conditionside_effect
fsm_001
When building a basic FSM (e.g. toggle, traffic light), use enum-based states and switch-case transitions for clarity and compactness.
βœ… RULES (2)
Define all states as enum values
Use switch(action) to determine next state
❌ ANTI-PATTERNS (1)
Using string literals for state names without central enum
πŸ’» CODE HINTS (2)
enum State { Red, Green, Yellow };
switch (event) { case 'TIMER': return State.Green; }
fsm_002
When modeling complex behavior with shared sub-states, use hierarchical FSM with nested states to improve reusability and structure.
βœ… RULES (2)
Represent child states inside parent structure
Bubble events from child to parent when unhandled
❌ ANTI-PATTERNS (1)
Flat FSMs with redundant transitions across unrelated states
πŸ’» CODE HINTS (1)
state: { loggedIn: { on: { LOGOUT: 'loggedOut' }, children: { viewing: {}, editing: {} } } }
fsm_003
When a transition depends on a runtime condition, add a guard clause that blocks invalid transitions.
βœ… RULES (2)
Evaluate guard function before transitioning
Proceed only if guard returns true
❌ ANTI-PATTERNS (1)
Letting invalid transitions proceed and correcting afterward
πŸ’» CODE HINTS (1)
on: { WITHDRAW: { target: 'processing', cond: (ctx) => ctx.balance >= amount } }
fsm_004
When state entry or exit triggers actions (e.g. fetch, log), attach side-effects to state transitions explicitly.
βœ… RULES (2)
Use entry/exit handlers for side-effects
Separate side-effect logic from transition logic
❌ ANTI-PATTERNS (1)
Triggering side-effects inside reducer logic
πŸ’» CODE HINTS (1)
entry: ['logEntry'], exit: ['cleanupEffect']
fsm_005
When a state represents completion (e.g. done, error), define it as terminal with no outgoing transitions.
βœ… RULES (2)
Do not define 'on' transitions for terminal state
Use type: 'final' if supported by library
❌ ANTI-PATTERNS (1)
Adding exit transitions from terminal state
πŸ’» CODE HINTS (1)
state: { success: { type: 'final' } }
fsm_006
When debugging or designing FSMs, use visualization tools to graph states and transitions.
βœ… RULES (2)
Export FSM definition to Graphviz or XState visualizer
Validate transition paths via visual graph
❌ ANTI-PATTERNS (1)
Manually tracing transitions in console logs only
πŸ’» CODE HINTS (1)
import { inspect } from '@xstate/inspect'; inspect();
πŸ§ͺ VALIDATION
Verify: FSM definitions include valid transitions, guard clauses block invalid states, entry/exit actions isolated, terminal states defined correctly, and tooling reflects accurate graph.
#101Event-Driven State Matrix6 cells12 rules6 anti6 hints
Determines how events trigger state changes β€” event types, dispatch patterns, event ordering, and event-to-state mapping.
event_sourcedispatch_patternordering_guaranteestate_mapping
eds_001
When a user clicks a button, directly dispatch a synchronous action to update local state.
βœ… RULES (2)
Map click event to specific action type
Handle action in reducer immediately
❌ ANTI-PATTERNS (1)
Using global pub/sub for trivial local UI clicks
πŸ’» CODE HINTS (1)
onClick={() => dispatch({ type: 'INCREMENT' })}
eds_002
When a timer fires periodically, publish an event that subscribers can handle independently.
βœ… RULES (2)
Use a pub/sub system to decouple producer from consumers
Ensure handler is idempotent if multiple subscribers act
❌ ANTI-PATTERNS (1)
Tight coupling between timer and update handler
πŸ’» CODE HINTS (1)
eventBus.publish('TICK')
eds_003
When multiple events are queued, process them in FIFO order to maintain logical consistency.
βœ… RULES (2)
Queue events with timestamps or order index
Ensure reducer applies actions in queue order
❌ ANTI-PATTERNS (1)
Processing newer events before older ones without justification
πŸ’» CODE HINTS (1)
queue.push(event); processNext()
eds_004
When a component mounts/unmounts, dispatch lifecycle events directly to manage setup/teardown state.
βœ… RULES (2)
Dispatch INIT/DESTROY actions during mount/unmount
Use reducer to update lifecycle flags
❌ ANTI-PATTERNS (1)
Delaying lifecycle handlers using async dispatch unless required
πŸ’» CODE HINTS (1)
useEffect(() => { dispatch({ type: 'INIT' }); return () => dispatch({ type: 'DESTROY' }); }, [])
eds_005
When user types input, dispatch controlled value updates directly to reducer.
βœ… RULES (2)
Capture input via onChange and dispatch with payload
Update state in reducer immutably
❌ ANTI-PATTERNS (1)
Reading input from DOM instead of state
πŸ’» CODE HINTS (1)
onChange={e => dispatch({ type: 'SET_VALUE', value: e.target.value })}
eds_006
To debug past states, store events in a log and replay through the reducer to reconstruct state.
βœ… RULES (2)
Store full sequence of dispatched actions
Support replay mode in reducer with deterministic logic
❌ ANTI-PATTERNS (1)
Storing state snapshots only without events β€” no replay possible
πŸ’» CODE HINTS (1)
replay(events).reduce(reducer, initialState)
πŸ§ͺ VALIDATION
Verify: event queues processed in FIFO, all actions mapped to state transitions, lifecycle and user events dispatch immediately or via pub/sub, reducer can replay event log deterministically.
#102Reactive State Matrix6 cells18 rules12 anti6 hints
Guide how reactive state is defined, updated, observed, and disposed in reactive programming contexts.
reactivity_modelsubscription_scopeupdate_granularityobservation_triggermemory_managementunsubscription_and_disposal
FINE_GRAINED_REACTIVE_SIGNAL
When UI or logic reacts to primitive value changes
βœ… RULES (3)
Expose primitive reactive units per field
Trigger observers only on real change
Batch notifications to reduce render thrash
❌ ANTI-PATTERNS (2)
Using global objects for small reactive values
Triggering all observers on every change
πŸ’» CODE HINTS (1)
Use `signal()`, `useState()`, or fine-grained observable
STRUCTURED_DERIVED_REACTIVITY
When state depends on computation over other state
βœ… RULES (3)
Track all dependencies automatically
Memoize derived values with invalidation
Avoid side effects during derivation
❌ ANTI-PATTERNS (2)
Reading unrelated globals inside derived functions
Mutating upstream state during derivation
πŸ’» CODE HINTS (1)
Use `computed()`, `derive()`, or memoizing selectors
TRANSIENT_EFFECT_SUBSCRIPTION
When running side effects based on reactive inputs
βœ… RULES (3)
Register cleanup logic on effect scope exit
Track dependencies implicitly via usage
Avoid subscribing in render or constructor paths
❌ ANTI-PATTERNS (2)
Leaving active subscriptions on unmounted components
Running effects on every render regardless of inputs
πŸ’» CODE HINTS (1)
Use `useEffect()`, `autorun()`, or `watch()` with teardown
REACTIVE_STORE_CONTAINER
When grouping multiple related reactive values
βœ… RULES (3)
Expose actions or mutators instead of direct mutation
Group values by domain or module
Avoid nested reactivity or circular tracking
❌ ANTI-PATTERNS (2)
Storing unrelated values in the same signal/store
Allowing external mutation of store internals
πŸ’» CODE HINTS (1)
Use `createStore()`, `useReducer()`, or `writable()` store
ASYNCHRONOUS_REACTIVE_BINDING
When reactive state is driven by async fetch or mutation
βœ… RULES (3)
Expose `loading`, `error`, `data` triple explicitly
Avoid race conditions across in-flight requests
Refetch only when reactive inputs change
❌ ANTI-PATTERNS (2)
Triggering re-fetch every render
Overwriting previous requests without abort control
πŸ’» CODE HINTS (1)
Use `useQuery()`, `resource()`, or async store pattern
DISPOSABLE_REACTIVE_CONTEXT
When reactive state is short-lived and context-bound
βœ… RULES (3)
Tie reactive lifetime to component or context
Auto-cleanup observers and stores on dispose
Avoid memory retention via closures
❌ ANTI-PATTERNS (2)
Letting stores live beyond component scope
Retaining disposed context in background tasks
πŸ’» CODE HINTS (1)
Use `onCleanup()`, context providers, or scoped signal hooks
πŸ§ͺ VALIDATION
Simulate reactive updates, dependency changes, async sources, and component mount/unmount cycles; verify propagation, cleanup, and reactivity fidelity.
#103Push vs Pull State Matrix6 cells18 rules12 anti6 hints
Determine whether state should be pushed reactively or pulled imperatively based on flow patterns and system requirements.
data_freshness_requirementcontrol_flow_originstate_visibility_scopedependency_directionalitychange_frequencyconsumption_latency
PUSH_REACTIVE_PROPAGATION
When updates must propagate immediately to observers
βœ… RULES (3)
Use observable or subscription-based state
Emit on change, not on request
Ensure backpressure or debounce if high-frequency
❌ ANTI-PATTERNS (2)
Pushing on every keystroke without throttling
Coupling push emitter to concrete consumer
πŸ’» CODE HINTS (1)
Use Subject, Signal, EventEmitter with observer pattern
PULL_ON_DEMAND_QUERY
When consumers need data only occasionally
βœ… RULES (3)
Expose query/read interface
Recompute or fetch only when requested
Memoize if computation is expensive
❌ ANTI-PATTERNS (2)
Polling every N ms instead of push
Requesting full state tree for one field
πŸ’» CODE HINTS (1)
Use getter, selector, or RPC-style fetch
HYBRID_PUSH_PULL_MIX
When some parts require push and others pull
βœ… RULES (3)
Use push for hot paths and pull for cold
Bridge via reactive wrapper or caching layer
Control sync boundaries explicitly
❌ ANTI-PATTERNS (2)
Letting pull consumers subscribe accidentally
Missing update boundary in shared store
πŸ’» CODE HINTS (1)
Use `computed()`, query observers, or invalidation-driven queries
ON_EVENT_PULL_REFETCH
When state must be refreshed in response to known events
βœ… RULES (3)
Refetch only on defined triggers (e.g. tab focus, user action)
Batch multiple triggers within cooldown
Fallback to full pull if granularity lost
❌ ANTI-PATTERNS (2)
Polling in background with no user trigger
Missing refresh on critical trigger like auth change
πŸ’» CODE HINTS (1)
Use visibility change hooks or action-based loaders
DISTRIBUTED_PUSH_VIA_SUBSCRIBE
When state changes across services or clients must propagate
βœ… RULES (3)
Subscribe via pub/sub, socket, or GraphQL subscription
Filter updates by subscriber interest
Support reconnect/replay if disconnected
❌ ANTI-PATTERNS (2)
Broadcasting all changes to all clients
Tightly coupling producer to list of consumers
πŸ’» CODE HINTS (1)
Use topic-based broker (e.g. NATS, Redis, MQTT)
LOCAL_CACHE_PULL_WITH_INVALIDATION
When local cache is used to avoid frequent remote pulls
βœ… RULES (3)
Store fetched data with TTL or version
Listen for invalidation signals or triggers
Allow pull override when cache is stale
❌ ANTI-PATTERNS (2)
Treating cache as always fresh
Blocking fetches on cache miss without fallback
πŸ’» CODE HINTS (1)
Use SWR, stale-while-revalidate, or background refresh logic
πŸ§ͺ VALIDATION
Simulate both push and pull state models across hot/cold paths, refresh triggers, and remote subscriptions; verify staleness, latency, and propagation boundaries.
#104Temporal State Matrix6 cells18 rules12 anti6 hints
Define how state that changes over time is represented, queried, and retained.
time_encodingretention_policyhistorical_query_modelevent_orderingclock_sourcestate_vs_event_boundary
SNAPSHOT_STATE_WITH_TIMESTAMP_TAGGING
When tracking versioned state over time
βœ… RULES (3)
Tag each write with wall-clock or logical timestamp
Persist snapshots as discrete records
Retain snapshot history within bounded TTL
❌ ANTI-PATTERNS (2)
Overwriting state without capturing timestamp
Saving snapshots without context of what changed
πŸ’» CODE HINTS (1)
Use temporal tables, versioned rows, or append-only logs
APPEND_ONLY_EVENT_LOG
When full provenance and replayability are required
βœ… RULES (3)
Log immutable events in temporal order
Use sequential IDs or monotonic clocks
Support rebuild of current state via reducer
❌ ANTI-PATTERNS (2)
Mutating event logs retroactively
Using wall-clock timestamps as event IDs
πŸ’» CODE HINTS (1)
Use Kafka, EventStore, or durable queues
TEMPORAL_QUERIES_ON_STATE
When applications need to inspect past or future state windows
βœ… RULES (3)
Index state or events by time
Support range filters and window functions
Model state as a function of time, not only latest
❌ ANTI-PATTERNS (2)
Storing only the current value
Recomputing history via slow replays for every query
πŸ’» CODE HINTS (1)
Use bitemporal DBs or time-series engines
RETENTION_BOUNDARY_ENFORCEMENT
When state history must be limited due to cost or policy
βœ… RULES (3)
Apply TTLs or archival rules per record type
Log when records are evicted or expired
Summarize or compress historical slices as needed
❌ ANTI-PATTERNS (2)
Keeping indefinite logs with no pruning
Deleting historical data with no trace
πŸ’» CODE HINTS (1)
Use time-partitioned storage and TTL-aware retention engine
MULTI_CLOCK_ALIGNMENT
When distributed components produce data with different clocks
βœ… RULES (3)
Tag data with both source-local and canonical clock
Align using sync pulses, offsets, or hybrid clocks
Log drift or skew for reconciliation
❌ ANTI-PATTERNS (2)
Trusting all wall-clock timestamps to be in sync
Using timestamp equality as a substitute for order
πŸ’» CODE HINTS (1)
Use hybrid logical clocks, vector clocks, or NTP-corrected stamps
STATE_EVENT_MODEL_BOUNDARY_CLARITY
When both state snapshots and events exist in same system
βœ… RULES (3)
Label records clearly as state vs event
Keep event IDs and state IDs distinct
Model projections and event sourcing separately
❌ ANTI-PATTERNS (2)
Mixing snapshot records into event logs
Treating state tables as both source and sink of truth
πŸ’» CODE HINTS (1)
Use schema tags or separate tables/streams
πŸ§ͺ VALIDATION
Replay from timestamp, simulate skewed clocks, query time-ranges, and prune expired state; confirm fidelity, boundaries, and retention observability.
#105State Persistence Matrix6 cells12 rules6 anti6 hints
Determines when and how state is persisted to survive page reloads, crashes, or session boundaries β€” and how to rehydrate it.
storage_mediumpersistence_triggerrehydration_strategyconflict_resolution
persist_001
When user preferences update, persist to localStorage on each change (with debounce).
βœ… RULES (2)
Use debounced write to avoid performance hits
Serialize only necessary subset
❌ ANTI-PATTERNS (1)
Writing entire app state to localStorage on every keystroke
πŸ’» CODE HINTS (1)
debounce(() => localStorage.setItem('prefs', JSON.stringify(prefs)), 300)
persist_002
When structured data (e.g. drafts, offline actions) changes, store in IndexedDB immediately or batched.
βœ… RULES (2)
Use indexed collections per domain
Support batched writes if needed
❌ ANTI-PATTERNS (1)
Misusing localStorage for complex object graphs
πŸ’» CODE HINTS (1)
db.drafts.put({ id, content })
persist_003
When user navigates away or closes the app, persist current session state to localStorage.
βœ… RULES (2)
Bind save function to beforeunload
Throttle updates if needed
❌ ANTI-PATTERNS (1)
Relying only on onUnload β€” may not fire on crash or mobile
πŸ’» CODE HINTS (1)
window.addEventListener('beforeunload', saveState)
persist_004
Persist structured app state to IndexedDB during navigation or app shutdown.
βœ… RULES (2)
Flush buffered writes on unload
Handle write failure gracefully
❌ ANTI-PATTERNS (1)
Initiating large async IndexedDB writes inside beforeunload
πŸ’» CODE HINTS (1)
window.onunload = () => flush();
persist_005
On app startup, rehydrate state from persistent storage with schema validation.
βœ… RULES (2)
Parse and validate schema version
Fallback to defaults on mismatch or corruption
❌ ANTI-PATTERNS (1)
Blindly using parsed JSON without verifying shape
πŸ’» CODE HINTS (1)
const state = safeParse(localStorage.getItem('session'))
persist_006
When local and server state conflict (e.g. offline edits), apply conflict resolution strategy.
βœ… RULES (2)
Use timestamp or versioning for merge
Prompt user or auto-resolve based on policy
❌ ANTI-PATTERNS (1)
Overwriting newer server data with stale local copy
πŸ’» CODE HINTS (1)
if (local.updatedAt > server.updatedAt) useLocal(); else useServer();
πŸ§ͺ VALIDATION
Verify: persisted state survives reload, state rehydrates with schema checks, localStorage limited to simple data, IndexedDB used for structure, conflicts resolved correctly.
#106State Hydration Matrix6 cells18 rules12 anti6 hints
Decide how and when to rehydrate in-memory state from persistent or external sources.
hydration_triggerpersistence_mediumpartial_vs_full_scopemerge_strategyavailability_during_hydrationfallback_on_corruption
FULL_REHYDRATION_ON_BOOT
When application must restore complete state at startup
βœ… RULES (3)
Load from known-good checkpoint
Fail fast on missing or corrupt state
Log recovery time and integrity check
❌ ANTI-PATTERNS (2)
Delaying hydration until first user interaction
Starting with uninitialized state in production
πŸ’» CODE HINTS (1)
Use bootstrap reducer or state preloader
LAZY_HYDRATION_ON_ACCESS
When only a subset of state is needed based on user path
βœ… RULES (3)
Hydrate per key or scope on-demand
Cache loaded pieces locally
Provide async fallback until hydrated
❌ ANTI-PATTERNS (2)
Trying to hydrate entire tree at once
Blocking flow on missing cold paths
πŸ’» CODE HINTS (1)
Use `useLazyLoader`, selector-based cache, or segment loader
PARTIAL_HYDRATION_WITH_STALE_CHECKS
When parts of state may be outdated or externally changed
βœ… RULES (3)
Tag each slice with version/hash
Validate against remote before using
Rehydrate or invalidate on mismatch
❌ ANTI-PATTERNS (2)
Blindly using stale local state
Mixing versions within the same view
πŸ’» CODE HINTS (1)
Use ETag/version field, SWR pattern, or schema stamp
REHYDRATION_WITH_LOCAL_OVERRIDE_MERGE
When restoring from local cache with uncommitted changes
βœ… RULES (3)
Merge remote and local state with field-level logic
Flag unresolved merge conflicts
Reapply local diffs after hydration
❌ ANTI-PATTERNS (2)
Overwriting local unsaved edits
Merging without schema-aware merge rules
πŸ’» CODE HINTS (1)
Use patch merge, diff replay, or optimistic cache
READONLY_STATE_REHYDRATION
When state is static or derived externally
βœ… RULES (3)
Mark state as readonly or view-only
Fetch once or subscribe passively
Avoid exposing setters or mutators
❌ ANTI-PATTERNS (2)
Allowing edits to mirrored read-only data
Exposing stale readonly data without update path
πŸ’» CODE HINTS (1)
Use frozen structures, readonly decorators, or shadow model
HYDRATION_FAILURE_RECOVERY_PATHS
When hydration source may be missing, corrupt, or unavailable
βœ… RULES (3)
Fallback to default or guest state
Log hydration errors with context
Offer user retry or reset UI
❌ ANTI-PATTERNS (2)
Crashing app on hydration failure
Silently continuing with uninitialized state
πŸ’» CODE HINTS (1)
Use try/catch with retry logic or degraded mode bootstrap
πŸ§ͺ VALIDATION
Simulate rehydration from partial, corrupted, or remote sources; test diff merging, stale detection, and fallback flows under load and latency.
#107State Isolation Matrix6 cells18 rules12 anti6 hints
Decide when and how to isolate state to prevent coupling, leakage, or cross-context interference.
isolation_boundarylifecycle_scopemutation_visibilitysharing_policytestability_constraintsresource_cleanup
PER_COMPONENT_STATE_SCOPE
When UI components manage their own state
βœ… RULES (3)
Declare state inside component body
Avoid storing cross-component state in local variables
Reset state on unmount
❌ ANTI-PATTERNS (2)
Leaking state into global or shared context
Reusing mutable references across instances
πŸ’» CODE HINTS (1)
Use `useState`, reactive scope, or instance-bound store
PER_SESSION_OR_USER_SCOPE
When state must persist per identity or session
βœ… RULES (3)
Store state keyed by session/user identifier
Wipe or rotate on login/logout
Avoid caching globally without ownership tag
❌ ANTI-PATTERNS (2)
Reusing request-scoped cache across sessions
Binding session state to static global var
πŸ’» CODE HINTS (1)
Use per-session container, middleware wrapper, or identity-bound context
THREAD_LOCAL_STATE_FOR_PARALLELISM
When concurrent threads/processes must hold isolated values
βœ… RULES (3)
Use thread-local storage or fiber-local context
Avoid sharing mutable references across threads
Clean up on thread exit or reuse
❌ ANTI-PATTERNS (2)
Using shared static vars across threads
Relying on request ID without proper isolation
πŸ’» CODE HINTS (1)
Use `ThreadLocal`, async context, or coroutine-local storage
SANDBOXED_TEST_STATE
When tests must run in complete isolation
βœ… RULES (3)
Spin up new state container per test
Reset all mocks and injected state
Verify no state bleed between tests
❌ ANTI-PATTERNS (2)
Sharing mocks or config between tests without reset
Reusing application context without teardown
πŸ’» CODE HINTS (1)
Use `beforeEach`, containerization, or DI sandbox
ISOLATED_BACKGROUND_TASK_STATE
When background jobs hold state across retries or attempts
βœ… RULES (3)
Bind state to job ID or context
Clean up after success/failure
Retry with fresh state if corrupted
❌ ANTI-PATTERNS (2)
Letting background jobs mutate global state
Accumulating state across retries blindly
πŸ’» CODE HINTS (1)
Use scoped job context, retry-safe store, or ephemeral state handler
ISOLATED_MICROSERVICE_STATE_MODEL
When services manage their own persistent and transient state
βœ… RULES (3)
Define state boundaries via service contracts
Avoid shared DBs or caches across services
Track ownership and mutation rights explicitly
❌ ANTI-PATTERNS (2)
Accessing internal state of peer services
Leaking internal state schema via external API
πŸ’» CODE HINTS (1)
Use encapsulated DB, bounded context model, and API faΓ§ade
πŸ§ͺ VALIDATION
Run concurrency, teardown, and boundary tests to verify no cross-scope leakage, correct lifecycle handling, and proper cleanup behavior.
#108State Sharing Matrix6 cells18 rules12 anti6 hints
Define controlled patterns for sharing state across modules, scopes, or systems.
sharing_boundaryvisibility_controlownership_modellifecycle_alignmentcoupling_riskchange_propagation_mechanism
EXPLICIT_CONTEXT_SHARING
When state must be shared within a defined component tree
βœ… RULES (3)
Provide shared state via explicit context
Scope context to minimal tree subtree
Document dependencies on shared context
❌ ANTI-PATTERNS (2)
Passing props through 5+ layers
Using hidden singleton as shared state source
πŸ’» CODE HINTS (1)
Use `React.Context`, DI container, or scoped provider
SHARED_MODULE_SINGLETON
When multiple consumers need access to shared logic or cache
βœ… RULES (3)
Encapsulate state inside a module singleton
Expose interaction via public API only
Guard against premature initialization
❌ ANTI-PATTERNS (2)
Accessing internal state directly from consumers
Using shared singleton across tests without reset
πŸ’» CODE HINTS (1)
Use factory pattern or export pattern with caching
CROSS_TAB_STATE_BROADCAST
When multiple browser tabs or windows need to sync state
βœ… RULES (3)
Broadcast only diffs or intents
Throttle or debounce broadcasts to avoid churn
Use versioning or clock to resolve conflicts
❌ ANTI-PATTERNS (2)
Syncing full state every few ms
Forgetting to unsubscribe on tab close
πŸ’» CODE HINTS (1)
Use `BroadcastChannel`, `localStorage` events, or SharedWorker
SHARED_BACKEND_SESSION_STATE
When multiple frontend clients interact with the same backend session
βœ… RULES (3)
Centralize session state in backend
Emit deltas or state snapshots on mutation
Route via secure, scoped user channel
❌ ANTI-PATTERNS (2)
Allowing clients to diverge silently
Tightly coupling backend session to UI model
πŸ’» CODE HINTS (1)
Use WebSocket session channel or REST polling with ETag
INTER_MODULE_STORE_REFERENCE
When multiple modules need to read/write shared store
βœ… RULES (3)
Expose store reference via shared registry or injection
Ensure each module owns only part of the store
Avoid deep mutation outside owning module
❌ ANTI-PATTERNS (2)
Sharing entire global store object without guards
Mutating shared state in downstream utility code
πŸ’» CODE HINTS (1)
Use registry-based store locator or modular reducers
ASYNC_STATE_SHARING_VIA_STREAMS
When state must be observed and updated asynchronously
βœ… RULES (3)
Emit state changes via observable or event stream
Use subscription-based consumption
Manage lifecycle and teardown for listeners
❌ ANTI-PATTERNS (2)
Overloading async streams with stateful logic
Allowing unbounded memory growth in listeners
πŸ’» CODE HINTS (1)
Use RxJS Subject, async generator, or broadcast channel
πŸ§ͺ VALIDATION
Simulate shared state flows across tabs, sessions, modules, and time; test freshness, isolation, teardown, and version convergence.
#109Concurrency State Matrix6 cells18 rules12 anti6 hints
Define how state behaves under concurrent access and what models ensure safety and performance.
access_patternconflict_resolution_strategyisolation_levelsynchronization_mechanismfairness_requirementfailure_visibility
LOCK_BASED_MUTUAL_EXCLUSION
When shared state is accessed by multiple threads or tasks
βœ… RULES (3)
Use locks or mutex around critical sections
Minimize lock duration and contention
Document invariants protected by lock
❌ ANTI-PATTERNS (2)
Using coarse locks across unrelated data
Assuming atomicity without enforcement
πŸ’» CODE HINTS (1)
Use `synchronized`, `Mutex`, or `std::lock_guard`
LOCK_FREE_ATOMIC_STATE
When low-latency updates are needed without blocking
βœ… RULES (3)
Use atomic variables with compare-and-swap (CAS)
Avoid torn reads or writes
Keep update logic simple and retry-safe
❌ ANTI-PATTERNS (2)
Simulating atomic behavior with booleans and if-else
Ignoring memory model or visibility guarantees
πŸ’» CODE HINTS (1)
Use `AtomicInteger`, `std::atomic`, or volatile-safe wrappers
ACTOR_MODEL_SERIALIZATION
When each actor owns its own isolated state
βœ… RULES (3)
Use message inbox for all state mutation
Avoid shared mutable state between actors
Define mailbox capacity and overflow policy
❌ ANTI-PATTERNS (2)
Reading or writing external state inside actor handler
Sending direct references instead of messages
πŸ’» CODE HINTS (1)
Use Akka actor, Erlang process, or async handler queue
ISOLATED_STATE_PER_UNIT_OF_PARALLELISM
When parallel workers must avoid stepping on shared data
βœ… RULES (3)
Sharding or indexing by parallel unit ID
Avoid global access from within workers
Combine results only at final reduce phase
❌ ANTI-PATTERNS (2)
Having all workers write to same map or counter
Uncoordinated writes to overlapping regions
πŸ’» CODE HINTS (1)
Use per-thread buffers or partitioned hashmaps
COORDINATED_TRANSACTIONAL_STATE
When multiple changes must happen atomically
βœ… RULES (3)
Group mutations into transactions
Commit only after all preconditions validate
Log or rollback on partial failure
❌ ANTI-PATTERNS (2)
Half-applied changes on error
Ignoring failure cases in multi-mutation flows
πŸ’» CODE HINTS (1)
Use DB transactions, Saga, or STM
EVENTUAL_STATE_PROPAGATION
When strict ordering is not required but state must sync across nodes
βœ… RULES (3)
Broadcast deltas or events via async channels
Support merge function on update receipt
Log divergence and convergence over time
❌ ANTI-PATTERNS (2)
Assuming immediate visibility across replicas
Overwriting without version comparison
πŸ’» CODE HINTS (1)
Use CRDTs, message queues, or gossip sync
πŸ§ͺ VALIDATION
Run concurrent stress tests, race detectors, and state integrity checkers to confirm correctness under contention and parallel updates.
#110Race Condition Matrix6 cells18 rules12 anti6 hints
Identify, prevent, and mitigate race conditions that arise from concurrent or interleaved operations.
race_trigger_patternscope_of_conflictdetection_methodmitigation_strategyretry_policylog_and_alerting
ASYNC_RESPONSE_OVERWRITE
When multiple async requests resolve out of order
βœ… RULES (3)
Tag each request with logical version
Apply result only if version matches current
Cancel outdated requests when possible
❌ ANTI-PATTERNS (2)
Always using latest response regardless of trigger
Lack of version control in overlapping fetches
πŸ’» CODE HINTS (1)
Use request tokens, AbortController, or race guards
DOM_EVENT_RACE_COLLISION
When DOM or UI interactions trigger overlapping state changes
βœ… RULES (3)
Debounce or throttle high-frequency triggers
Guard transition logic with current state checks
Ignore or queue redundant transitions
❌ ANTI-PATTERNS (2)
Allowing double submission on rapid click
Binding animation and update to the same clock edge
πŸ’» CODE HINTS (1)
Use `disabled` flag, debounce, or transition locks
SHARED_RESOURCE_ACCESS
When multiple actors access and mutate a shared resource
βœ… RULES (3)
Use locks, mutexes, or job queues
Partition by ownership or namespace
Avoid in-place updates without fencing
❌ ANTI-PATTERNS (2)
Modifying global cache from multiple flows
Writing to shared memory with no coordination
πŸ’» CODE HINTS (1)
Use semaphore, critical section wrapper, or ownership token
INTERLEAVED_SCHEDULING_RACES
When system schedules or threads overlap due to async behavior
βœ… RULES (3)
Capture required state before async yields
Avoid mutating shared state post-await
Scope side effects to the resolved task only
❌ ANTI-PATTERNS (2)
Reading stale variables after await
Assuming sequential semantics in async callbacks
πŸ’» CODE HINTS (1)
Use closures, task-scoped vars, or zone-local context
WRITE_AFTER_INVALIDATION
When invalidated or stale state gets written post-change
βœ… RULES (3)
Check state freshness or version before write
Reject mutation if precondition no longer holds
Log attempted writes after scope change
❌ ANTI-PATTERNS (2)
Allowing writes from dismissed views or sessions
Committing UI state from obsolete lifecycle phase
πŸ’» CODE HINTS (1)
Use stale guard, lifecycle hook checks, or session ID
RACE_RECOVERY_AND_DIAGNOSTICS
When race causes must be triaged or mitigated post-factum
βœ… RULES (3)
Log all race-relevant transitions and timestamps
Use tracing or replay systems for root cause analysis
Expose guard failures for metrics and alerting
❌ ANTI-PATTERNS (2)
Failing silently or ignoring rare race manifestations
Overwriting logs that contain race timing info
πŸ’» CODE HINTS (1)
Use structured logs, spans, or race replay buffers
πŸ§ͺ VALIDATION
Run fuzz tests, timing skews, and injected delays to verify race conditions are detected, mitigated, or diagnosed properly.
#111Matrix 111 β€” Locking Strategy Matrix6 cells18 rules18 anti6 hints
Define when and how to apply locks to shared resources, balancing correctness with performance and deadlock avoidance.
lock_typelock_granularitydeadlock_preventiontimeout_behaviordistributed_vs_locallock_ownership
EXCLUSIVE_WRITE_LOCKS
When only one writer must access resource at a time
βœ… RULES (3)
Use mutex or exclusive lock construct
Hold lock only for write-critical section
Avoid nested locks when possible
❌ ANTI-PATTERNS (3)
Holding locks across async boundaries
Acquiring multiple write locks in chain
Allowing reentrancy without check
πŸ’» CODE HINTS (1)
mutex.acquire(); try { ... } finally { mutex.release(); }
READ_WRITE_LOCK_BALANCING
When reads are frequent and writes are rare
βœ… RULES (3)
Use ReadWriteLock pattern
Allow multiple readers but exclusive writer
Implement fairness if needed
❌ ANTI-PATTERNS (3)
Readers always blocking writers
Favoring readers in write-heavy apps
Missing upgrade logic from read to write
πŸ’» CODE HINTS (1)
rwLock.readLock().lock(); ... rwLock.writeLock().lock();
DISTRIBUTED_LOCKS_FOR_SHARED_RESOURCES
When multiple nodes need to coordinate over shared resource
βœ… RULES (3)
Use external system like Redis, Zookeeper, or etcd
Set TTL on locks to prevent stuck states
Handle retries and clock skew gracefully
❌ ANTI-PATTERNS (3)
Using in-memory locks for cross-node coordination
Assuming lock TTL equals task duration
Ignoring split-brain scenarios
πŸ’» CODE HINTS (1)
SET resource_key my_id NX PX 3000 (Redis)
OPTIMISTIC_LOCKING_STRATEGY
When minimizing lock contention in high-throughput writes
βœ… RULES (3)
Use versioning or timestamps for conflict detection
Retry only on version mismatch
Avoid holding actual locks
❌ ANTI-PATTERNS (3)
Skipping version check on update
Writing without read-verify step
Retrying indefinitely without backoff
πŸ’» CODE HINTS (1)
UPDATE ... WHERE version = ?
TIMEOUT_AND_BACKOFF_CONTROL
When acquiring locks in systems prone to contention
βœ… RULES (3)
Set max wait time when acquiring
Use exponential backoff on retries
Log and alert on repeated lock failures
❌ ANTI-PATTERNS (3)
Waiting indefinitely for lock
Retry loops without delay
Swallowing lock acquisition errors silently
πŸ’» CODE HINTS (1)
lock.tryAcquire(timeout); retryWithBackoff()
LOCK_OWNERSHIP_HANDOFF
When transferring lock control between tasks or systems
βœ… RULES (3)
Record current lock owner ID
Support explicit transfer protocols
Release old lock before acquiring new
❌ ANTI-PATTERNS (3)
Assuming single task holds lock forever
Transferring ownership implicitly
Failing to release lock on crash
πŸ’» CODE HINTS (1)
metadata.lockOwner = processId
πŸ§ͺ VALIDATION
Simulate contention scenarios with logging. Monitor throughput, deadlocks, lock wait times. Test ownership, expiration, and conflict behavior under load.
#112Optimistic Update Matrix6 cells18 rules12 anti6 hints
Define how and when to apply optimistic UI updates and how to reconcile them with server truth.
trigger_of_optimismrollback_strategyconcurrent_update_handlingserver_reconciliation_mechanismuser_feedback_during_pendingidempotency_and_retry
OPTIMISTIC_UI_ON_USER_ACTION
When user actions imply intent to mutate state
βœ… RULES (3)
Apply local update before network call
Queue network mutation with context
Rollback on error and notify user
❌ ANTI-PATTERNS (2)
Waiting for server before visual feedback
Allowing inconsistent state if mutation fails
πŸ’» CODE HINTS (1)
Use mutation hooks with optimistic state preview
ROLLBACK_ON_FAILURE_WITH_CONTEXT
When server rejects optimistic mutation
βœ… RULES (3)
Track pre-mutation state snapshot
Apply reverse patch or state diff
Log and alert on rollback events
❌ ANTI-PATTERNS (2)
Resetting entire state blindly
Failing to distinguish transient vs permanent failure
πŸ’» CODE HINTS (1)
Use reducer-based undo stack or mutation journal
MERGE_ON_SERVER_RESPONSE
When server result contains authoritative state
βœ… RULES (3)
Replace or merge based on field granularity
Retain local-only fields if safe
Track reconciliation path in logs
❌ ANTI-PATTERNS (2)
Overwriting optimistic update with full server blob
Losing user edits made post-optimism
πŸ’» CODE HINTS (1)
Use patch merge, field-based update strategy
IDEMPOTENT_RETRY_LOGIC
When optimistic action may be retried due to network instability
βœ… RULES (3)
Use mutation keys or deduplication tokens
Track mutation in-flight and result status
Apply retry with exponential backoff
❌ ANTI-PATTERNS (2)
Submitting identical mutation without dedupe
Assuming retry will always result in same state
πŸ’» CODE HINTS (1)
Use SWR mutation key or operation fingerprint
PENDING_STATE_UI_FEEDBACK
When user needs visibility into optimistic operation state
βœ… RULES (3)
Show inline loader or optimistic highlight
Disable repeated triggers until confirmation
Expose error hint on failure
❌ ANTI-PATTERNS (2)
Letting user believe change is permanent immediately
Silently reverting UI on error
πŸ’» CODE HINTS (1)
Use toast, badge, or spinner bound to mutation status
CONCURRENT_OPTIMISTIC_PATH_CONFLICTS
When multiple optimistic updates target overlapping state
βœ… RULES (3)
Isolate mutation contexts per operation
Serialize or queue conflicting intents
Apply last-known-good checkpoint on conflict
❌ ANTI-PATTERNS (2)
Allowing parallel optimistic updates on same field
Overlapping updates with no conflict detection
πŸ’» CODE HINTS (1)
Use patch queues, mutation lanes, or context-specific snapshots
πŸ§ͺ VALIDATION
Inject optimistic updates with failure, delay, and conflict; validate rollback integrity, UI feedback, and server truth merge behavior.
#113Pessimistic Update Matrix6 cells18 rules12 anti6 hints
Determine how to handle UI and system state updates only after server confirmation, ensuring strict correctness.
confirmation_strategyblocking_ui_behaviorerror_feedback_handlingretry_path_logicuser_experience_mitigationsynchronization_model
STRICT_UI_BLOCK_UNTIL_CONFIRM
When state must not change until remote system accepts mutation
βœ… RULES (3)
Disable triggering element while pending
Avoid pre-rendering updated state
Expose loading indicator and block re-entry
❌ ANTI-PATTERNS (2)
Letting user click twice during API delay
Showing change before server acknowledges
πŸ’» CODE HINTS (1)
Use `await mutate()`, disable button, show spinner
POST_CONFIRMATION_STATE_UPDATE
When only server-confirmed updates should affect local state
βœ… RULES (3)
Update local store only on successful response
Bind update logic to resolved payload
Handle divergence if server result differs from intent
❌ ANTI-PATTERNS (2)
Assuming server mirrored local mutation
Ignoring mismatch between request and response
πŸ’» CODE HINTS (1)
Use response payload to update store, not original input
ERROR_FEEDBACK_AND_RETRY_PATH
When mutation fails and user must respond
βœ… RULES (3)
Show clear error message inline or as toast
Offer retry with same or edited input
Log failure reason for debugging
❌ ANTI-PATTERNS (2)
Swallowing errors silently
Restarting flow without context of prior failure
πŸ’» CODE HINTS (1)
Use error boundary, toast handler, or retry modal
USER_EXPERIENCE_SMOOTHING
When strict confirmation introduces noticeable latency
βœ… RULES (3)
Use optimistic spinner, ghost element, or disabled placeholder
Transition visually after confirmation rather than instantly
Delay UI unlock until commit completes
❌ ANTI-PATTERNS (2)
Freezing UI with no feedback
Interrupting user flow on every minor delay
πŸ’» CODE HINTS (1)
Use transition states and suspense zones
SYNC_SERVER_ACK_LOGIC
When multiple updates depend on strict sequencing
βœ… RULES (3)
Wait for response before next mutation or navigation
Queue dependent actions until ack received
Track in-flight vs committed mutation state
❌ ANTI-PATTERNS (2)
Triggering navigation on click before save confirms
Running chained updates without guarding dependency
πŸ’» CODE HINTS (1)
Use mutation queue or `await` chain for dependent actions
RETRY_SAFE_MUTATION_CONTRACTS
When network unreliability or backend load may cause failure
βœ… RULES (3)
Make mutation idempotent with operation ID
Expose retry UI and policy
Avoid duplicate writes or visual flicker
❌ ANTI-PATTERNS (2)
Blindly retrying without deduplication
Showing flickering UI on each attempt
πŸ’» CODE HINTS (1)
Use mutation key, retry policy with backoff, and persistent mutation log
πŸ§ͺ VALIDATION
Simulate network failures, delays, divergence between intent and result, and retry loops to validate strict update behavior and UX coherence.
#114Conflict Resolution Matrix6 cells18 rules12 anti6 hints
Define consistent strategies for resolving concurrent or divergent state updates in distributed or multi-source systems.
conflict_detection_methodresolution_authoritymerge_strategyuser_visibility_of_conflictundo_or_revert_pathlogging_and_auditability
LAST_WRITE_WINS
When conflicting updates must resolve automatically
βœ… RULES (3)
Tag updates with logical timestamp
Accept latest version deterministically
Log overwritten values for inspection
❌ ANTI-PATTERNS (2)
Assuming newest is always correct semantically
Overwriting without trace
πŸ’» CODE HINTS (1)
Use Lamport timestamps or server clock
MANUAL_MERGE_RESOLUTION
When data accuracy is critical and multiple truths may exist
βœ… RULES (3)
Present side-by-side conflicting inputs
Allow override with audit trail
Retain both versions when undecided
❌ ANTI-PATTERNS (2)
Auto-resolving without user input
Failing silently on unresolved conflict
πŸ’» CODE HINTS (1)
Use diff viewer or merge modal in UI
FIELD_LEVEL_MERGING
When some parts of object are conflicted but others are not
βœ… RULES (3)
Detect conflicts per field or section
Apply merge policy per field (e.g., max, union, latest)
Avoid discarding entire object on partial conflict
❌ ANTI-PATTERNS (2)
Blowing away full records on minor diff
Ignoring per-field resolution options
πŸ’» CODE HINTS (1)
Use structured merge with field precedence map
INTENT_BASED_RESOLUTION
When operations encode meaning beyond raw data
βœ… RULES (3)
Track mutation type and semantic goal
Resolve in order of operation significance
Preserve action log for traceability
❌ ANTI-PATTERNS (2)
Overwriting intent-based changes with stale bulk payload
Assuming all mutations are value replacements
πŸ’» CODE HINTS (1)
Use command pattern or domain events
VERSION_VECTOR_MERGE_PROTOCOL
When distributed replicas make concurrent changes
βœ… RULES (3)
Track version per source or replica
Detect and resolve divergent histories
Apply CRDTs or structured merge with version trace
❌ ANTI-PATTERNS (2)
Using scalar versioning in multi-writer systems
Losing causality in overwrite merges
πŸ’» CODE HINTS (1)
Use vector clocks, Lamport clocks, or CRDT frameworks
AUDITABLE_CONFLICT_LOGGING_AND_REPLAY
When conflicts must be reviewed or replayed for audit
βœ… RULES (3)
Log both sides of all conflicts
Attach metadata like timestamp, source, diff
Support replay or export of conflict records
❌ ANTI-PATTERNS (2)
Resolving conflicts silently without trace
Dropping conflicting input without log
πŸ’» CODE HINTS (1)
Use audit log stream, diff serializer, or replay bus
πŸ§ͺ VALIDATION
Inject synthetic conflicts (field-level, version, intent-based); verify merge behavior, logging, resolution UI, and correctness in replay.
#115Input Constraint Matrix6 cells12 rules6 anti6 hints
Determines how input is constrained at the field level β€” max length, pattern, masking, allowed characters, and live formatting.
constraint_typeenforcement_methodui_feedbackdata_integrity
input_001
When a field has fixed length (e.g. ZIP code), use maxlength attribute to limit user input at HTML level.
βœ… RULES (2)
Set maxlength=X on <input>
Pair with proper label and format hint
❌ ANTI-PATTERNS (1)
Allowing overflow into backend
πŸ’» CODE HINTS (1)
<input maxlength='5' />
input_002
When only certain characters are allowed (e.g. alphanumeric), use pattern attribute or JavaScript filter to constrain.
βœ… RULES (2)
Enforce regex on keypress and paste
Reject or sanitize invalid input
❌ ANTI-PATTERNS (1)
Allowing emoji in numeric fields
πŸ’» CODE HINTS (1)
/^[a-zA-Z0-9]+$/
input_003
When a format must be followed (e.g. phone, credit card), apply input mask to guide user live.
βœ… RULES (2)
Show placeholder for expected format
Insert characters as user types
❌ ANTI-PATTERNS (1)
Free text input for credit card
πŸ’» CODE HINTS (1)
inputmask('(999) 999-9999')
input_004
When input must be numeric, prevent entry of non-digits via key filtering.
βœ… RULES (2)
Use inputmode=numeric and pattern=\d*
Block keydown for non-digit keys
❌ ANTI-PATTERNS (1)
Relying solely on post-input validation
πŸ’» CODE HINTS (1)
<input inputmode='numeric' pattern='\d*' />
input_005
When possible, provide live preview (e.g. username URL, password strength) as user types.
βœ… RULES (2)
Update preview in real time
Indicate validation state clearly
❌ ANTI-PATTERNS (1)
Showing preview only after submit
πŸ’» CODE HINTS (1)
onInput: updatePreview(input.value)
input_006
When consistent formatting improves readability (e.g. credit card spacing), auto-insert delimiters during typing.
βœ… RULES (2)
Insert space or dash after X digits
Keep cursor position logical
❌ ANTI-PATTERNS (1)
User must type spaces manually
πŸ’» CODE HINTS (1)
formatWithSpaces('4111111111111111') β†’ '4111 1111 1111 1111'
πŸ§ͺ VALIDATION
Verify: max length enforced, disallowed characters blocked, masking applied, numeric keys only allowed, preview shown live, delimiters auto-inserted.
#116Undo / Redo Matrix6 cells18 rules12 anti6 hints
Define how to implement reversible operations, including user undo/redo flows and system rollback.
operation_granularityhistory_retention_modelserialization_of_actionsboundary_scopingconflict_with_external_statepresentation_to_user
COMMAND_PATTERN_FOR_UNDOABLE_ACTIONS
When actions can be expressed as discrete reversible units
βœ… RULES (3)
Encapsulate each mutation as a command object
Implement `do` and `undo` methods
Chain compound operations with transactional semantics
❌ ANTI-PATTERNS (2)
Recording state diffs without re-executable logic
Tying command format to UI component
πŸ’» CODE HINTS (1)
Use command queue with undo/redo stack
STATE_DIFF_AND_PATCH_TRACKING
When state is large but only a small diff changes
βœ… RULES (3)
Compute before/after diffs per change
Store both forward and reverse patches
Collapse or coalesce trivial diffs
❌ ANTI-PATTERNS (2)
Snapshotting entire state on each change
Keeping irreversible diffs in circular buffer
πŸ’» CODE HINTS (1)
Use diffing engine, structural patcher
USER_ACTION_GROUPING
When a series of actions should undo as one logical step
βœ… RULES (3)
Start and end group boundaries explicitly
Collapse grouped actions into single undo record
Expose grouped label in UI history if applicable
❌ ANTI-PATTERNS (2)
Undoing every keystroke as a separate action
Auto-grouping without explicit bounds
πŸ’» CODE HINTS (1)
Use `beginGroup()` / `endGroup()` markers
CROSS_CONTEXT_UNDO_CONSTRAINTS
When undo must span or respect multiple state contexts
βœ… RULES (3)
Tag undo records with scope ID or context
Disallow undo if dependent context no longer valid
Rollback cross-context only if all are resolvable
❌ ANTI-PATTERNS (2)
Undoing one part of a compound transaction
Applying undo blindly across lifecycles
πŸ’» CODE HINTS (1)
Use scoped history stack or domain-bound record
PERSISTED_HISTORY_FOR_RELOAD_RECOVERY
When undo/redo state must survive app refresh or crash
βœ… RULES (3)
Serialize undo/redo stack to localStorage/session
Replay and validate history on restore
Trim long histories based on session policy
❌ ANTI-PATTERNS (2)
Clearing undo state on reload
Storing sensitive diffs without encryption
πŸ’» CODE HINTS (1)
Use JSON snapshot + journal + history pointer
UNDO_UI_AND_FEEDBACK_MODEL
When users need control over reversal of their actions
βœ… RULES (3)
Show undo affordance immediately post-action
Disable redo unless an undo was performed
Highlight affected elements during undo/redo
❌ ANTI-PATTERNS (2)
Hiding undo behind long menus
Allowing undo of destructive irreversible actions
πŸ’» CODE HINTS (1)
Use snackbar with undo CTA, or keyboard shortcut + visual cue
πŸ§ͺ VALIDATION
Simulate long undo chains, cross-context state changes, grouped rollbacks, and post-crash restore. Confirm integrity, traceability, and user experience.
#117Snapshot Matrix6 cells18 rules12 anti6 hints
Define when and how to capture and use snapshots of application or system state for consistency, recovery, or tracking.
snapshot_triggerscope_of_snapshotstorage_mediumconsistency_modelretention_policyrecovery_and_access
PERIODIC_STATE_SNAPSHOT
When application state should be saved on a fixed schedule
βœ… RULES (3)
Capture entire state tree at intervals
Store with timestamp and version
Purge old snapshots based on TTL or limit
❌ ANTI-PATTERNS (2)
Snapshotting at inconsistent or arbitrary intervals
Failing to validate snapshot integrity
πŸ’» CODE HINTS (1)
Use `setInterval` with `serialize(state)` or DB checkpoint
EVENT_TRIGGERED_SNAPSHOT
When specific changes or milestones require preserving state
βœ… RULES (3)
Trigger snapshot on key state transitions
Log reason and metadata alongside snapshot
Tag for retention or rollback eligibility
❌ ANTI-PATTERNS (2)
Missing snapshot during significant system change
Not labeling manual vs auto snapshot
πŸ’» CODE HINTS (1)
Use lifecycle hook or reducer tap to snapshot on change
USER_INITIATED_SNAPSHOT_CAPTURE
When users should be able to bookmark or version state
βœ… RULES (3)
Expose snapshot action in UI
Name or tag snapshot with user context
Limit redundant captures by hash or delta
❌ ANTI-PATTERNS (2)
Allowing uncontrolled snapshot spam
Failing to restore snapshot accurately
πŸ’» CODE HINTS (1)
Use β€˜Save Version’ CTA or bookmarkable route hash
PRE_EXECUTION_SNAPSHOT_FOR_ROLLBACK
When actions might fail and state should be recoverable
βœ… RULES (3)
Capture state just before mutation
Store snapshot transactionally with mutation intent
Offer undo or rollback path if operation fails
❌ ANTI-PATTERNS (2)
Applying critical updates without backup
Restoring stale snapshot after external mutation
πŸ’» CODE HINTS (1)
Use undo middleware or mutation guard
INCREMENTAL_SNAPSHOT_CHAINING
When state is large and full snapshot is expensive
βœ… RULES (3)
Store base + patch chain or differential deltas
Prune chain periodically via full snapshot
Ensure atomic write and merge semantics
❌ ANTI-PATTERNS (2)
Merging deltas without base validation
Letting chains grow indefinitely
πŸ’» CODE HINTS (1)
Use `diff(stateA, stateB)` and rolling compaction
RESTORE_AND_REPLAY_FROM_SNAPSHOT
When full system state must be restored and resumed
βœ… RULES (3)
Restore snapshot into correct environment context
Replay deferred actions or inputs from time of capture
Verify integrity before accepting restore
❌ ANTI-PATTERNS (2)
Restoring into mismatched app version
Replaying actions blindly after long inactivity
πŸ’» CODE HINTS (1)
Use snapshot + action log combo with version pin
πŸ§ͺ VALIDATION
Simulate all snapshot types: periodic, event-based, manual, rollback, delta-chained, and full-restore; confirm timing, fidelity, and contextual integrity.
#118Time-Travel State Matrix6 cells18 rules12 anti6 hints
Define how to traverse, inspect, and manipulate application state across past, present, and possible future timelines.
temporal_navigation_modestate_serializationside_effect_controlui_representationaction_log_structurereentry_and_playback_model
LINEAR_ACTION_LOG_REPLAY
When state evolves through a known sequence of pure actions
βœ… RULES (3)
Log each action with timestamp and metadata
Ensure all mutations are pure and deterministic
Reset to baseline and reapply actions
❌ ANTI-PATTERNS (2)
Letting external state mutate result during replay
Using non-idempotent actions in log
πŸ’» CODE HINTS (1)
Use reducer log + reset + replay loop
SNAPSHOT_WITH_ACTION_DELTA_CHAIN
When replaying all history is too expensive
βœ… RULES (3)
Capture full state snapshot at interval
Store action diffs between snapshots
Rebuild by applying delta chain over snapshot
❌ ANTI-PATTERNS (2)
Relying only on full replays for large timelines
Mixing snapshot versions without diff validation
πŸ’» CODE HINTS (1)
Use checkpointed reducer + diff engine
SIDE_EFFECT_FREE_TRAVEL
When state travel should not affect real system state
βœ… RULES (3)
Avoid triggering network, file IO, or timers during travel
Sandbox state view in isolated context
Lock out mutations to core system state
❌ ANTI-PATTERNS (2)
Emitting metrics, analytics, or logs during rewind
Executing navigation or transitions during rewind
πŸ’» CODE HINTS (1)
Use dry-run reducer, ghost UI context
UI_TIMELINE_CONTROLLER
When user needs direct control over time travel navigation
βœ… RULES (3)
Render timeline slider or discrete stepper
Label actions or snapshots with meaningful names
Disable interactions while paused in past
❌ ANTI-PATTERNS (2)
Using cryptic internal action names
Allowing mutations during paused state
πŸ’» CODE HINTS (1)
Use playback control bar, history scrubber, or jump-to UI
FORKABLE_BRANCHABLE_STATE_HISTORY
When alternate futures or what-if scenarios must be explored
βœ… RULES (3)
Fork state history into new timeline
Track parent snapshot and branch ID
Allow user to label and compare branches
❌ ANTI-PATTERNS (2)
Overwriting original history during branch
Losing linkage between base and fork
πŸ’» CODE HINTS (1)
Use tree of timelines with rollback & merge support
REENTRY_WITH_REDO_AND_COMMIT
When user returns to live state and wants to persist past changes
βœ… RULES (3)
Prompt user to commit or discard rewound actions
Replay forward only valid branch
Track reentry points and resolution paths
❌ ANTI-PATTERNS (2)
Silently merging historic changes into live flow
Losing undo stack after reentry
πŸ’» CODE HINTS (1)
Use checkpoint commit logic and forward replay
πŸ§ͺ VALIDATION
Rewind, branch, and replay user/app state under load and UI controls; validate consistency, immutability during travel, and forked branch behavior.
#119State Debugging Matrix6 cells18 rules12 anti6 hints
Define strategies and tools to inspect, visualize, and trace application state over time for debugging purposes.
debug_data_collectiontemporal_inspection_capabilitystate_visualizationreproducibility_supportside_effect_annotationdeveloper_feedback_channel
LOG_BASED_STATE_WATCH
When state changes must be observed post-execution
βœ… RULES (3)
Log state diffs with timestamp
Include action/event metadata
Persist to searchable store
❌ ANTI-PATTERNS (2)
Logging full state snapshot each time
Mixing logs with unrelated app output
πŸ’» CODE HINTS (1)
Use structured logging with diff serialization
IN_BROWSER_DEVTOOLS_INSPECTION
When frontend developers debug state changes in UI
βœ… RULES (3)
Integrate with browser DevTools or plugin panel
Enable state jump, replay, and diff view
Support filters by component or action
❌ ANTI-PATTERNS (2)
Coupling debug tool to production state directly
Allowing inspection to mutate state
πŸ’» CODE HINTS (1)
Use Redux DevTools, MobX Inspector, or React Debug Hooks
RECORD_REPLAY_AND_TIMELINE_SCRUBBING
When reproducing bug requires observing state over time
βœ… RULES (3)
Record state transitions and UI changes in session
Allow forward/backward stepping and pause
Expose causality links and event source
❌ ANTI-PATTERNS (2)
Capturing UI only without underlying state
Replaying without verification of determinism
πŸ’» CODE HINTS (1)
Use session replay tools or time-travel debugger
STATE_DIFFERENCE_ALERTING
When state divergence or anomaly must trigger feedback
βœ… RULES (3)
Define invariants or constraints over state
Detect and alert on violation
Log snapshot at moment of break
❌ ANTI-PATTERNS (2)
Allowing silent state corruption
Throwing without diagnostic context
πŸ’» CODE HINTS (1)
Use assertion hooks, invariant checks, or diff guards
DEBUGGING_SAFE_SNAPSHOT_EXPORT
When debugging requires external inspection or sharing
βœ… RULES (3)
Redact sensitive data before export
Serialize in stable format (e.g., JSON, binary)
Log export source and context
❌ ANTI-PATTERNS (2)
Leaking private info in bug reports
Capturing environment-specific identifiers
πŸ’» CODE HINTS (1)
Use export debugger action or support dump-to-file
INTEGRATED_FEEDBACK_INTO_DEV_LOOP
When developer workflow should benefit from observed state behavior
βœ… RULES (3)
Feed state anomalies into issue tracker or CI
Allow snapshot promotion into test cases
Visualize frequency of transition paths
❌ ANTI-PATTERNS (2)
Debug info visible only in console or logs
Throwaway state inspection without actionable capture
πŸ’» CODE HINTS (1)
Integrate with CI dashboard, test generator, or telemetry report
πŸ§ͺ VALIDATION
Simulate state mutation, error, and rollback paths under debug tooling; verify visibility, exportability, replay, and signal-to-action pipeline.
#120State Observability Matrix6 cells18 rules12 anti6 hints
Ensure visibility, traceability, and monitoring over runtime state for debugging, analytics, and health.
observation_scopeinstrumentation_strategygranularity_of_visibilityperformance_impacttemporal_correlationconsumer_tooling_integration
LIGHTWEIGHT_STATE_LOGGING
When frequent low-impact observation is needed
βœ… RULES (3)
Log key transitions with timestamps
Avoid verbose full state dumps
Throttle or sample if volume exceeds threshold
❌ ANTI-PATTERNS (2)
Logging entire state on each frame/tick
Allowing log noise to drown signals
πŸ’» CODE HINTS (1)
Use debug hooks with console grouping
METRIC_DERIVATION_FROM_STATE
When business or operational metrics come from runtime state
βœ… RULES (3)
Derive counters, gauges, histograms from state changes
Tag with labels relevant to system context
Aggregate at ingest or collector level
❌ ANTI-PATTERNS (2)
Conflating metric derivation with business logic
Failing to align metrics with observability goals
πŸ’» CODE HINTS (1)
Use Prometheus counters, OpenTelemetry instruments
STATE_SNAPSHOT_EXPORT_AND_TAGGING
When point-in-time state must be captured for audit or debugging
βœ… RULES (3)
Trigger snapshot via user action, event, or rule
Tag with metadata (user, context, action)
Support export to external system
❌ ANTI-PATTERNS (2)
Capturing state without timestamps
Exporting snapshot without context
πŸ’» CODE HINTS (1)
Use dump API, snapshot service, or export-to-cloud hook
STATE_VISUALIZATION_TOOLS
When developers or ops need real-time state view
βœ… RULES (3)
Visualize major state machines, values, and transitions
Support drill-down on transitions
Make read-only to prevent accidental mutation
❌ ANTI-PATTERNS (2)
Hiding internal state behind abstraction layers only
Allowing visualization to mutate runtime state
πŸ’» CODE HINTS (1)
Use inspector panel, dev console overlay, or debug HUD
CORRELATED_TRACE_EMISSION
When state changes must be linked to request or event traces
βœ… RULES (3)
Emit trace spans for key transitions
Link to upstream request or action ID
Export to centralized trace system (e.g. Jaeger, Zipkin)
❌ ANTI-PATTERNS (2)
State changes with no trace or context
Silent transitions invisible to ops
πŸ’» CODE HINTS (1)
Use OpenTelemetry span decorators and trace injection
EXTERNAL_DASHBOARD_INTEGRATION
When state observability must be shared with stakeholders
βœ… RULES (3)
Stream or export state summaries via API
Support dashboard widgets or alert panels
Apply access control for sensitive views
❌ ANTI-PATTERNS (2)
Exposing internal-only observability to public
Assuming ops tooling is only for developers
πŸ’» CODE HINTS (1)
Use Grafana dashboards, external BI tools, or snapshot sharing
πŸ§ͺ VALIDATION
Trigger and monitor state changes under load and event conditions; verify logging, metric export, trace correlation, snapshot correctness, and dashboard visibility.
β–Ό βœ… L5 β€” Validation 30 matrices
#121Input Validation Matrix6 cells12 rules6 anti6 hints
Determines how user and external input is validated β€” where validation occurs, what rules apply, and how violations are reported.
validation_layerrule_typeerror_reportingstrictness
val_001
When validating user input on the client, enforce field-level rules for immediate UX feedback.
βœ… RULES (2)
Use HTML5 attributes or JS listeners
Highlight fields with inline messages
❌ ANTI-PATTERNS (1)
Deferring all validation to server
πŸ’» CODE HINTS (1)
<input required pattern='\d{5}' />
val_002
On backend, validate incoming data against full schema using Zod or Joi before processing.
βœ… RULES (2)
Fail fast on validation errors
Log invalid attempts for audit
❌ ANTI-PATTERNS (1)
Trusting input shape from frontend
πŸ’» CODE HINTS (1)
z.object({ email: z.string().email() })
val_003
Use schema validators to check relationships between fields (e.g. confirmPassword matches password).
βœ… RULES (2)
Define refinement rules in schema
Attach shared error to relevant fields
❌ ANTI-PATTERNS (1)
Validating fields independently only
πŸ’» CODE HINTS (1)
.refine(data => data.password === data.confirm, { message: 'Passwords must match' })
val_004
Format validation errors for i18n compatibility and structured consumption.
βœ… RULES (2)
Use error codes with translatable labels
Expose path, type, and message per error
❌ ANTI-PATTERNS (1)
Hardcoded error strings returned from backend
πŸ’» CODE HINTS (1)
{ path: 'email', code: 'invalid_email', message: t('error.invalid_email') }
val_005
Use schema validation on client (e.g. Zod) for rich field validation before submission.
βœ… RULES (2)
Validate all fields before send
Display list of errors or per-field feedback
❌ ANTI-PATTERNS (1)
Only checking required fields, skipping formats
πŸ’» CODE HINTS (1)
formSchema.safeParse(formData)
val_006
Enforce minimal required field-level checks at server to reject clearly invalid input early.
βœ… RULES (2)
Check for required, min/max/regex
Return 400 with structured error response
❌ ANTI-PATTERNS (1)
Only validating in business logic layer
πŸ’» CODE HINTS (1)
if (!email.match(...)) return res.status(400).json(...);
πŸ§ͺ VALIDATION
Verify: field and schema validation run on both client and server, cross-field rules applied, error messages structured and translatable, input rejected early where needed.
#122Output Validation Matrix6 cells12 rules6 anti7 hints
Determines how system outputs are validated before being sent to consumers β€” ensuring responses match contracts, schemas, and safety constraints.
validation_pointrule_typefailure_actionstrictness
outval_001
Before returning API response, validate output against schema (Zod/Joi) at controller boundary.
βœ… RULES (2)
Define response schema separately from request schema
Fail fast with 500 or structured error on mismatch
❌ ANTI-PATTERNS (1)
Returning unchecked outputs that mismatch expected shape
πŸ’» CODE HINTS (1)
return ResponseSchema.parse(payload)
outval_002
Before serializing response, strip internal-only or sensitive fields to prevent data leaks.
βœ… RULES (2)
Mark internal fields in schema or via annotation
Use serialization whitelist or field-level transformers
❌ ANTI-PATTERNS (1)
Leaking password_hash or internal flags in API response
πŸ’» CODE HINTS (2)
delete user.passwordHash
return pick(user, publicFields)
outval_003
Before sending response, check for null/undefined and handle explicitly.
βœ… RULES (2)
Return 404 for missing resource when null
Guard against undefined values before JSON conversion
❌ ANTI-PATTERNS (1)
Passing undefined to JSON.stringify() β†’ empty body
πŸ’» CODE HINTS (1)
if (!result) return res.status(404).json({ error: 'Not found' })
outval_004
Before releasing to consumers, validate output against OpenAPI/Swagger contract using tests.
βœ… RULES (2)
Generate contract from OpenAPI and test with output samples
Fail CI if output mismatch with spec
❌ ANTI-PATTERNS (1)
Updating implementation without syncing API contract
πŸ’» CODE HINTS (1)
jest + openapi-response-validator
outval_005
Before sending response, validate that size does not exceed safe limit (e.g. 1MB).
βœ… RULES (2)
Set max response size per route or endpoint
Truncate or error if size exceeded
❌ ANTI-PATTERNS (1)
Returning full dataset without pagination
πŸ’» CODE HINTS (1)
if (Buffer.byteLength(JSON.stringify(data)) > MAX_SIZE) return 413
outval_006
After output is built but before send, validate for anomalies and log errors without blocking user flow.
βœ… RULES (2)
Use non-blocking logger to capture unexpected patterns
Route logs to monitoring system
❌ ANTI-PATTERNS (1)
Silently allowing corrupt or unexpected data to pass without trace
πŸ’» CODE HINTS (1)
log.warn('unexpected output format', { output })
πŸ§ͺ VALIDATION
Verify: all outputs are schema-validated, null/undefined values handled, sensitive fields stripped, responses contract-tested, size-checked, and soft anomalies logged.
#123Schema Validation Matrix6 cells12 rules6 anti6 hints
Determines how data schemas are validated at runtime β€” schema definition, validation execution, and mismatch handling for stored data integrity.
schema_sourcevalidation_timingmismatch_actionstrictness
sv_001
When receiving input from client, define Zod schema and validate on arrival before processing.
βœ… RULES (2)
Use z.object to define structure
Apply .parse() or .safeParse() immediately after receiving input
❌ ANTI-PATTERNS (1)
Trusting client input shape before schema validation
πŸ’» CODE HINTS (1)
const result = schema.safeParse(req.body);
sv_002
When validating REST API input, use JSON Schema with tools like AJV to enforce contract compliance.
βœ… RULES (2)
Compile schema once, validate each request against it
Reject requests with 400 on validation failure
❌ ANTI-PATTERNS (1)
Validating JSON shape manually via if/else trees
πŸ’» CODE HINTS (1)
const validate = ajv.compile(schema); if (!validate(data)) return 400;
sv_003
When loading documents from database, apply schema validation at runtime to catch drift or legacy data issues.
βœ… RULES (2)
Parse stored documents against expected schema
Log and quarantine malformed records
❌ ANTI-PATTERNS (1)
Trusting DB shape without schema after migrations
πŸ’» CODE HINTS (1)
z.object({...}).safeParse(dbResult)
sv_004
When a function expects structured input, define schema inline with Zod and validate at entry.
βœ… RULES (2)
Throw on invalid input
Document expected shape via schema type export
❌ ANTI-PATTERNS (1)
Assuming developer passed valid object without validation
πŸ’» CODE HINTS (1)
function save(data) { schema.parse(data); ... }
sv_005
When enforcing strict mode, reject any extra fields not defined in the schema to ensure tight contract.
βœ… RULES (2)
Enable strict() or additionalProperties: false
Log unknown fields for auditing
❌ ANTI-PATTERNS (1)
Allowing extra fields silently
πŸ’» CODE HINTS (1)
z.object({...}).strict()
sv_006
When using lenient mode, allow extra fields but emit warnings or strip unknown keys for resilience.
βœ… RULES (2)
Use strip() or allow unknowns via config
Log discarded fields for visibility
❌ ANTI-PATTERNS (1)
Blocking entire request for harmless extra fields
πŸ’» CODE HINTS (1)
z.object({...}).strip()
πŸ§ͺ VALIDATION
Verify: schemas validated at input and DB read, strict mode rejects unknowns, lenient mode strips safely.
#124Type Validation Matrix6 cells18 rules12 anti6 hints
Define how, where, and when to enforce type validation across runtime, schema, and integration boundaries.
validation_scopevalidation_locationruntime_vs_compiletimestrictness_levelerror_reportingintegration_with_tooling
COMPILE_TIME_STATIC_TYPING
When using statically typed languages or transpilers
βœ… RULES (3)
Define type annotations in source code
Use generics to enforce type contracts
Fail build on type inference conflict
❌ ANTI-PATTERNS (2)
Bypassing types with `any` or loose casting
Ignoring warnings in typed pipeline
πŸ’» CODE HINTS (1)
Use TypeScript, Flow, or statically typed languages like Rust, Kotlin
RUNTIME_TYPE_GUARDS
When inputs come from dynamic or untyped sources
βœ… RULES (3)
Check value type explicitly before usage
Use schema or validation library for structural types
Fail early on invalid type
❌ ANTI-PATTERNS (2)
Trusting dynamic input blindly
Accessing fields before verifying type
πŸ’» CODE HINTS (1)
Use `typeof`, `Array.isArray`, or `zod`, `yup`, `io-ts`
SCHEMA_DRIVEN_VALIDATION
When validating payloads at boundaries (e.g. APIs, DBs)
βœ… RULES (3)
Define JSON schema or interface contracts
Validate input and output against schema
Version schemas for evolution
❌ ANTI-PATTERNS (2)
Allowing untyped JSON to flow between systems
Mixing schema evolution with breaking changes
πŸ’» CODE HINTS (1)
Use OpenAPI, JSON Schema, GraphQL type system, Avro
GRADUAL_TYPING_FOR_MIGRATION
When migrating from dynamic to typed system
βœ… RULES (3)
Wrap dynamic inputs with validators
Refactor modules with highest risk first
Provide fallback for untyped parts
❌ ANTI-PATTERNS (2)
Stopping halfway with partial coverage
Tying new logic to legacy untyped contracts
πŸ’» CODE HINTS (1)
Use `unknown` over `any`, lint for unsafe casts
STRICT_VALIDATION_FOR_CRITICAL_PATHS
When type errors can lead to security, safety, or financial impact
βœ… RULES (3)
Use exhaustive type checking
Forbid implicit coercion
Fail loudly and log on type violation
❌ ANTI-PATTERNS (2)
Swallowing type errors with try/catch
Allowing fallback value injection on type failure
πŸ’» CODE HINTS (1)
Use type-safe switch, literal unions, or disjoint tags
TOOLING_INTEGRATED_TYPE_AWARENESS
When teams need visibility into type flow and safety
βœ… RULES (3)
Integrate linter/typechecker into CI pipeline
Enable type-aware autocomplete in editors
Track type coverage metrics
❌ ANTI-PATTERNS (2)
Manual review of types only during PR
Skipping type check step in fast CI runs
πŸ’» CODE HINTS (1)
Use ESLint, `tsc`, SonarQube, or typecov
πŸ§ͺ VALIDATION
Run type checkers, schema validators, and input fuzzer across trusted and untrusted boundaries; verify correctness, clarity, and failure semantics.
#125Range Validation Matrix6 cells18 rules12 anti6 hints
Define how and when to validate numeric, date, and bounded inputs to ensure safe and meaningful values.
range_typevalidation_locationdynamic_vs_static_boundsfeedback_strategyerror_handling_behaviorlogging_and_monitoring
NUMERIC_BOUND_CHECKING
When values must stay within defined numeric limits
βœ… RULES (3)
Define inclusive or exclusive min/max
Validate on input and before computation
Clamp or reject out-of-bounds values
❌ ANTI-PATTERNS (2)
Assuming integers won’t overflow
Letting float NaN/Infinity propagate
πŸ’» CODE HINTS (1)
Use min/max guards, assertions, or validation libraries
DATE_RANGE_CONSTRAINTS
When user input or system dates must be constrained
βœ… RULES (3)
Restrict to current or future/past ranges as needed
Disallow impossible dates (e.g. leap errors)
Account for timezone and locale variation
❌ ANTI-PATTERNS (2)
Allowing unbounded date input
Ignoring epoch assumptions
πŸ’» CODE HINTS (1)
Use `minDate`, `maxDate`, or temporal DSLs
DYNAMIC_RANGE_VALIDATION
When allowed ranges depend on external conditions
βœ… RULES (3)
Compute bounds from context at runtime
Defer validation until all dependencies resolved
Expose validation errors in context-aware form
❌ ANTI-PATTERNS (2)
Validating statically when constraints are dynamic
Caching bounds without invalidation
πŸ’» CODE HINTS (1)
Use form context evaluators or rule engines
INLINE_UI_VALIDATION_FEEDBACK
When user input must stay within defined ranges
βœ… RULES (3)
Display validation message near input
Use color or icon cues with textual explanation
Prevent submission or progression until valid
❌ ANTI-PATTERNS (2)
Hiding error in console or summary only
Letting invalid range proceed to server
πŸ’» CODE HINTS (1)
Use reactive form validators, `aria-invalid`, live regions
FAIL_FAST_SERVER_SIDE_ENFORCEMENT
When values enter system from API or network
βœ… RULES (3)
Check bounds before storage or mutation
Fail with clear error message and code
Log violation with context
❌ ANTI-PATTERNS (2)
Assuming frontend validated correctly
Logging vague β€˜invalid input’ errors only
πŸ’» CODE HINTS (1)
Use schema validators with bounded ranges
VIOLATION_METRICS_AND_ALERTING
When invalid inputs may indicate abuse, bugs, or misuse
βœ… RULES (3)
Emit metrics on range violations
Tag violations by user, endpoint, or source
Alert on spike or threshold breach
❌ ANTI-PATTERNS (2)
Failing silently on repeated violations
Ignoring metrics from blocked actions
πŸ’» CODE HINTS (1)
Use Prometheus counters, log ingestion, or audit hook
πŸ§ͺ VALIDATION
Fuzz input with in-range and out-of-range values across UI, API, and dynamic context; confirm correct rejection, feedback, logging, and alerting.
#126Format Validation Matrix6 cells18 rules12 anti6 hints
Define how to validate structured formats like emails, URLs, phone numbers, or domain-specific strings to ensure syntactic correctness before usage.
format_typevalidation_locationstrictness_leveluser_feedback_strategyfailure_handling_behaviorlocalization_and_variants
EMAIL_FORMAT_VALIDATION
When collecting email addresses from users or systems
βœ… RULES (3)
Use regex or parser to match RFC-compliant structure
Reject common invalid patterns (e.g., missing domain)
Validate at both client and server
❌ ANTI-PATTERNS (2)
Accepting empty or whitespace-only strings
Using overly strict regex that blocks valid edge cases
πŸ’» CODE HINTS (1)
Use `email-validator`, HTML5 `type=email` input
URL_SYNTAX_ENFORCEMENT
When user or config input is expected to be a valid URL
βœ… RULES (3)
Use URL parser to confirm structure
Check for required protocol prefix (http, https)
Normalize and encode if accepted
❌ ANTI-PATTERNS (2)
Trusting free-form input without protocol check
Embedding unvalidated URLs in href/src attributes
πŸ’» CODE HINTS (1)
Use `URL()` constructor or URI parser libraries
PHONE_NUMBER_STRUCTURE_CHECK
When validating phone input for calls or SMS
βœ… RULES (3)
Parse using international library (e.g. libphonenumber)
Require country code for global formats
Format and validate display vs dial value
❌ ANTI-PATTERNS (2)
Letting unformatted or local-only numbers proceed
Validating using only string length
πŸ’» CODE HINTS (1)
Use `libphonenumber`, `intl-tel-input`
REGEX_BASED_FORMAT_GUARDS
When expecting structured patterns like tax IDs or invoice numbers
βœ… RULES (3)
Define and document format rules
Use regex or grammar pattern
Validate length and required separators
❌ ANTI-PATTERNS (2)
Hardcoding patterns in multiple places
Ignoring format drift in legacy systems
πŸ’» CODE HINTS (1)
Use centralized validator registry
LOCALIZED_FORMAT_VALIDATION
When input varies by user locale (e.g., postal codes, IDs)
βœ… RULES (3)
Detect locale from user profile or input
Apply format rules per region
Store original and normalized form
❌ ANTI-PATTERNS (2)
Using single regex globally
Stripping locale detail during validation
πŸ’» CODE HINTS (1)
Use `i18n-format-rules`, `locale-validator`
FAILURE_LOGGING_AND_ALERTING_ON_FORMAT_ERRORS
When invalid input patterns may indicate abuse or systemic error
βœ… RULES (3)
Log rejected values with input metadata
Track format error rates by field and source
Alert on spikes or attack patterns
❌ ANTI-PATTERNS (2)
Silently discarding malformed inputs
Throwing generic error without context
πŸ’» CODE HINTS (1)
Use structured logs with format type + source tags
πŸ§ͺ VALIDATION
Fuzz each format field with valid and invalid inputs; verify rejection, feedback, error tagging, and regional compliance.
#127Required Fields Matrix6 cells18 rules12 anti6 hints
Define when and how to enforce presence of required fields across forms, APIs, and internal structures to ensure completeness and integrity.
validation_contextfield_criticalitytiming_of_validationdefault_handling_behavioruser_feedback_pathconditional_requirement_logic
FORM_INPUT_REQUIRED_UI_ENFORCEMENT
When user-facing forms must collect mandatory data
βœ… RULES (3)
Mark required fields visually and semantically
Block form submission until all required inputs are filled
Expose validation immediately on blur or submit attempt
❌ ANTI-PATTERNS (2)
Letting user submit form with missing required fields
Showing validation only after backend rejection
πŸ’» CODE HINTS (1)
Use HTML5 `required` attribute or form validation schema
API_REQUEST_REQUIRED_FIELD_VALIDATION
When backend services expect mandatory fields in requests
βœ… RULES (3)
Define required fields in API schema (e.g., OpenAPI spec)
Validate all required fields before processing
Respond with 400 error and missing field list
❌ ANTI-PATTERNS (2)
Allowing null or undefined through without error
Relying on backend logic to infer missing fields
πŸ’» CODE HINTS (1)
Use schema validator like Joi, Zod, or Ajv
CONDITIONAL_FIELD_REQUIREMENTS
When a field becomes required based on value of another field
βœ… RULES (3)
Use conditional validation rules tied to parent field
Update validation state reactively
Test all combinations of controlling values
❌ ANTI-PATTERNS (2)
Treating conditional required fields as optional
Missing logic for when requirement toggles on/off
πŸ’» CODE HINTS (1)
Use conditional schema branches or form logic rules
DEFAULT_REQUIRED_WITH_OVERRIDABLE_VALUES
When fields should default to required unless overridden
βœ… RULES (3)
Declare fields as required by default in schema
Allow override via config flag or per-case switch
Track overrides and reasons for auditability
❌ ANTI-PATTERNS (2)
Letting consumers override required fields silently
Lacking centralized default definition
πŸ’» CODE HINTS (1)
Use default schema template with override map
INTERNAL_STRUCTURE_INVARIANT_ENFORCEMENT
When internal objects must always have certain fields set
βœ… RULES (3)
Assert required keys during object creation or mutation
Fail fast if invariant is violated
Enforce in both runtime and compile-time when possible
❌ ANTI-PATTERNS (2)
Assuming presence based on code path
Catching invariant errors only after crash
πŸ’» CODE HINTS (1)
Use constructor guards or static type constraints
MULTI_LAYER_VALIDATION_ALIGNMENT
When validation occurs at multiple layers (UI, API, DB)
βœ… RULES (3)
Keep required field definitions synchronized across layers
Validate progressively (UI β†’ API β†’ DB)
Test end-to-end flows with intentionally missing fields
❌ ANTI-PATTERNS (2)
Marking field as required in DB but not UI
Expecting downstream layers to fix upstream omissions
πŸ’» CODE HINTS (1)
Use shared schema or contract generation tool
πŸ§ͺ VALIDATION
Test each layer (UI, API, internal) with missing, null, and conditionally required fields; verify rejection, feedback, and consistency across systems.
#128Conditional Validation Matrix6 cells12 rules6 anti6 hints
Determines when validation rules are applied conditionally β€” based on context, user role, feature flags, or data state.
condition_typetriggerrule_scopeoverride_policy
condval_001
When a field is optional, validate it only if present in the payload.
βœ… RULES (2)
Apply format/length checks only if field exists
Skip missing optional fields silently
❌ ANTI-PATTERNS (1)
Throwing error when optional field is absent
πŸ’» CODE HINTS (1)
if ('email' in data) schema.email.parse(data.email)
condval_002
Apply stricter validation for admin users than regular users.
βœ… RULES (2)
Branch validation logic by user.role
Admins must provide additional fields (e.g. audit metadata)
❌ ANTI-PATTERNS (1)
Applying same validation to all roles regardless of access level
πŸ’» CODE HINTS (1)
if (user.role === 'admin') schemaAdmin.parse(input)
condval_003
Enable or disable specific validation rules via feature flags.
βœ… RULES (2)
Wrap new rules in featureFlag check
Log validation toggle state with input context
❌ ANTI-PATTERNS (1)
Hardcoding rule behavior without environment toggle
πŸ’» CODE HINTS (1)
if (flags.validateZip) validateUSZip(zip)
condval_004
Enforce strict validation only when transitioning to 'published' state.
βœ… RULES (2)
Allow partial input when in 'draft'
Block publish if required fields are missing or invalid
❌ ANTI-PATTERNS (1)
Applying publish-time rules during draft save
πŸ’» CODE HINTS (1)
if (state === 'publish') validateFull(payload)
condval_005
Apply stricter validation in production, allow leniency in development.
βœ… RULES (2)
Guard strict validations with ENV check
Fail only in prod if field fails strict rule
❌ ANTI-PATTERNS (1)
Letting loose rules leak into production
πŸ’» CODE HINTS (1)
if (env === 'production') enforceStrict(payload)
condval_006
Make field B required only if field A has a specific value.
βœ… RULES (2)
Use schema refinement to enforce A β†’ B dependency
Describe dependency clearly in docs
❌ ANTI-PATTERNS (1)
Requiring B unconditionally regardless of A
πŸ’» CODE HINTS (1)
refine(obj => !(obj.plan === 'paid') || !!obj.billingInfo)
πŸ§ͺ VALIDATION
Verify: conditional rules apply only when triggered, optional fields skip silently, role and state conditions enforced.
#129Cross-Field Validation Matrix6 cells12 rules6 anti6 hints
Determines how validation rules that span multiple fields are defined, executed, and reported β€” ensuring inter-field consistency.
dependency_typeexecution_ordererror_attributioncomplexity
xfval_001
When confirming a password or email, validate that confirmation field matches source field within same validation step.
βœ… RULES (2)
Compare password and confirmPassword fields synchronously
Attach error to confirmation field
❌ ANTI-PATTERNS (1)
Reporting mismatch on password instead of confirmation field
πŸ’» CODE HINTS (1)
refine(data => data.password === data.confirmPassword)
xfval_002
When validating date ranges, ensure startDate < endDate within the same form step.
βœ… RULES (2)
Both dates must be present before validation
Block submission on invalid range
❌ ANTI-PATTERNS (1)
Allowing endDate earlier than startDate
πŸ’» CODE HINTS (1)
refine(obj => new Date(obj.start) < new Date(obj.end))
xfval_003
If fields A and B are mutually exclusive, ensure only one is filled out at a time.
βœ… RULES (2)
Validate that not both A and B are non-null
Attach error to both if violated
❌ ANTI-PATTERNS (1)
Allowing both fields to be submitted with values
πŸ’» CODE HINTS (1)
refine(obj => !(obj.a && obj.b))
xfval_004
When a certain field value implies a required dependency (e.g. if type=business then taxId required), enforce conditionally.
βœ… RULES (2)
Check parent field before requiring child
Custom error if condition not met
❌ ANTI-PATTERNS (1)
Requiring taxId for all users instead of business only
πŸ’» CODE HINTS (1)
refine(obj => obj.type !== 'business' || !!obj.taxId)
xfval_005
When validating allocations, ensure total sum across fields equals expected value (e.g. 100%).
βœ… RULES (2)
Sum all percent fields before submit
Attach total error on summary or global
❌ ANTI-PATTERNS (1)
Allowing partial or over 100% allocations
πŸ’» CODE HINTS (1)
const total = [a, b, c].reduce((s, v) => s + v, 0); if (total !== 100) error
xfval_006
When validating cross-entity consistency (e.g. order total matches sum of items), perform async check before submit.
βœ… RULES (2)
Fetch line items and compare with order.total
Block or warn on mismatch
❌ ANTI-PATTERNS (1)
Trusting frontend total without server-side verification
πŸ’» CODE HINTS (1)
const total = sum(items.map(i => i.price)); if (total !== order.total) reject
πŸ§ͺ VALIDATION
Verify: all declared dependencies are enforced at the correct step, attribution is shown on correct field, async joins are verified, and conditional/aggregate logic is deterministic.
#130Business Rules Matrix6 cells18 rules12 anti6 hints
Define how to represent, enforce, and evolve domain-specific business logic across services and systems.
rule_origin_sourceenforcement_layermodifiability_and_versioningexecution_timingconflict_resolution_priorityuser_override_capability
CENTRALIZED_RULE_ENGINE_ENFORCEMENT
When business rules are shared across multiple services
βœ… RULES (3)
Define rules in a central engine (e.g., Drools, RuleJS)
Invoke engine from each participating service
Version rules independently from codebase
❌ ANTI-PATTERNS (2)
Duplicating rule logic in each service
Hardcoding rule checks inside business logic
πŸ’» CODE HINTS (1)
Use external rules DSL or declarative engine
INLINE_IMPERATIVE_RULE_VALIDATION
When rule logic is tightly coupled to immediate operation
βœ… RULES (3)
Implement rule as part of domain method
Document business rationale inline with logic
Keep rule updates versioned with code
❌ ANTI-PATTERNS (2)
Scattering same rule in multiple locations
Using unclear magic numbers or flags
πŸ’» CODE HINTS (1)
Use well-named constants and encapsulated domain methods
CONFIG_DRIVEN_RULE_OVERRIDES
When rule parameters may differ across tenants or environments
βœ… RULES (3)
Externalize rule thresholds and toggles to config
Support override hierarchy (global β†’ tenant β†’ user)
Validate config integrity on load
❌ ANTI-PATTERNS (2)
Hardcoding per-tenant rule variants
Allowing config overrides without validation
πŸ’» CODE HINTS (1)
Use dynamic config loader with schema validation
EVENT_DRIVEN_RULE_TRIGGERING
When rules should respond to business events asynchronously
βœ… RULES (3)
Subscribe to domain events via broker
Execute rules in event consumers or workers
Idempotently handle repeated events
❌ ANTI-PATTERNS (2)
Embedding rule checks only in request handlers
Failing on duplicate event delivery
πŸ’» CODE HINTS (1)
Use message queues, Kafka consumers, or webhook processors
RULE_PRIORITY_AND_CONFLICT_RESOLUTION
When multiple rules apply and may contradict
βœ… RULES (3)
Assign explicit priority to each rule
Detect and log conflict scenarios
Apply resolution policy (e.g., highest, first-match)
❌ ANTI-PATTERNS (2)
Assuming rules never conflict
Letting lower-priority rules override silently
πŸ’» CODE HINTS (1)
Use rule engine with priority metadata or policy resolver
USER_VISIBLE_RULE_FEEDBACK
When users must understand why an action is blocked or altered
βœ… RULES (3)
Log rule evaluation results for user actions
Surface human-readable rule explanations in UI
Provide reference to rule ID or doc link
❌ ANTI-PATTERNS (2)
Silently blocking user actions
Exposing cryptic internal rule codes to end-users
πŸ’» CODE HINTS (1)
Use rule evaluation summary + localized UI message
πŸ§ͺ VALIDATION
Simulate business event triggers, conflicting rule paths, and tenant override scenarios; verify correct enforcement, traceability, and explainability.
#131Matrix 131 β€” Rule Ordering Matrix6 cells18 rules18 anti6 hints
Define how to determine and enforce the execution order of validation rules when multiple rules apply to the same input or entity.
ordering_strategydependency_resolutionstage_of_executionconflict_detectiondeterminism_guaranteeoverride_mechanism
SEQUENTIAL_RULE_CHAINING
When rules must be applied in a fixed order regardless of outcome
βœ… RULES (3)
Define rule list statically
Execute one-by-one in order
Continue even after failure unless specified
❌ ANTI-PATTERNS (3)
Dynamic reordering at runtime
Skipping rule execution silently
Combining unrelated rules in same sequence
πŸ’» CODE HINTS (1)
['required', 'minLength', 'pattern']
DEPENDENCY_BASED_ORDERING
When certain rules depend on others’ outcomes
βœ… RULES (3)
Model rules as DAG (no circular refs)
Topologically sort before execution
Fail early on unmet dependencies
❌ ANTI-PATTERNS (3)
Ignoring preconditions
Allowing implicit dependencies
Circular rule graphs
πŸ’» CODE HINTS (1)
buildDependencyGraph(rules).topoSort()
STAGE_SPLIT_EXECUTION
When different validation stages apply pre/post transformation
βœ… RULES (3)
Tag rules with stage metadata
Group by stage (pre, mid, post)
Route data through appropriate pipeline
❌ ANTI-PATTERNS (3)
Applying post-transformation rules on raw input
Omitting stage tagging
Mixing rule concerns across stages
πŸ’» CODE HINTS (1)
if (rule.stage === 'post') applyAfterTransform()
CONFLICT_DETECTION_AND_RESOLUTION
When multiple rules produce contradictory outcomes
βœ… RULES (3)
Detect rule conflicts before runtime
Log and flag for human resolution
Apply resolution policy (precedence, merge)
❌ ANTI-PATTERNS (3)
Letting both rules fail independently
Hiding conflict behind generic error
Assuming silent override
πŸ’» CODE HINTS (1)
resolveConflicts(ruleSet, policy)
DETERMINISTIC_EXECUTION_ASSURANCE
When rules must produce consistent output across runs
βœ… RULES (3)
Sort rule execution consistently
Avoid randomized rule selection
Track rule source/version
❌ ANTI-PATTERNS (3)
Unordered validation maps
Random test order in CI
Mutable rule definitions
πŸ’» CODE HINTS (1)
rules.sort((a, b) => a.name.localeCompare(b.name))
OVERRIDABLE_ORDER_RULESETS
When consumers need to alter validation flow without rewriting all rules
βœ… RULES (3)
Support override map for rule sequence
Preserve dependency and conflict checks
Expose override mechanism via config
❌ ANTI-PATTERNS (3)
Copying full rule tree to reorder
Violating dependency contracts
Hardcoding override logic
πŸ’» CODE HINTS (1)
config.ruleOrderOverrides = ['x', 'y', 'z']
πŸ§ͺ VALIDATION
Run tests with varied input permutations. Confirm rule fire order matches expected order, respects dependencies, and produces stable, traceable outcomes.
#132Matrix 132 β€” Rule Priority Matrix6 cells18 rules18 anti6 hints
Define how to assign, resolve, and enforce priority levels when multiple validation rules conflict or compete for the same decision outcome.
priority_assignment_methodconflict_resolution_modepriority_scopeoverride_authorityescalation_pathaudit_trail
STATIC_PRIORITY_LEVELS
When rules are predefined and ranked manually
βœ… RULES (3)
Assign integer priority to each rule
Lower number = higher priority
Break ties with ordering matrix
❌ ANTI-PATTERNS (3)
No priority metadata in rules
Relying on definition order only
Unclear meaning of levels
πŸ’» CODE HINTS (1)
{ priority: 1 }
DYNAMIC_PRIORITY_CONTEXTUALIZATION
When priority depends on runtime context
βœ… RULES (3)
Compute priority based on input flags
Re-evaluate priorities on data change
Log contextual adjustments
❌ ANTI-PATTERNS (3)
Hardcoding dynamic priority
Ignoring condition branches
Mutating base priority in place
πŸ’» CODE HINTS (1)
if (isUrgent) rule.priority = 1; else rule.priority = 3;
SCOPE_BASED_PRIORITY_SCOPING
When rule priority differs across domains or fields
βœ… RULES (3)
Define scope hierarchy (global > module > field)
Support override at narrower scopes
Merge scope priorities using resolution policy
❌ ANTI-PATTERNS (3)
Using one priority for all use cases
Losing context in nested structures
No scoping metadata in rules
πŸ’» CODE HINTS (1)
{ field: 'email', priority: { global: 2, local: 1 } }
CONFLICT_POLICY_APPLICATION
When multiple rules target the same field with same priority
βœ… RULES (3)
Use policies like 'first-wins', 'last-wins', 'merge'
Log resolution outcome
Allow manual override where needed
❌ ANTI-PATTERNS (3)
Silently applying both rules
No visibility into resolution path
Conflicting error messages
πŸ’» CODE HINTS (1)
resolvePriorityConflict(rules, 'last-wins')
ESCALATION_FOR_CRITICAL_FAILURES
When low-priority rule surfaces critical issue
βœ… RULES (3)
Tag rule with escalation flag
Bypass normal priority resolution
Notify human reviewer if necessary
❌ ANTI-PATTERNS (3)
Suppressing all low-priority rules
Ignoring critical data in favor of hierarchy
Lacking escalation path for exceptions
πŸ’» CODE HINTS (1)
if (rule.escalateOnFailure) notify()
AUDIT_TRAIL_FOR_PRIORITY_DECISIONS
When reviewing why a certain rule won or lost
βœ… RULES (3)
Log priority comparison and resolution
Store evaluation metadata per run
Include in validation reports
❌ ANTI-PATTERNS (3)
Opaque conflict resolution
No trace of override reason
Missing logging for fallback paths
πŸ’» CODE HINTS (1)
logDecision(ruleA, ruleB, result)
πŸ§ͺ VALIDATION
Run overlapping rule sets with conflicting priorities. Inspect which rules win, how escalation is handled, and audit trails are generated.
#133Validation Triggers Matrix6 cells12 rules6 anti6 hints
Determines when validation is triggered in the UI or backend β€” on input, on blur, on submit, periodically, or delayed.
trigger_typevalidation_timingscopeuser_feedback
trigger_001
When a field loses focus, validate only that field to provide targeted feedback.
βœ… RULES (2)
Trigger validation once on blur event
Display inline message under field
❌ ANTI-PATTERNS (1)
Validating full form on blur
πŸ’» CODE HINTS (1)
input.onBlur = () => validate(field)
trigger_002
When user submits form, validate all fields and show summary if errors exist.
βœ… RULES (2)
Validate synchronously or via Promise
Scroll to first error or show summary banner
❌ ANTI-PATTERNS (1)
Allowing submission despite errors
πŸ’» CODE HINTS (1)
form.onSubmit = (e) => { e.preventDefault(); validateAll(); }
trigger_003
When user changes a value, validate as they type with debounced delay.
βœ… RULES (2)
Use debounce (300–500ms) before validating
Avoid flashing errors on every keystroke
❌ ANTI-PATTERNS (1)
Immediate sync validation per char typed
πŸ’» CODE HINTS (1)
input.onChange = debounce(validate, 300)
trigger_004
When input stops for a while (e.g. 2s), validate field to reduce interruptions during typing.
βœ… RULES (2)
Track last input timestamp
Validate if pause exceeds threshold
❌ ANTI-PATTERNS (1)
Aggressive validation on every short pause
πŸ’» CODE HINTS (1)
setTimeout(validateIfIdle, 2000)
trigger_005
When editing complex data, run validation in background every X seconds or autosave checkpoint.
βœ… RULES (2)
Throttle to avoid network spam
Indicate background validation subtly
❌ ANTI-PATTERNS (1)
Triggering server-side validation too often
πŸ’» CODE HINTS (1)
setInterval(() => validateDraft(), 10000)
trigger_006
When server performs async validation (e.g. availability check), trigger post-submit and show as async field message.
βœ… RULES (2)
Display loading spinner while awaiting response
Merge result into local error system
❌ ANTI-PATTERNS (1)
Blocking UI with no feedback
πŸ’» CODE HINTS (1)
validateAsync(field).then(showResult)
πŸ§ͺ VALIDATION
Verify: blur triggers field-level check, submit validates form, change uses debounce, pause-based timing works, periodic validation throttled, async API results handled gracefully.
#134Soft Validation Matrix6 cells18 rules12 anti6 hints
Define when and how to apply validations that warn but do not block user or system actions, enabling flexible guidance without interruption.
validation_trigger_pointuser_visibility_levelblocking_vs_nonblockingpersistence_of_warningsseverity_gradingoverride_capability
ON_SUBMIT_WARNING_WITH_OVERRIDE
When form submit includes questionable but syntactically valid data
βœ… RULES (3)
Run soft validations during final submit phase
Display non-blocking modal or alert
Require user to explicitly confirm override
❌ ANTI-PATTERNS (2)
Blocking action on soft warning
Proceeding without any user notice
πŸ’» CODE HINTS (1)
Use confirm modal or toast with 'Continue Anyway' button
INLINE_WEAK_PATTERN_HINTING
When user input diverges from recommended patterns
βœ… RULES (3)
Render hint near field in real-time
Use soft visuals (gray, info icon)
Allow input to proceed unchanged
❌ ANTI-PATTERNS (2)
Blocking submission due to weak pattern
Using red or error-style for non-critical hints
πŸ’» CODE HINTS (1)
Use info tooltips or ghost labels
BACKGROUND_VALIDATION_WITH LOGGING
When system receives data not following best practices
βœ… RULES (3)
Run async validation on incoming data
Log violations to observability pipeline
Tag source and frequency for later analysis
❌ ANTI-PATTERNS (2)
Rejecting valid-but-unpreferred data
Failing silently with no audit trace
πŸ’» CODE HINTS (1)
Use lint-style validators with metrics output
SOFT_WARNING_ON_API_CONSUMPTION
When API clients send inputs that trigger soft rules
βœ… RULES (3)
Include `warnings` field in API response
Document soft rules in API schema
Track soft warning triggers per client
❌ ANTI-PATTERNS (2)
Returning hard 4xx/5xx status on soft violations
Sending warning in undocumented header
πŸ’» CODE HINTS (1)
Use RFC7807-style `warnings` array
ADMIN_PANEL_VALIDATION_INSIGHTS
When admins need visibility into soft rule violations
βœ… RULES (3)
Visualize common soft violations per entity
Support drill-down to specific violations
Enable export for audits
❌ ANTI-PATTERNS (2)
Burying soft validation info in backend logs only
Lacking cross-entity soft violation analytics
πŸ’» CODE HINTS (1)
Use admin dashboard widget for validation heatmap
USER_PREFERENCE_SOFT_RULE_OPT_OUT
When soft rules may be irrelevant for some user roles
βœ… RULES (3)
Allow user to suppress specific soft rules
Persist suppression in user profile
Fallback to default warning if no opt-out configured
❌ ANTI-PATTERNS (2)
Forcing same soft rule policy on all users
Allowing permanent suppression with no expiry
πŸ’» CODE HINTS (1)
Use rule preference map in user settings
πŸ§ͺ VALIDATION
Test soft rule flow with real user inputs, API calls, and admin insights; confirm override visibility, logging fidelity, and user awareness without blocking.
#135Error Feedback Matrix6 cells12 rules6 anti6 hints
Determines how errors are communicated to users β€” inline messages, tooltips, field highlights, summary banners, and ARIA integration.
error_surfaceuser_locationfield_linkageaccessibility_support
error_001
When a field has a validation error, show short inline text below the field in close proximity.
βœ… RULES (2)
Use concise phrasing
Match field width and spacing
❌ ANTI-PATTERNS (1)
Generic error at top with no field context
πŸ’» CODE HINTS (1)
<Input /> <ErrorText>Email is required</ErrorText>
error_002
When space is limited or dense UI, show error tooltip on hover or focus of the invalid field.
βœ… RULES (2)
Use aria-describedby to bind tooltip to field
Make tooltip dismissible
❌ ANTI-PATTERNS (1)
Tooltip appears only on hover with mouse (not focus)
πŸ’» CODE HINTS (1)
<Input aria-describedby='email-error' /> <Tooltip id='email-error'>Enter a valid email</Tooltip>
error_003
When a field is invalid, highlight its border in a strong error color (e.g. red).
βœ… RULES (2)
Use color token with contrast ratio β‰₯ 4.5:1
Avoid relying on color alone
❌ ANTI-PATTERNS (1)
Red border only, no text or icon
πŸ’» CODE HINTS (1)
<Input error aria-invalid='true' />
error_004
When multiple errors exist, display a summary banner at top listing all issues with links to fields.
βœ… RULES (2)
Use unordered list with anchors to field IDs
Auto-focus banner on submit
❌ ANTI-PATTERNS (1)
Listing errors without navigation
πŸ’» CODE HINTS (1)
<ul><li><a href='#email'>Email is required</a></li></ul>
error_005
When validating forms, show errors on blur and again on submit, to avoid overwhelming users during typing.
βœ… RULES (2)
Validate onBlur for each field
Revalidate all on submit
❌ ANTI-PATTERNS (1)
Validating on every keystroke by default
πŸ’» CODE HINTS (1)
input.onBlur = validateField; form.onSubmit = validateAll
error_006
When an error is shown, bind it to the input field via ARIA for screen reader accessibility.
βœ… RULES (2)
Use aria-describedby to point to error message ID
Set aria-invalid=true on field
❌ ANTI-PATTERNS (1)
Error not announced by screen readers
πŸ’» CODE HINTS (1)
<input aria-invalid='true' aria-describedby='error-id' />
πŸ§ͺ VALIDATION
Verify: inline errors near field, tooltips on focus, border color used with text/icon, summary banner links to fields, blur+submit validation, ARIA bindings in place.
#136Error Message Matrix6 cells12 rules6 anti6 hints
Determines how validation error messages are structured, translated, and presented β€” ensuring clarity for users and machines.
message_formatlocalizationtarget_audienceseverity
errmsg_001
When reporting validation errors, use structured object format with path, code, and message per field.
βœ… RULES (2)
Include 'path', 'code', and 'message' keys
Attach errors to specific field paths
❌ ANTI-PATTERNS (1)
Returning plain strings with no field context
πŸ’» CODE HINTS (1)
{ path: 'user.email', code: 'invalid_email', message: 'Invalid email address' }
errmsg_002
For multilingual support, return error codes that map to translatable i18n keys on the frontend.
βœ… RULES (2)
Use consistent error codes per type
Provide translation key reference
❌ ANTI-PATTERNS (1)
Hardcoded English strings in backend responses
πŸ’» CODE HINTS (1)
{ code: 'required_field', i18n: 'form.error.required' }
errmsg_003
When showing errors to users at the form level, use concise and friendly messages that summarize the issue.
βœ… RULES (2)
Avoid technical jargon
Group multiple errors into a readable list or sentence
❌ ANTI-PATTERNS (1)
Exposing internal validation rule details to end users
πŸ’» CODE HINTS (1)
Please correct the highlighted fields.
errmsg_004
For developer logs or debug tools, include detailed context about the error location and reason.
βœ… RULES (2)
Log full field path, expected vs actual value
Include stack trace if applicable
❌ ANTI-PATTERNS (1)
Masking error location in logs
πŸ’» CODE HINTS (1)
console.error({ path: 'user.age', expected: 'integer > 0', received: 'abc' })
errmsg_005
When input is technically valid but discouraged (e.g. weak password), return as warning, not blocking error.
βœ… RULES (2)
Tag warning severity in message object
Display with different visual indicator
❌ ANTI-PATTERNS (1)
Blocking user flow for non-critical issues
πŸ’» CODE HINTS (1)
{ path: 'password', severity: 'warning', message: 'Password could be stronger' }
errmsg_006
When validation fails on required or critical fields, return blocking error with clear message.
βœ… RULES (2)
Use severity: 'error' or equivalent flag
Explain why blocking and how to fix
❌ ANTI-PATTERNS (1)
Returning warning for missing required field
πŸ’» CODE HINTS (1)
{ path: 'email', severity: 'error', message: 'Email is required' }
πŸ§ͺ VALIDATION
Verify: error messages include structured metadata, are localized when needed, user-facing messages are clear, developer-facing messages are detailed, severity level is set appropriately.
#137Localization of Errors Matrix6 cells12 rules6 anti6 hints
Determines how error messages are localized β€” i18n key mapping, RTL support, pluralization, and dynamic interpolation.
i18n_strategymessage_formatrtl_supportfallback
localization_001
When an error involves a field name, use i18n keys with interpolated values to generate the localized message.
βœ… RULES (2)
Define translation key per error type
Use {field} placeholder and inject localized field name
❌ ANTI-PATTERNS (1)
Concatenating strings in logic code
πŸ’» CODE HINTS (1)
t('error.required', { field: t('field.email') })
localization_002
When rendering messages involving counts (e.g. password length), use ICU message format for plural-sensitive phrasing.
βœ… RULES (2)
Define plural forms in translation files
Use ICU syntax like {count, plural, one {...} other {...}}
❌ ANTI-PATTERNS (1)
Manual if-else on count values
πŸ’» CODE HINTS (1)
t('error.tooShort', { count: 3 })
localization_003
When supporting RTL languages, adjust text direction and punctuation to suit Arabic or Hebrew presentation.
βœ… RULES (2)
Set dir='rtl' on containers
Use mirrored icons and spacing
❌ ANTI-PATTERNS (1)
LTR-only layout with hardcoded spacing
πŸ’» CODE HINTS (1)
<div dir='rtl'>{t('error.required')}</div>
localization_004
When translation for the user's locale is missing, fallback to English as default message language.
βœ… RULES (2)
Log missing key on fallback
Allow locale override for default
❌ ANTI-PATTERNS (1)
Failing silently with blank message
πŸ’» CODE HINTS (1)
t('error.required') || 'This field is required'
localization_005
When returning errors from backend, separate machine-readable code from localized user-facing message.
βœ… RULES (2)
Include 'code' and 'message' fields in response
Allow client to localize message as needed
❌ ANTI-PATTERNS (1)
Embedding English error message only
πŸ’» CODE HINTS (1)
{ code: 'ERR_001', message: t('error.required') }
localization_006
When interpolating values into RTL messages, ensure punctuation and direction remain correct.
βœ… RULES (2)
Use bidi support in formatting lib
Test with numbers and punctuation in RTL
❌ ANTI-PATTERNS (1)
Broken layout due to LTR interpolation in RTL flow
πŸ’» CODE HINTS (1)
t('error.minLength', { count: 3 }) // Ψ±Ψ³Ψ§Ω„Ψ© ΨͺΨ­Ψͺوي ΨΉΩ„Ω‰ Ψ§Ω„Ψ±Ω‚Ω… Ω£
πŸ§ͺ VALIDATION
Verify: i18n keys render localized text with placeholders, ICU plurals work, RTL direction correct, fallback shows English, code/message separated, and RTL interpolation renders properly.
#138Validation Performance Matrix6 cells18 rules12 anti6 hints
Guide how to structure validation logic for optimal runtime performance under different application constraints.
validation_frequencysynchronous_vs_asynchronousscope_of_datacaching_and_memoizationparallelization_supportfeedback_granularity
PER_INPUT_REALTIME_VALIDATION
When user input needs immediate validation on keystroke or change
βœ… RULES (3)
Validate only changed field on each input
Debounce high-frequency triggers
Avoid full-form reevaluation unless required
❌ ANTI-PATTERNS (2)
Re-validating all fields on each keypress
Blocking input thread with heavy sync logic
πŸ’» CODE HINTS (1)
Use `onChange` + debounce + per-field validation function
BATCHED_FORM_SUBMIT_VALIDATION
When full validation is needed only at submission
βœ… RULES (3)
Defer deep validation until submit trigger
Validate entire form state in batch
Provide grouped error summary after batch
❌ ANTI-PATTERNS (2)
Running heavy validation logic on every field blur
Showing partial errors before form complete
πŸ’» CODE HINTS (1)
Use `validateOnSubmit()` method with form schema
SERVER_SIDE_PARALLEL_VALIDATION
When backend must validate large or complex payloads
βœ… RULES (3)
Split validation into independent units
Run validations in parallel threads or workers
Aggregate and merge results with source context
❌ ANTI-PATTERNS (2)
Running all validation in single thread
Returning first error only, delaying rest
πŸ’» CODE HINTS (1)
Use job queue or thread pool with futures/promises
CACHED_SCHEMA_VALIDATION
When validating against large or repeated schemas
βœ… RULES (3)
Precompile and cache schema objects
Re-use compiled validators across requests
Evict rarely used schemas via LRU policy
❌ ANTI-PATTERNS (2)
Re-parsing JSON schema on every request
Failing to free memory for unused schemas
πŸ’» CODE HINTS (1)
Use schema cache with TTL and hit counter
LAZY_ASYNC_EXTERNAL_VALIDATION
When validation requires calling remote service or database
βœ… RULES (3)
Defer remote validation until after local rules pass
Run external calls asynchronously
Show loading indicator and allow retries
❌ ANTI-PATTERNS (2)
Calling external API on every keystroke
Failing form while external check is pending
πŸ’» CODE HINTS (1)
Use `validateAsync()` with fetch + fallback state
PROGRESSIVE_VALIDATION_FEEDBACK
When validation feedback should scale with user interaction
βœ… RULES (3)
Start with fast local checks
Add deeper structural rules after interaction
Delay expensive rules until necessary
❌ ANTI-PATTERNS (2)
Running full validation immediately on load
Showing all possible warnings at once
πŸ’» CODE HINTS (1)
Use staged validation pipeline with feedback levels
πŸ§ͺ VALIDATION
Run synthetic benchmarks on validation flows with increasing data size and frequency; verify latency, throughput, memory reuse, and progressive feedback fidelity.
#139Client vs Server Validation Matrix6 cells18 rules12 anti6 hints
Decide where to enforce validation rules (client-side, server-side, or both) to balance UX responsiveness, security, and consistency.
validation_locationdata_trust_levelinteraction_latencyrule_complexityfeedback_urgencysource_of_truthduplication_tolerance
CLIENT_FAST_FEEDBACK_UI_RULES
When user needs real-time feedback on input formatting
βœ… RULES (3)
Apply simple syntactic validation in browser
Provide inline feedback during input
Block form submission if basic checks fail
❌ ANTI-PATTERNS (2)
Delegating trivial validation to server
Letting user submit with clearly invalid syntax
πŸ’» CODE HINTS (1)
Use HTML5 input constraints or lightweight JS validators
SERVER_TRUSTED_ENFORCEMENT_GATE
When request originates from untrusted client or API
βœ… RULES (3)
Re-validate all critical fields server-side
Block mutation even if client validated
Log source IP and failure cause
❌ ANTI-PATTERNS (2)
Assuming client sanitized data
Allowing write path without validation replay
πŸ’» CODE HINTS (1)
Use schema validator (e.g., Zod, Joi) in backend
DUAL_LAYER_CRITICAL_VALIDATION
When both fast UX and secure backend are essential
βœ… RULES (3)
Validate all user input in UI immediately
Mirror validation logic on backend
Sync validation rules via shared schema when possible
❌ ANTI-PATTERNS (2)
Having mismatched validation logic
Letting server logic drift from frontend schema
πŸ’» CODE HINTS (1)
Use shared validation library or codegen schema
ASYNC_SERVER_VALIDATION_ON_SUBMIT
When validation requires data only available to server
βœ… RULES (3)
Defer heavy checks until submission
Perform lookup-based or relational validation server-side
Show result asynchronously with field-specific message
❌ ANTI-PATTERNS (2)
Blocking typing on server latency
Performing server check on every keystroke
πŸ’» CODE HINTS (1)
Use submit handler with async await + error toast
CLIENT_SIDE_SOFT_WARNINGS
When guidance is needed but not mandatory enforcement
βœ… RULES (3)
Show inline warnings that do not block submission
Tag optional rules with severity level
Let user override with confirmation
❌ ANTI-PATTERNS (2)
Treating soft warnings as hard errors
Letting soft warnings accumulate silently
πŸ’» CODE HINTS (1)
Use warning badges + override checkbox
SERVER_SIDE_AUDIT_VALIDATION
When post-submission analysis ensures policy compliance
βœ… RULES (3)
Run audit pipeline asynchronously after insert
Log violations with rule ID and metadata
Flag entities for review if thresholds breached
❌ ANTI-PATTERNS (2)
Assuming all validation must be pre-submit
Failing to log post-insert violations
πŸ’» CODE HINTS (1)
Use queue-based validation jobs with structured log output
πŸ§ͺ VALIDATION
Test each path (client-only, server-only, dual) with valid and invalid inputs; verify user feedback speed, backend enforcement, and drift between layers.
#140Matrix 140 β€” Trust Boundary Matrix6 cells18 rules18 anti6 hints
Define where trust boundaries exist in the system and how to enforce validation at each crossing point to prevent untrusted data from entering trusted zones.
boundary_locationtrust_level_classificationvalidation_enforcement_pointdata_flow_directioncrossing_frequencythreat_model_alignment
API_GATEWAY_INPUT_VALIDATION
When external clients send requests to your API
βœ… RULES (3)
Validate schema at gateway level
Reject unknown fields or invalid types
Log validation failures for monitoring
❌ ANTI-PATTERNS (3)
Validating only inside downstream services
Allowing unchecked passthrough
No visibility into input validation failures
πŸ’» CODE HINTS (1)
gateway.validate(schema).onFail(logAndReject)
INTER_SERVICE_TRUST_TOKEN_CHECK
When one internal service talks to another
βœ… RULES (3)
Require signed service tokens
Check token freshness and scope
Log rejected tokens with service ID
❌ ANTI-PATTERNS (3)
Relying on internal IPs as trust
Skipping validation for known peers
Accepting expired credentials
πŸ’» CODE HINTS (1)
validateServiceToken(jwt, expectedScope)
DATABASE_QUERY_INPUT_CLEANSE
When constructing database queries from user input
βœ… RULES (3)
Use parameterized queries
Cleanse input before inclusion in dynamic parts
Whitelist known-safe patterns if needed
❌ ANTI-PATTERNS (3)
String concatenation in query strings
Accepting user regex unchecked
Trusting client-side validation only
πŸ’» CODE HINTS (1)
db.query('SELECT * FROM users WHERE id = ?', [userId])
FRONTEND_SANITIZATION_BEFORE_RENDER
When rendering user-generated content in browser
βœ… RULES (3)
Escape HTML entities before rendering
Use DOMPurify or similar library
Avoid using innerHTML directly
❌ ANTI-PATTERNS (3)
Injecting raw user content into DOM
Assuming backend has sanitized everything
Bypassing framework templating systems
πŸ’» CODE HINTS (1)
sanitizeHtml(content) β†’ safeContent
CROSS_BOUNDARY_LOGGING_AND_ALERTING
When untrusted data crosses into sensitive zone
βœ… RULES (3)
Log all boundary validation failures
Trigger alerts on repeated boundary violations
Include source context in logs
❌ ANTI-PATTERNS (3)
Silent rejection of untrusted input
Lack of correlation ID for boundary logs
No alerting on recurring patterns
πŸ’» CODE HINTS (1)
log('boundary_reject', { src, rule, input })
VALIDATION_AT_DEVICE_EDGE
When receiving data from remote or IoT devices
βœ… RULES (3)
Validate sensor readings against known ranges
Check digital signature or auth token
Throttle or block misbehaving senders
❌ ANTI-PATTERNS (3)
Trusting edge devices blindly
Skipping validation due to scale
Failing open on parse errors
πŸ’» CODE HINTS (1)
if (!validReading(data) || !auth(deviceToken)) reject()
πŸ§ͺ VALIDATION
Run boundary-fuzz tests. Inject malformed data at every entry point. Confirm enforcement, logging, and rejection occur per matrix definition.
#141Sanitization Matrix6 cells12 rules7 anti6 hints
Determines how external input is sanitized before storage or display β€” stripping dangerous content, encoding output, and preventing injection attacks.
sanitization_typeinjection_vectorencoding_strategycontext
san_001
When displaying user-generated HTML, strip dangerous elements like <script> tags to prevent XSS.
βœ… RULES (2)
Use a whitelist-based sanitizer like DOMPurify
Remove all <script>, <iframe>, <object>, and event attributes
❌ ANTI-PATTERNS (2)
Using regex to remove tags
Allowing raw innerHTML insertion
πŸ’» CODE HINTS (1)
DOMPurify.sanitize(userHtml)
san_002
When inserting input into SQL queries, use parameterized queries to prevent SQL injection.
βœ… RULES (2)
Never concatenate user input directly into SQL strings
Use ? or $1 placeholders with parameter binding
❌ ANTI-PATTERNS (1)
'SELECT * FROM users WHERE name = ' + input
πŸ’» CODE HINTS (1)
db.query('SELECT * FROM users WHERE name = ?', [input])
san_003
When constructing URLs from input, encode path segments to prevent path traversal or breaking structure.
βœ… RULES (2)
Use encodeURIComponent on each path segment
Validate segments do not contain ../
❌ ANTI-PATTERNS (1)
Concatenating raw input into URL path
πŸ’» CODE HINTS (1)
const url = '/files/' + encodeURIComponent(filename);
san_004
When accepting JSON input, strip __proto__ and constructor fields to prevent prototype pollution.
βœ… RULES (2)
Recursively remove keys named '__proto__', 'constructor', or 'prototype'
Disallow Object.assign with untrusted data
❌ ANTI-PATTERNS (1)
Blindly merging input into existing objects
πŸ’» CODE HINTS (1)
if (key === '__proto__') delete obj[key];
san_005
When outputting dynamic text into HTML, encode special characters to entities to prevent HTML injection.
βœ… RULES (2)
Convert &, <, >, " to &amp;, &lt;, &gt;, &quot;
Use encoder libraries or built-in functions
❌ ANTI-PATTERNS (1)
Injecting dynamic text via innerHTML without encoding
πŸ’» CODE HINTS (1)
element.textContent = userInput
san_006
When accepting text input, normalize and trim whitespace and Unicode variants to ensure consistent validation and storage.
βœ… RULES (2)
Trim leading/trailing whitespace
Apply Unicode NFC normalization if needed
❌ ANTI-PATTERNS (1)
Comparing raw user input with system strings without normalization
πŸ’» CODE HINTS (1)
const clean = input.trim().normalize('NFC');
πŸ§ͺ VALIDATION
Verify: HTML/script elements removed, SQL queries use placeholders, URLs encoded safely, JSON stripped of polluting keys, dynamic output encoded for HTML, and inputs normalized before comparison or storage.
#142Escaping Matrix6 cells18 rules12 anti6 hints
Decide how and where to apply escaping rules to prevent injection attacks across different content contexts.
content_contextescape_strategyescape_locationinput_trust_levelencoder_library_usedfailure_behavior
HTML_ATTRIBUTE_ESCAPING
When dynamic input is inserted into HTML attributes
βœ… RULES (3)
Escape quotes, angle brackets, and ampersands
Use attribute-specific escape routines
Apply escaping before HTML render phase
❌ ANTI-PATTERNS (2)
Injecting raw input into `href`, `src`, or `on*` attributes
Escaping only after DOM insertion
πŸ’» CODE HINTS (1)
Use `escapeHtmlAttr()` before assigning to attribute nodes
JS_STRING_ESCAPING_IN_TEMPLATES
When user input is injected into JavaScript string literals
βœ… RULES (3)
Escape quotes, backslashes, newlines
Use JS-safe string encoder
Avoid inline script tag concatenation
❌ ANTI-PATTERNS (2)
Embedding unescaped input into `<script>`
Using JSON.stringify but reinterpreting manually
πŸ’» CODE HINTS (1)
Use `JSON.stringify(userInput)` for JS-safe embedding
SQL_IDENTIFIER_ESCAPING
When dynamic identifiers (not values) are used in SQL queries
βœ… RULES (3)
Reject unknown identifier names
Wrap identifiers using dialect-specific quotes
Whitelist allowed column/table names only
❌ ANTI-PATTERNS (2)
Interpolating user input directly into SQL identifiers
Using same escaping for values and identifiers
πŸ’» CODE HINTS (1)
Use query builder libraries like Knex or ORM abstraction
SHELL_COMMAND_ESCAPING
When input is passed to shell commands or scripts
βœ… RULES (3)
Escape or quote each shell argument individually
Avoid shell concatenation when possible
Use subprocess APIs that avoid shell
❌ ANTI-PATTERNS (2)
Using `exec()` with interpolated strings
Failing to escape spaces or semicolons
πŸ’» CODE HINTS (1)
Use `spawn(command, [args])` instead of `exec()` in Node.js
URL_QUERY_COMPONENT_ENCODING
When building URLs with user-controlled parameters
βœ… RULES (3)
Encode each parameter value using URI component encoding
Avoid full-URL concatenation
Apply encoding before interpolation
❌ ANTI-PATTERNS (2)
Concatenating raw user input into URLs
Encoding entire URL after interpolation
πŸ’» CODE HINTS (1)
Use `encodeURIComponent()` for each parameter
LOG_OUTPUT_ESCAPE_SANITIZATION
When user data is written to logs
βœ… RULES (3)
Sanitize line breaks and control characters
Tag untrusted log fields
Avoid direct piping of input into logs
❌ ANTI-PATTERNS (2)
Logging raw headers or inputs
Letting terminal escape sequences through
πŸ’» CODE HINTS (1)
Use logging library that strips ANSI/control chars
πŸ§ͺ VALIDATION
Inject crafted payloads into each target context; verify correct escaping prevents behavior deviation or execution side effects.
#143Constraint Enforcement Matrix6 cells18 rules12 anti6 hints
Define how and where to enforce hard constraints on data to maintain structural, logical, and referential integrity.
constraint_typeenforcement_locationenforcement_timingviolation_behaviorvisibility_and_feedbackconstraint_scope
DATABASE_UNIQUE_KEY_ENFORCEMENT
When enforcing uniqueness of records (e.g., usernames, emails)
βœ… RULES (3)
Define unique constraints at DB schema level
Validate in application before insert to preempt collisions
Handle constraint violation with friendly error
❌ ANTI-PATTERNS (2)
Relying only on application-level uniqueness checks
Swallowing DB errors without explanation
πŸ’» CODE HINTS (1)
Use SQL UNIQUE INDEX + ORM-level pre-checks
APPLICATION_LEVEL_INVARIANT_ASSERTION
When complex constraints can’t be expressed in schema
βœ… RULES (3)
Assert invariants at domain service boundaries
Fail fast with descriptive error
Unit test invariants independently of transport
❌ ANTI-PATTERNS (2)
Allowing invalid object state to propagate
Testing invariants only via end-to-end flows
πŸ’» CODE HINTS (1)
Use `assert(condition, message)` or domain guard classes
FRONTEND_FORM_FIELD_INTERDEPENDENCY
When field validity depends on other fields’ values
βœ… RULES (3)
Observe related fields reactively
Disable or adjust dependent inputs dynamically
Validate group-level logic before submission
❌ ANTI-PATTERNS (2)
Treating interdependent fields as standalone
Submitting with partial logical group completion
πŸ’» CODE HINTS (1)
Use form state observer hooks or reactive schema logic
REFERENTIAL_INTEGRITY_CHECKS
When one entity depends on another’s existence
βœ… RULES (3)
Define foreign key constraints in database
Validate references before mutation or delete
Provide cascading behavior or explicit denial
❌ ANTI-PATTERNS (2)
Deleting referenced entities without check
Assuming reference target exists without lookup
πŸ’» CODE HINTS (1)
Use SQL FOREIGN KEY or ORM-level relation guards
CONSTRAINT_VIOLATION_LOGGING_AND_ALERTING
When constraints are violated despite validation attempts
βœ… RULES (3)
Log violation with entity ID and context
Alert on repeated or critical constraint failures
Store violation metrics for analysis
❌ ANTI-PATTERNS (2)
Failing silently on constraint breach
Logging only technical stack traces without context
πŸ’» CODE HINTS (1)
Use structured logging + alerting thresholds (e.g., Sentry, Datadog)
MIGRATION_SAFE_CONSTRAINT_DEPLOYMENT
When deploying new constraints to existing datasets
βœ… RULES (3)
Backfill and clean data before adding constraint
Deploy constraint in dry-run or warning mode first
Monitor impact before enforcing strictly
❌ ANTI-PATTERNS (2)
Adding hard constraints without data prep
Enforcing without rollout observability
πŸ’» CODE HINTS (1)
Use feature flags or migration frameworks with staged enforcement
πŸ§ͺ VALIDATION
Simulate constraint violations across frontend, backend, and DB layers; test error visibility, rollback behavior, and enforcement under migration.
#144Rule Versioning Matrix6 cells12 rules6 anti6 hints
Determines how validation rules are versioned β€” rule sets per API version, gradual rollout, and backward-compatible rule changes.
versioning_methodrollout_strategybackward_compatibilityaudit
versioning_001
When supporting multiple API versions, attach specific rule sets to each version and resolve them at runtime.
βœ… RULES (2)
Store rule sets per version tag (e.g., v1, v2)
Resolve rule set based on request.version
❌ ANTI-PATTERNS (1)
Mixing v1 and v2 rules in same request context
πŸ’» CODE HINTS (1)
const rules = rulesByVersion[req.version]
versioning_002
When deploying new rules, gradually roll them out by activating on a percentage of incoming requests.
βœ… RULES (2)
Assign rollout cohort by consistent hash of user/request ID
Ramp up traffic in controlled % tiers (e.g., 5%, 20%, 50%)
❌ ANTI-PATTERNS (1)
Enabling new rules for all users at once
πŸ’» CODE HINTS (1)
if (hash(user.id) % 100 < rolloutPercent) applyNewRules()
versioning_003
When introducing new validation logic, log warnings first before hard enforcement to prevent regressions.
βœ… RULES (2)
Emit warning logs if new rule fails
Switch to enforcement mode after observation window
❌ ANTI-PATTERNS (1)
Immediate breakage on newly deployed rule
πŸ’» CODE HINTS (1)
if (!newRulePass) logWarn('v2 rule failed')
versioning_004
When removing an old validation rule, warn on violations for a period before deleting the rule entirely.
βœ… RULES (2)
Track deprecated rule hits via logs
Notify developers or clients before final removal
❌ ANTI-PATTERNS (1)
Silent removal of rules that users depend on
πŸ’» CODE HINTS (1)
logDeprecated('rule X will be removed in 30d')
versioning_005
When running validations, log the rule version used per request for audit and debugging purposes.
βœ… RULES (2)
Tag logs with rule version identifier
Include rule version in error payload optionally
❌ ANTI-PATTERNS (1)
Logs that cannot explain what version applied
πŸ’» CODE HINTS (1)
logger.info('validate', { ruleVersion: v })
versioning_006
When validating new logic, A/B test rule sets against control and treatment groups to measure impact.
βœ… RULES (2)
Split traffic randomly into A/B cohorts
Compare error rates, conversions or complaints
❌ ANTI-PATTERNS (1)
Deploying experimental logic without control baseline
πŸ’» CODE HINTS (1)
if (group === 'B') useNewRule() else useOldRule()
πŸ§ͺ VALIDATION
Verify: rule version attached per API version, gradual rollout follows % ramp-up, backward rules warn before enforce, deprecation alerts logged, version per request logged, A/B groups compared.
#145Validation Extensibility Matrix6 cells18 rules12 anti6 hints
Define how to structure validation frameworks and rule engines for long-term extensibility across modules and domains.
rule_registration_modelruntime_extensibility_supportschema_vs_code_injectionplugin_support_levelversioning_and_compatibilityownership_and_discovery
PLUGGABLE_RULE_REGISTRY
When multiple teams or modules must contribute custom validation rules
βœ… RULES (3)
Provide global rule registry or container
Allow modules to register rules at init or runtime
Support unique rule IDs to avoid collision
❌ ANTI-PATTERNS (2)
Hardcoding rules into central switch blocks
Duplicate logic due to missing registration hook
πŸ’» CODE HINTS (1)
Use DI containers or plugin mounts with lifecycle hooks
RULE_METADATA_DECORATORS
When rules need introspection or UI binding
βœ… RULES (3)
Tag rules with domain, scope, severity, version
Use decorators or annotations for discovery
Expose rule metadata for dashboards or docs
❌ ANTI-PATTERNS (2)
Lacking metadata registry
Requiring manual lookup to understand rule context
πŸ’» CODE HINTS (1)
Use annotation processors or reflection utilities
RUNTIME_RULE_LOADING
When rules must be updated without redeploying core system
βœ… RULES (3)
Load rule definitions from external source (DB, file, config service)
Validate structure and signature before activation
Track rule version and last update timestamp
❌ ANTI-PATTERNS (2)
Embedding all rules at compile-time only
Letting unvalidated external rules corrupt engine
πŸ’» CODE HINTS (1)
Use hot-reloadable config parser or eval-safe DSL
MIXED_SCHEMA_AND_CODE_RULE_INJECTION
When both declarative and imperative rules are needed
βœ… RULES (3)
Support schema-defined constraints and code-defined logic
Use adapters to unify rule evaluation interface
Document precedence when both apply
❌ ANTI-PATTERNS (2)
Choosing one format and banning the other
Evaluating schema and code rules in isolation only
πŸ’» CODE HINTS (1)
Use hybrid rule engine with visitor + parser pattern
RULE_VERSIONING_AND_DEPRECATION
When rules evolve over time and clients depend on specific versions
βœ… RULES (3)
Tag rules with semantic versions
Allow multiple versions to coexist during migration
Deprecate with warning and expiry policy
❌ ANTI-PATTERNS (2)
Overwriting rule logic silently
Removing rules without notice to consumers
πŸ’» CODE HINTS (1)
Use rule.version field and status metadata
RULE_DISCOVERY_AND_INTROSPECTION_TOOLS
When developers or operators need to browse or inspect rules dynamically
βœ… RULES (3)
Expose API or CLI for rule listing
Include rule metadata in discovery output
Support filtering by domain, status, owner
❌ ANTI-PATTERNS (2)
Relying on codebase grep to discover rules
Bundling undocumented rules in deploys
πŸ’» CODE HINTS (1)
Use searchable registry + schema docs + debug UI
πŸ§ͺ VALIDATION
Install new rules at runtime, inspect via UI or CLI, verify registration, metadata tagging, and proper hybrid execution of schema/code paths.
#146Validation Testing Matrix6 cells18 rules12 anti6 hints
Define strategies to test validation logic for correctness, completeness, and resilience across layers.
validation_typetest_trigger_methoddata_sourcefailure_mode_coveragelayer_of_executiontest_feedback_channel
UNIT_TEST_RULE_AT_SOURCE
When validating custom logic implemented in code
βœ… RULES (3)
Write unit tests per rule function/module
Cover both valid and invalid inputs
Isolate from surrounding business logic
❌ ANTI-PATTERNS (2)
Skipping unit tests for simple validators
Combining multiple rule tests into one case
πŸ’» CODE HINTS (1)
Use rule function exports + test stubs
SCHEMA_VALIDATION_TEST_CASES
When schemas are defined in declarative formats (e.g. JSON Schema, Zod)
βœ… RULES (3)
Write sample payloads per constraint edge
Test required, type, format, and enum violations
Assert full error path and messages
❌ ANTI-PATTERNS (2)
Assuming schema works because it compiles
Relying only on positive case coverage
πŸ’» CODE HINTS (1)
Use schema.validate() with fixture sets
END_TO_END_VALIDATION_SCENARIOS
When validations span UI, API, and backend
βœ… RULES (3)
Create flows with valid and invalid inputs
Check inline error display and backend enforcement
Simulate common user mistakes
❌ ANTI-PATTERNS (2)
Testing only happy path
Validating UI but not backend response
πŸ’» CODE HINTS (1)
Use Cypress or Playwright for UI + API testing
FUZZ_TESTING_ON_VALIDATION_LAYER
When robustness of input validation is critical
βœ… RULES (3)
Run random or mutation-based input generators
Track validation rejections and crashes
Log unexpected acceptance of invalid payloads
❌ ANTI-PATTERNS (2)
Assuming inputs will always follow UI pattern
Not capturing logs of failed cases
πŸ’» CODE HINTS (1)
Use fast-check, Fuzzinator, or in-house input mutator
NEGATIVE_TEST_CASE_AUDITING
When validating the presence and correctness of rejection paths
βœ… RULES (3)
List known failure scenarios per rule
Test explicit rejection and feedback
Document which rules have no negative tests
❌ ANTI-PATTERNS (2)
Relying on accidental failures for negative coverage
Missing logs for failed assertions
πŸ’» CODE HINTS (1)
Use test coverage tools + rejection feedback validators
MULTI_LAYER_CONSISTENCY_CHECKS
When rules are implemented across multiple layers (UI, API, DB)
βœ… RULES (3)
Test same input across all layers
Compare rejection reasons and formats
Log drift between frontend and backend checks
❌ ANTI-PATTERNS (2)
Assuming same logic exists everywhere
Allowing schema mismatches to persist silently
πŸ’» CODE HINTS (1)
Use shared test fixtures across client/server
πŸ§ͺ VALIDATION
Run each strategy with known-valid and known-invalid inputs; confirm detection, rejection, feedback quality, and cross-layer consistency.
#147Matrix 147 β€” Validation Logging Matrix6 cells18 rules18 anti6 hints
Define how to log validation events (passes, failures, overrides) for auditability, debugging, and compliance without exposing sensitive data.
log_event_typelog_detail_levelpii_handlinglog_destinationretention_policycorrelation_strategy
FAILURE_LOGGING_WITH_CONTEXT
When a validation check fails during input processing
βœ… RULES (3)
Log field name and error type
Mask or omit PII
Include correlation ID
❌ ANTI-PATTERNS (3)
Logging full input values
Using generic error logs without detail
Lack of trace ID linkage
πŸ’» CODE HINTS (1)
logger.warn('ValidationError', { field, error, traceId })
VALIDATION_SUCCESS_METRICS_LOGGING
When validation passes and metrics are needed for audit
βœ… RULES (3)
Log rule name and outcome
Avoid logging input content
Increment success counters per rule
❌ ANTI-PATTERNS (3)
Omitting logs on pass
Logging entire data set redundantly
Confusing success with skip
πŸ’» CODE HINTS (1)
metrics.log('validation.pass', { rule: 'emailFormat' })
OVERRIDE_ACTION_AUDIT_LOG
When a validation rule is bypassed by an authorized user
βœ… RULES (3)
Log user ID, rule ID, and reason
Timestamp override decision
Route to secure audit log channel
❌ ANTI-PATTERNS (3)
Allowing silent override
No justification recorded
Logging overrides in same channel as errors
πŸ’» CODE HINTS (1)
audit.log('override', { userId, ruleId, reason, time })
PII_REDACTION_POLICY_ENFORCEMENT
When logging includes user-submitted data
βœ… RULES (3)
Apply redaction middleware to all logs
Classify fields by sensitivity
Verify logs with synthetic test data
❌ ANTI-PATTERNS (3)
Logging raw email or ID numbers
Skipping redaction under load
Disabling redaction for debugging
πŸ’» CODE HINTS (1)
logger.use(redactPII({ fields: ['email', 'ssn'] }))
VALIDATION_LOG_RETENTION_AND_ROTATION
When storing logs in regulated environments
βœ… RULES (3)
Set retention per log type (error vs audit)
Encrypt logs at rest
Purge logs after retention window
❌ ANTI-PATTERNS (3)
Keeping logs indefinitely
Storing logs unencrypted
No rotation or archive policy
πŸ’» CODE HINTS (1)
logStore.configure({ ttl: '90d', encrypt: true })
CROSS_REQUEST_CORRELATION_SUPPORT
When validating data across async microservices
βœ… RULES (3)
Pass traceId between services
Include traceId in all validation logs
Aggregate correlated logs for debugging
❌ ANTI-PATTERNS (3)
Dropping context between hops
Using ad-hoc correlation IDs
Logging without linking back to original request
πŸ’» CODE HINTS (1)
logger.info({ ...logData, traceId })
πŸ§ͺ VALIDATION
Run validation scenarios across success, fail, and override. Inspect logs for PII safety, correlation presence, and compliance with retention policy.
#148Validation Metrics Matrix6 cells18 rules12 anti6 hints
Define how to capture, categorize, and act upon validation-related metrics to improve coverage, performance, and accuracy.
metric_typecollection_pointgranularityviolation_severityconsumer_targetretention_policy
VALIDATION_PASS_RATE_TRACKING
When you want to monitor how often inputs pass vs fail validation
βœ… RULES (3)
Log pass/fail result per validation rule
Tag metrics by rule ID and input type
Export summary to dashboard
❌ ANTI-PATTERNS (2)
Only logging failures
Lacking breakdown by rule
πŸ’» CODE HINTS (1)
Use Prometheus counters or event tags with rule_id label
VIOLATION_FREQUENCY_ALERTING
When certain rules are frequently violated
βœ… RULES (3)
Track per-rule violation frequency over time
Set threshold for alert generation
Group violations by source (user, API, system)
❌ ANTI-PATTERNS (2)
Alerting only on total errors
Ignoring high-volume soft failures
πŸ’» CODE HINTS (1)
Use alertmanager thresholds + rule origin tag
LAYERED_METRICS_BREAKDOWN
When validation occurs at multiple layers (UI, API, DB)
βœ… RULES (3)
Capture validation metrics per layer
Log which layer rejected or passed input
Expose cross-layer heatmap
❌ ANTI-PATTERNS (2)
Aggregating all metrics into one
Losing origin of failure in metrics stream
πŸ’» CODE HINTS (1)
Use `validation_layer` label in logging system
VALIDATION_LATENCY_HISTOGRAMS
When validation logic may impact perceived performance
βœ… RULES (3)
Measure per-rule execution time
Bucket timings into histograms
Monitor 95th percentile and spikes
❌ ANTI-PATTERNS (2)
Measuring only total form latency
Ignoring expensive async checks
πŸ’» CODE HINTS (1)
Use `Histogram` metrics in OpenTelemetry or Prometheus
INTEGRITY_RULE_COVERAGE_ANALYSIS
When some validations are never triggered
βœ… RULES (3)
Track invocation count per rule ID
Flag rules never hit in production
Correlate with code coverage tools
❌ ANTI-PATTERNS (2)
Assuming unused rules are harmless
Not correlating with actual data profile
πŸ’» CODE HINTS (1)
Use rule registry with hit counters and test sync
CONSUMER_LEVEL_METRIC_STREAMS
When external teams need insight into validation outcomes
βœ… RULES (3)
Stream per-client validation summary
Tag by consumer, tenant, or feature
Respect privacy and metric filtering
❌ ANTI-PATTERNS (2)
Exposing raw PII in metrics
Failing to partition metrics by client
πŸ’» CODE HINTS (1)
Use sanitized stream or tenant-aware metric emitter
πŸ§ͺ VALIDATION
Inject synthetic validation traffic across all layers; verify metrics emitted per rule, layer, latency bucket, and consumer scope.
#149Validation Recovery Matrix6 cells12 rules6 anti6 hints
Determines how the system recovers from validation failures β€” auto-correction, user guidance, fallback values, and retry flows.
recovery_methodauto_correctionuser_guidancefallback
validation_001
When user inputs leading/trailing whitespace in fields (e.g. email), trim automatically without surfacing error.
βœ… RULES (2)
Trim all text inputs before validation
Log correction silently for audit
❌ ANTI-PATTERNS (1)
Rejecting field due to whitespace
πŸ’» CODE HINTS (1)
const trimmed = input.trim(); validate(trimmed);
validation_002
When user input is structurally close to a valid format (e.g. gmaul.com instead of gmail.com), offer suggestion visibly.
βœ… RULES (2)
Use string similarity or typo DB
Highlight suggestion and allow one-click correction
❌ ANTI-PATTERNS (1)
Autocorrecting without confirmation
πŸ’» CODE HINTS (1)
if (similar(email, knownDomains)) showSuggestion('Did you mean gmail.com?')
validation_003
When field is invalid or missing and non-critical, apply default fallback value to proceed safely.
βœ… RULES (2)
Only apply fallback when value is optional
Expose fallback in confirmation screen
❌ ANTI-PATTERNS (1)
Overwriting user input without notice
πŸ’» CODE HINTS (1)
const locale = input.locale || 'en-US'
validation_004
When validation fails, allow retry with error message that explains what was wrong and how to fix it.
βœ… RULES (2)
Error message should name the exact issue
Highlight erroneous field(s) visually
❌ ANTI-PATTERNS (1)
Generic 'Invalid input' message
πŸ’» CODE HINTS (1)
showError('Phone number must be 10 digits')
validation_005
When form has multiple fields and some are valid, accept valid ones and surface issues only for invalid fields.
βœ… RULES (2)
Store partial data as draft
Mark valid fields with green and invalid with red
❌ ANTI-PATTERNS (1)
Blocking entire form due to one field
πŸ’» CODE HINTS (1)
updateDraft({ ...validFields }); showErrors(invalidFields)
validation_006
When automated validation cannot determine result (e.g. suspicious name), escalate to manual review queue.
βœ… RULES (2)
Flag ambiguous entries with confidence score
Push to human review with metadata
❌ ANTI-PATTERNS (1)
Rejecting uncertain input outright
πŸ’» CODE HINTS (1)
if (score < 0.6) queueForReview(entry)
πŸ§ͺ VALIDATION
Verify: whitespace trimmed silently, suggestions offered with confirmation, fallbacks documented, retries explain cause, partial save supported, and uncertain inputs flagged for human check.
#150Validation Recovery Matrix6 cells18 rules12 anti6 hints
Define how systems should gracefully handle validation failures to maintain usability, consistency, and resilience.
failure_contextuser_interaction_moderecovery_path_typedata_persistence_strategyfeedback_channelautomated_vs_manual_resolution
SOFT_FAILURE_INLINE_RETRY
When user input fails client-side validation during form filling
βœ… RULES (3)
Preserve user-entered data in form fields
Focus first invalid field after submit attempt
Display contextual inline error with guidance
❌ ANTI-PATTERNS (2)
Clearing entire form on validation error
Showing all errors as toast messages only
πŸ’» CODE HINTS (1)
Use form state preservation and field-level validation indicators
SERVER_SIDE_FAILURE_RETRY_PROMPT
When backend validation fails on submit despite frontend checks
βœ… RULES (3)
Return structured error message with field hints
Repopulate form with previous values on failure
Offer 'Retry with changes' or 'Discard' options
❌ ANTI-PATTERNS (2)
Responding with generic 400 error
Dropping submitted payload after failure
πŸ’» CODE HINTS (1)
Use error payload replay into form state with diff highlighting
AUTO_CORRECTION_ON_PATTERN_MISMATCH
When input fails due to predictable but fixable format issue
βœ… RULES (3)
Detect common typos or missing elements (e.g. domain in email)
Propose correction with option to apply
Log auto-corrected attempts for analytics
❌ ANTI-PATTERNS (2)
Silently mutating input without user consent
Over-aggressive correction that breaks valid input
πŸ’» CODE HINTS (1)
Use validator with autocorrect hooks or pattern matchers
PARTIAL_SAVE_ON_VALIDATION_FAILURE
When long forms or batch operations contain mixed valid/invalid entries
βœ… RULES (3)
Allow saving of valid entries while flagging invalid ones
Track which fields or records failed
Provide resume/edit option post-validation
❌ ANTI-PATTERNS (2)
Blocking save due to one error in entire batch
Saving incomplete state without error trace
πŸ’» CODE HINTS (1)
Use split-payload handling with error map return
QUEUED_RETRY_AFTER_VALIDATION_FIX
When system input is retried after external or async fix
βœ… RULES (3)
Place failed input in retry queue with reason
Detect resolution (e.g. reference exists now)
Re-evaluate input and log retry outcome
❌ ANTI-PATTERNS (2)
Dropping invalid input without tracking
Retrying blindly without confirming fix
πŸ’» CODE HINTS (1)
Use DLQ + background validator reprocessor
ADMIN_ASSISTED_VALIDATION_OVERRIDE
When exceptional cases justify bypassing standard validation
βœ… RULES (3)
Provide UI for admin to override specific validations
Require reason + confirmation before proceeding
Audit all override actions with user and timestamp
❌ ANTI-PATTERNS (2)
Hardcoding bypass logic in application path
Allowing override without audit trail
πŸ’» CODE HINTS (1)
Use override modal + log structured override event
πŸ§ͺ VALIDATION
Simulate validation failures at each stage (client, server, async); verify recovery options, user feedback, partial save, retry logic, and override flow.
β–Ό 🎨 L6 β€” UI 30 matrices
#151Layout Composition Matrix6 cells12 rules6 anti6 hints
Determines how UI layouts are composed from components β€” layout primitives, nesting rules, responsive behavior, and composition patterns.
layout_typecomposition_patternresponsivenessnesting_depth
layout_001
When composing a list or column of elements, use a vertical stack layout via flex-direction: column.
βœ… RULES (2)
Use gap to space items
Prefer align-items: start for left-aligned content
❌ ANTI-PATTERNS (1)
Manually adding margin-bottom to every child
πŸ’» CODE HINTS (1)
display: flex; flex-direction: column; gap: 1rem;
layout_002
When laying out toolbar buttons or nav items in a row, use horizontal flex layout.
βœ… RULES (2)
Apply gap between items
Use justify-content to control alignment
❌ ANTI-PATTERNS (1)
Floating items instead of flex layout
πŸ’» CODE HINTS (1)
display: flex; flex-direction: row; gap: 0.5rem;
layout_003
For dashboards or data views, use CSS Grid to define 2D column/row structure.
βœ… RULES (2)
Define explicit grid-template-columns/rows
Place items using grid-area or line numbers
❌ ANTI-PATTERNS (1)
Using float or flex for complex table-like layouts
πŸ’» CODE HINTS (1)
display: grid; grid-template-columns: repeat(3, 1fr);
layout_004
When designing layouts for multiple devices, switch layout rules at responsive breakpoints.
βœ… RULES (2)
Define breakpoints for mobile/tablet/desktop
Adjust flex/grid direction or size at breakpoints
❌ ANTI-PATTERNS (1)
Fixed px widths with no media queries
πŸ’» CODE HINTS (1)
@media (min-width: 768px) { ... }
layout_005
When creating composable page templates, use slot-based composition with defined regions.
βœ… RULES (2)
Declare slots for header, body, footer
Inject components via named slots or props
❌ ANTI-PATTERNS (1)
Hardcoding layout inside each page
πŸ’» CODE HINTS (1)
<PageLayout header={<Header />} body={<Main />} footer={<Footer />} />
layout_006
To maintain readability and performance, avoid nesting layout containers beyond 3 levels deep.
βœ… RULES (2)
Flatten layout structure where possible
Use utility classes to avoid deep wrapping
❌ ANTI-PATTERNS (1)
Nested div > div > div > div chains
πŸ’» CODE HINTS (1)
.layout-grid .section .box { ... }
πŸ§ͺ VALIDATION
Verify: layouts use appropriate primitives (flex/grid), respond to breakpoints, slot regions are respected, and nesting stays under max depth.
#152Grid System Matrix6 cells12 rules6 anti6 hints
Determines how grid systems are configured β€” column counts, gutter sizes, breakpoints, and unit conversion for precise layout rendering.
grid_typecolumn_countgutter_strategyunit_system
grid_001
When designing responsive UIs using a classic 12-column layout, define fixed gutter sizes in px for consistent spacing.
βœ… RULES (2)
Use 12 equal-width columns
Set gutter width (e.g. 16px) via column-gap or padding
❌ ANTI-PATTERNS (1)
Using % for gutters which scale unpredictably
πŸ’» CODE HINTS (1)
.grid { display: grid; grid-template-columns: repeat(12, 1fr); column-gap: 16px; }
grid_002
When using CSS Grid with auto-fit columns, apply responsive gutters using clamp() to scale between breakpoints.
βœ… RULES (2)
Use clamp() for column-gap for adaptive spacing
Allow grid items to auto-fit min/max width
❌ ANTI-PATTERNS (1)
Hardcoding px gaps that don't scale on smaller screens
πŸ’» CODE HINTS (1)
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); column-gap: clamp(8px, 2vw, 24px);
grid_003
When using auto-fill layout, combine it with minmax() and flexible gutters for dynamic flow-based grids.
βœ… RULES (2)
Use minmax() with auto-fill to handle overflow gracefully
Apply column-gap: min(4vw, 32px) for responsiveness
❌ ANTI-PATTERNS (1)
Using fixed width + auto-fill without responsive consideration
πŸ’» CODE HINTS (1)
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); column-gap: min(4vw, 32px);
grid_004
When defining UI grids semantically, name grid areas for clarity and maintainability.
βœ… RULES (2)
Use grid-template-areas for explicit layout regions
Assign grid-area to each child element
❌ ANTI-PATTERNS (1)
Relying on row/column start/end numbers without names
πŸ’» CODE HINTS (1)
grid-template-areas: 'header header' 'sidebar main';
grid_005
When designing print layouts, convert grid spacing from mm to equivalent CSS units for precision across formats.
βœ… RULES (2)
Define gutters in mm or convert mm to px via 96dpi mapping
Use print-specific media queries
❌ ANTI-PATTERNS (1)
Designing for screen units only in print layouts
πŸ’» CODE HINTS (1)
@media print { .grid { column-gap: 10mm; } }
grid_006
When combining flexible and fixed layouts, use hybrid gutter strategy (e.g. fixed side margin, responsive internal gaps).
βœ… RULES (2)
Outer layout uses fixed margin (e.g. 64px)
Inner columns use responsive column-gap (e.g. 2vw)
❌ ANTI-PATTERNS (1)
Using one gutter strategy for all breakpoints
πŸ’» CODE HINTS (1)
margin: 0 64px; column-gap: 2vw;
πŸ§ͺ VALIDATION
Verify: grids respect column counts, gutters adapt by breakpoint, semantic naming used where applicable, unit conversions applied for print or hybrid contexts.
#153Flex Layout Matrix6 cells13 rules6 anti6 hints
Determines how flexbox is used for one-dimensional layouts β€” alignment, distribution, wrapping, and common patterns for 80% of screen layouts.
flex_directionalignmentdistributionwrapping
flex_001
When creating a horizontal navigation bar or toolbar, use flex-direction: row with space-between and center alignment.
βœ… RULES (3)
Set display: flex and flex-direction: row
Use justify-content: space-between
Use align-items: center for vertical centering
❌ ANTI-PATTERNS (1)
Using inline-blocks and margins to fake toolbar layout
πŸ’» CODE HINTS (1)
.toolbar { display: flex; flex-direction: row; justify-content: space-between; align-items: center; }
flex_002
When stacking form fields or list items vertically, use flex-direction: column with start alignment.
βœ… RULES (2)
Use flex-direction: column for vertical flow
align-items: flex-start for left alignment
❌ ANTI-PATTERNS (1)
Using block display for grouped spacing without control
πŸ’» CODE HINTS (1)
.form { display: flex; flex-direction: column; align-items: flex-start; gap: 12px; }
flex_003
When centering an element both horizontally and vertically, use align-items and justify-content set to center.
βœ… RULES (2)
Use flex-direction: row
Set both justify-content and align-items to center
❌ ANTI-PATTERNS (1)
Manually centering using margin or padding hacks
πŸ’» CODE HINTS (1)
.centered { display: flex; justify-content: center; align-items: center; }
flex_004
When needing even distribution across row with space at edges, use justify-content: space-between.
βœ… RULES (2)
Use flex-direction: row
Use space-between to push outer items to edges
❌ ANTI-PATTERNS (1)
Using margin auto on both ends to simulate spacing
πŸ’» CODE HINTS (1)
.row { display: flex; justify-content: space-between; }
flex_005
When wrapping items responsively (e.g. tags, chips), use flex-wrap: wrap with row direction.
βœ… RULES (2)
Set flex-wrap: wrap to allow wrapping
Combine with gap for spacing between items
❌ ANTI-PATTERNS (1)
Letting items overflow container without wrapping
πŸ’» CODE HINTS (1)
.wrap { display: flex; flex-wrap: wrap; gap: 8px; }
flex_006
When distributing items proportionally, control flex-grow, flex-shrink, and flex-basis explicitly per item.
βœ… RULES (2)
Set base size via flex-basis
Tune flex-grow/flex-shrink to match layout needs
❌ ANTI-PATTERNS (1)
Relying on default flex behavior without tuning
πŸ’» CODE HINTS (1)
.item { flex: 1 1 0; }
πŸ§ͺ VALIDATION
Verify: flexbox layouts use correct direction, alignment, wrapping, and grow-shrink-basis settings.
#154Responsive Breakpoints Matrix6 cells18 rules12 anti6 hints
Define how to select and apply responsive breakpoints to ensure optimal layout behavior across screen sizes.
breakpoint_strategycontent_density_leveldevice_classlayout_grid_behaviorscaling_modetesting_scope
MOBILE_FIRST_LINEAR_STACK
When designing UI for mobile-first experiences
βœ… RULES (3)
Start with smallest breakpoint (e.g., < 640px)
Use single-column layouts by default
Apply media queries to scale up, not down
❌ ANTI-PATTERNS (2)
Designing desktop-first and scaling down
Hiding mobile content on larger screens
πŸ’» CODE HINTS (1)
Use CSS `@media (min-width: X)` and mobile-first utilities
DESKTOP_OPTIMIZED_FIXED_GRID
When targeting widescreen enterprise interfaces
βœ… RULES (3)
Use max-width containers (e.g., 1200px or 1440px)
Align content with 12-column grid
Introduce side gutters and padding zones
❌ ANTI-PATTERNS (2)
Letting content span full width on ultra-wide displays
Skipping grid alignment for forms or tables
πŸ’» CODE HINTS (1)
Use grid frameworks like CSS Grid, Tailwind, Bootstrap grid
TABLET_ADAPTIVE_LAYOUT
When UI must adapt gracefully between mobile and desktop
βœ… RULES (3)
Define breakpoints around 768–1024px
Switch between stacked and inline layout modes
Adjust spacing and font sizes incrementally
❌ ANTI-PATTERNS (2)
Using mobile layout unchanged on tablets
Applying desktop grid too early
πŸ’» CODE HINTS (1)
Use utility classes tied to `md`/`lg` ranges
CONTENT_DENSITY_VARIANT_BREAKPOINTS
When content density must change based on screen real estate
βœ… RULES (3)
Use density classes for `compact`, `cozy`, and `comfortable` modes
Bind density to breakpoint tiers
Test readability at all density levels
❌ ANTI-PATTERNS (2)
Keeping font size fixed across all devices
Overcrowding small screens with dense UIs
πŸ’» CODE HINTS (1)
Use tokenized spacing and typography systems
DYNAMIC_CONTAINER_QUERIES
When layout must respond to parent container size instead of viewport
βœ… RULES (3)
Use `@container` queries to adapt UI inside components
Define fallback for browsers without support
Avoid relying solely on global viewport size
❌ ANTI-PATTERNS (2)
Using viewport-based breakpoints for deeply nested components
Ignoring resize behavior in embedded widgets
πŸ’» CODE HINTS (1)
Use `@container` in CSS or container-aware utility frameworks
BREAKPOINT_TESTING_AND_COVERAGE
When verifying correct layout behavior across screen sizes
βœ… RULES (3)
Test layouts at all declared breakpoints
Automate visual regression snapshots
Verify keyboard and touch behavior in each mode
❌ ANTI-PATTERNS (2)
Skipping tablet or edge-case sizes
Testing only on desktop emulator
πŸ’» CODE HINTS (1)
Use Percy, Playwright, or Cypress with viewport emulation
πŸ§ͺ VALIDATION
Render app across mobile, tablet, desktop, and container-based layouts; confirm correct grid behavior, typography scaling, and interactivity at each breakpoint.
#155Container vs Content Matrix6 cells18 rules12 anti6 hints
Clarify layout responsibility between container components and their inner content, avoiding coupling and rendering conflicts.
responsibility_scopesizing_strategyoverflow_handlingalignment_mechanismscroll_behaviorcontent_awareness
CONTAINER_DEFINED_LAYOUT_CONSTRAINTS
When a parent container dictates layout bounds for its children
βœ… RULES (3)
Define fixed or max width/height in the container
Apply padding and margin externally
Use layout wrappers for zone control
❌ ANTI-PATTERNS (2)
Letting child content overflow container unpredictably
Defining layout spacing inside child elements
πŸ’» CODE HINTS (1)
Use utility classes like `max-w-screen-lg` or layout primitives
CONTENT_DRIVEN_RESIZING_WITH_FLEX_GROW
When inner content should determine the size of its wrapper
βœ… RULES (3)
Enable flex grow/shrink on child
Let parent use `min-content` or `fit-content`
Avoid clamping dimensions unless necessary
❌ ANTI-PATTERNS (2)
Setting fixed size that truncates content
Using overflow scroll unnecessarily
πŸ’» CODE HINTS (1)
Use `flex-grow` and `min-w-fit` in Tailwind or CSS
SCROLLABLE_CONTAINER_WITH_CLIPPED_CONTENT
When content may exceed visible area in constrained space
βœ… RULES (3)
Set container to `overflow-auto` or `scroll`
Clip content visually with `max-height` or `max-width`
Preserve scrollbar accessibility
❌ ANTI-PATTERNS (2)
Allowing hidden overflow that hides content
Setting scroll on inner child instead of container
πŸ’» CODE HINTS (1)
Use `overflow-y-auto` and keyboard-focusable wrappers
CENTERED_CONTENT_WITHIN_CONTAINER
When content must appear visually centered inside a layout zone
βœ… RULES (3)
Use `flex` or `grid` with alignment utilities
Center both horizontally and vertically if needed
Ensure container has explicit size or fill behavior
❌ ANTI-PATTERNS (2)
Relying on margin auto without display context
Centering only in one axis when dual-axis needed
πŸ’» CODE HINTS (1)
Use `flex justify-center items-center` or `grid place-items-center`
CONTAINER_SCROLL_LOCK_WITHIN_MODAL
When displaying a modal or overlay that traps scroll inside
βœ… RULES (3)
Lock body scroll on modal open
Enable internal scroll on modal content area
Restore scroll state on close
❌ ANTI-PATTERNS (2)
Allowing background scroll during modal
Preventing all scroll including inside modal
πŸ’» CODE HINTS (1)
Use `overflow-hidden` on body + modal content scroll area
CONTENT_OVERFLOW_VISUAL_CUE
When content overflows and user must be aware
βœ… RULES (3)
Detect overflow and render shadows or fade cues
Use scroll indicators or peek elements
Avoid cut-off with no affordance
❌ ANTI-PATTERNS (2)
Hiding overflow with no feedback
Assuming user will scroll without signal
πŸ’» CODE HINTS (1)
Use intersection observer + fading mask
πŸ§ͺ VALIDATION
Render nested layouts with mixed overflow, resizing, and scroll-lock needs. Confirm visual integrity, scroll accessibility, and clear separation of layout concerns.
#156Component Hierarchy Matrix6 cells12 rules6 anti6 hints
Determines how UI components are organized in parent-child hierarchies β€” who owns what, composition vs inheritance, and preventing spaghetti UI.
hierarchy_depthownership_modelcomposition_patternresponsibility
ch_001
When organizing components up to 3 levels deep (page > section > widget), use flat ownership where each level manages its immediate children only.
βœ… RULES (2)
Each component owns only direct children
Avoid cross-level communication
❌ ANTI-PATTERNS (1)
Top-level page managing inner widget logic directly
πŸ’» CODE HINTS (1)
<Page><Section><Widget /></Section></Page>
ch_002
When separating data from layout, split components into container (logic/state) and presentational (UI-only) components.
βœ… RULES (2)
Container passes props to presentational
Presentational is stateless and reusable
❌ ANTI-PATTERNS (1)
Mixing stateful logic into UI component
πŸ’» CODE HINTS (1)
<UserContainer><UserCard /></UserContainer>
ch_003
When building compound components (e.g. Tabs > Tab), let parent expose children APIs and children register with parent.
βœ… RULES (2)
Parent manages active state
Children access context to register/render
❌ ANTI-PATTERNS (1)
Parent relying on props.children without control
πŸ’» CODE HINTS (1)
<Tabs><Tab label='A'/><Tab label='B'/></Tabs>
ch_004
When deep customization is needed in a nested hierarchy, use render props or function-as-children pattern.
βœ… RULES (2)
Pass function child to control rendering
Encapsulate logic but expose render slot
❌ ANTI-PATTERNS (1)
Passing static children where dynamic logic needed
πŸ’» CODE HINTS (1)
<DataProvider>{(data) => <List items={data} />}</DataProvider>
ch_005
When components accept varied content in multiple places, use named slots or props.children pattern for flexible injection.
βœ… RULES (2)
Use slots for layout composition
Name slots for clarity (e.g. header, footer)
❌ ANTI-PATTERNS (1)
Hardcoding all child positions
πŸ’» CODE HINTS (1)
<Card><Card.Header /> <Card.Body /> <Card.Footer /></Card>
ch_006
When composing stateful and display-only components, define clear boundaries β€” logic lives in parent, visuals in child.
βœ… RULES (2)
Keep business logic in upper component
Visuals receive props only
❌ ANTI-PATTERNS (1)
Display component mutating shared state
πŸ’» CODE HINTS (1)
<StateWrapper><PureDisplay value={state} /></StateWrapper>
πŸ§ͺ VALIDATION
Verify: component boundaries are respected, each layer manages only its children, compound components expose internal coordination, and logic never leaks into visual components.
#157Atomic Components Matrix6 cells18 rules12 anti7 hints
Define how to design, compose, and isolate atomic UI components for maximum reuse, clarity, and maintainability.
component_scopestate_ownershipstyling_strategyprop_handling_modetestability_levelslotting_and_composability
PURE_PRESENTATIONAL_ATOMS
When building stateless UI primitives like buttons or inputs
βœ… RULES (3)
Keep component stateless and purely visual
Receive all data and handlers via props
Avoid layout assumptions about parent
❌ ANTI-PATTERNS (2)
Embedding fetch logic or side effects in atom
Hardcoding margins or positioning
πŸ’» CODE HINTS (2)
Use `(props) => <div>{props.children}</div>` pattern
Isolate CSS via design token classes
LOCAL_STATEFUL_COMPONENTS
When building self-contained widgets like toggle switches or modals
βœ… RULES (3)
Manage only local state (e.g., open/closed)
Expose controlled vs uncontrolled modes
Ensure internal state resets on unmount
❌ ANTI-PATTERNS (2)
Using global context for local toggles
Hard-binding internal state to external props
πŸ’» CODE HINTS (1)
Use `useState` internally + `onChange` callback if needed
STYLE_ISOLATED_ATOMS_WITH_THEME_TOKENS
When ensuring atomic components adapt to themes or design systems
βœ… RULES (3)
Use design tokens for spacing, color, typography
Avoid hardcoded pixels or raw color codes
Expose variant prop (e.g., size, tone)
❌ ANTI-PATTERNS (2)
Inline styles without token mapping
Theme-agnostic fixed CSS values
πŸ’» CODE HINTS (1)
Use Tailwind, CSS modules, or `styled-components` with tokens
SLOT_BASED_COMPOSITION_SUPPORT
When allowing consumers to inject arbitrary content into UI shells
βœ… RULES (3)
Use `children` and named slots for dynamic injection
Document allowed slot areas clearly
Avoid deep prop drilling in slotted zones
❌ ANTI-PATTERNS (2)
Rigid markup without override ability
Hardcoded layout nesting
πŸ’» CODE HINTS (1)
Use `props.children`, `props.header`, `props.footer`
PROP_FORWARDING_AND_EXTENSIBILITY
When atomic components wrap native HTML elements
βœ… RULES (3)
Forward unhandled props to native root element
Use destructuring to separate known vs unknown props
Avoid shadowing common DOM props
❌ ANTI-PATTERNS (2)
Filtering out valid `aria-*` or `data-*` attributes
Blocking event handlers by omission
πŸ’» CODE HINTS (1)
Use `{...rest}` in JSX + `prop-types` or TS interfaces
TEST_FRIENDLY_API_SURFACE
When designing components for automated testing environments
βœ… RULES (3)
Expose stable `data-testid` or `aria-label` attributes
Avoid dynamic class names tied to logic
Separate logic-heavy components for test injection
❌ ANTI-PATTERNS (2)
Tying component behavior to visual-only selectors
Making test code rely on DOM structure assumptions
πŸ’» CODE HINTS (1)
Use `data-testid="btn-ok"` and test-friendly variant APIs
πŸ§ͺ VALIDATION
Render all atomic components with test fixtures across multiple themes, breakpoints, and prop sets. Verify slot behavior, styling consistency, and accessibility tagging.
#158Composite Components Matrix6 cells18 rules12 anti6 hints
Define how to structure, isolate, and manage composite UI components built from atomic parts for clarity, scalability, and reusability.
composition_strategystate_propagation_modeinternal_vs_external_layoutreusability_scopedependency_injection_methodslot_customization_support
SIMPLE_WRAPPER_WITH_FIXED_STRUCTURE
When wrapping atoms in a fixed hierarchy (e.g., Card, InputGroup)
βœ… RULES (3)
Use atomic components as children
Keep internal layout static and opinionated
Expose only high-level props to configure inner parts
❌ ANTI-PATTERNS (2)
Letting parent override too many internals
Creating per-use-case variants instead of one reusable
πŸ’» CODE HINTS (1)
Use `<Card><CardHeader/><CardBody/></Card>` style composition
COMPOSITE_WITH_SLOT_INJECTION_SUPPORT
When consumer must control content inside structural shell
βœ… RULES (3)
Use `children`, `header`, `footer`, etc. as named slots
Define fallback defaults per slot
Style outer layout, leave slot content agnostic
❌ ANTI-PATTERNS (2)
Hardcoding content inside shell
Preventing override of content area
πŸ’» CODE HINTS (1)
Use `props.children` and optional subcomponents
STATEFUL_COMPOSITE_WITH_CONTROLLED_API
When composite component manages coordinated internal state
βœ… RULES (3)
Keep internal state via `useState` or `useReducer`
Expose value + onChange props for control
Sync derived props with state transitions
❌ ANTI-PATTERNS (2)
Mutating state directly from child atoms
Leaking inner state shape to consumers
πŸ’» CODE HINTS (1)
Expose `value/onChange` API like input elements
LAYOUT_AGNOSTIC_COMPOSABLE_GROUP
When composing group of atoms that can be laid out externally
βœ… RULES (3)
Expose each atom via named exports
Avoid wrapping layout logic into group
Let parent arrange atoms with its layout system
❌ ANTI-PATTERNS (2)
Encapsulating fixed layout in the composite
Hiding access to individual atomic parts
πŸ’» CODE HINTS (1)
Export `{ Field, Label, Input }` separately from group
THEME_AWARE_COMPOSITE_COMPONENT
When visual appearance must adapt to theme or context
βœ… RULES (3)
Use tokenized variables for color, spacing, typography
Expose `variant`, `size`, `tone` props
Apply design constraints at composite level
❌ ANTI-PATTERNS (2)
Hardcoding styles without theme binding
Duplicating theme logic inside each atom
πŸ’» CODE HINTS (1)
Use design system context or utility classes with theme tokens
INJECTABLE_BEHAVIOR_COMPOSITE
When behavior (e.g., validation, tracking) should be added externally
βœ… RULES (3)
Support hook injection or context wrapping
Expose lifecycle or event hook points
Avoid coupling core logic to specific behaviors
❌ ANTI-PATTERNS (2)
Wiring analytics or validators directly into component
Preventing external enhancement of logic
πŸ’» CODE HINTS (1)
Use `useEffect` listeners or event bubbling with context
πŸ§ͺ VALIDATION
Render composite components with nested atoms, injected slots, state control, and side-effects. Confirm predictable behavior, theme adaptation, and layout control boundaries.
#159Slot / Children Matrix6 cells18 rules12 anti6 hints
Define how to structure and expose content insertion points in UI components using children and named slots.
insertion_mechanismnamed_vs_default_slotslayout_responsibilityfallback_content_strategypropagation_of_propsnesting_and_override_behavior
DEFAULT_CHILDREN_RENDERING
When simple content is passed between component tags
βœ… RULES (3)
Access content via `props.children`
Render children in fixed position inside layout
Do not transform or interpret children content
❌ ANTI-PATTERNS (2)
Wrapping children in unexpected containers
Omitting `children` from render tree
πŸ’» CODE HINTS (1)
Use `{props.children}` directly in JSX
NAMED_SLOT_PROP_INJECTION
When consumers need to insert content into specific sub-regions
βœ… RULES (3)
Define named props like `header`, `footer`, `actions`
Render each slot in predefined layout zone
Type slots to accept JSX or component
❌ ANTI-PATTERNS (2)
Combining named slots and children ambiguously
Forcing consumers to deeply nest for layout override
πŸ’» CODE HINTS (1)
Use `props.header && <div>{props.header}</div>` syntax
SLOT_WITH_DEFAULT_FALLBACK
When slot content is optional but component must remain usable
βœ… RULES (3)
Check if slot prop exists, else render fallback
Keep fallback logic close to slot zone
Document fallback behavior explicitly
❌ ANTI-PATTERNS (2)
Leaving slot region blank
Making fallback dependent on external state
πŸ’» CODE HINTS (1)
Use `{props.header ?? <DefaultHeader />}`
PROPAGATED_CONTEXT_TO_SLOT
When slot content needs access to internal state or props
βœ… RULES (3)
Pass context via render prop or React context
Avoid prop drilling through slot chains
Expose stable API contract for slot consumers
❌ ANTI-PATTERNS (2)
Letting slot content access outer scope implicitly
Binding internal props dynamically without control
πŸ’» CODE HINTS (1)
Use `(ctx) => props.slot(ctx)` pattern
OVERRIDABLE_NESTED_SLOT_TREES
When deeply nested components require partial layout overrides
βœ… RULES (3)
Expose override points at multiple levels
Use consistent slot naming across hierarchy
Fallback to default layout for non-overridden branches
❌ ANTI-PATTERNS (2)
Flattening deeply nested structure into one-level slots
Requiring full reimplementation for minor override
πŸ’» CODE HINTS (1)
Expose nested slots as subcomponents or named keys
CHILDREN_AND_SLOT_INTEROPERABILITY
When component supports both children and named slots
βœ… RULES (3)
Document precedence of `children` vs named slots
Render one as primary, conditionally hide other
Warn when both are used without clear intent
❌ ANTI-PATTERNS (2)
Merging children and slots into same DOM node
Failing silently when both are passed
πŸ’» CODE HINTS (1)
Use `if (children) return children; else render slots`
πŸ§ͺ VALIDATION
Render component with default children, named slots, missing slots, nested overrides, and slot-context injection. Confirm correctness, fallback rendering, and DOM output consistency.
#160Reusability Matrix6 cells12 rules6 anti6 hints
Determines how UI components are designed for reuse β€” prop interfaces, composition patterns, and avoiding premature abstraction.
reuse_levelabstraction_methodprop_designdocumentation
reusability_001
When building a one-off UI unit, define a single purpose component with clear, strict prop interface.
βœ… RULES (2)
Name props descriptively for one job
Avoid optional or vague props
❌ ANTI-PATTERNS (1)
Generic props like `data` or `config`
πŸ’» CODE HINTS (1)
<UserAvatar src={user.image} alt={user.name} size='sm' />
reusability_002
When reusing the same component across variants (e.g. primary/secondary buttons), expose variant props explicitly.
βœ… RULES (2)
Use enum-style prop like variant='primary'
Style variants consistently
❌ ANTI-PATTERNS (1)
Boolean props that conflict (e.g. `isRed`, `isBold`)
πŸ’» CODE HINTS (1)
<Button variant='secondary' size='lg' />
reusability_003
When designing interrelated components (e.g. Tabs, Accordion), use compound pattern with shared context and slot components.
βœ… RULES (2)
Expose subcomponents as properties of parent
Use React context for internal coordination
❌ ANTI-PATTERNS (1)
Require manual prop passing to subcomponents
πŸ’» CODE HINTS (1)
<Tabs><Tabs.List>...<Tabs.Panel>...</Tabs></Tabs>
reusability_004
When separating logic from presentation, create headless component that provides state via hook or render prop.
βœ… RULES (2)
Expose logic only, require consumer to render UI
Provide accessibility behaviors if relevant
❌ ANTI-PATTERNS (1)
Bundling logic with default UI without override
πŸ’» CODE HINTS (1)
const { isOpen, toggle } = useDisclosure()
reusability_005
When tempted to extract reusable logic, apply Rule of Three β€” wait for 3 real use cases before abstraction.
βœ… RULES (2)
Avoid abstracting after first reuse
Track duplication before generalizing
❌ ANTI-PATTERNS (1)
Premature creation of utils or shared component with speculative props
πŸ’» CODE HINTS (1)
// repeated ButtonWithIcon pattern used in 3 places β†’ refactor
reusability_006
When component is reusable, document via Storybook with multiple usage examples and edge cases.
βœ… RULES (2)
Provide stories for all variants and sizes
Add usage notes and accessibility hints
❌ ANTI-PATTERNS (1)
No documentation beyond inline code comments
πŸ’» CODE HINTS (1)
export const Primary = () => <Button variant='primary'>Save</Button>
πŸ§ͺ VALIDATION
Verify: components are reused via props or slots, abstractions follow Rule of Three, logic/UI separated when needed, and documentation clearly shows usage.
#161Visual Consistency Matrix6 cells18 rules12 anti6 hints
Define how to ensure consistent visual styling across atomic and composite components regardless of layout context.
color_system_usagespacing_scale_adherencetypography_consistencycomponent_variant_alignmenticonography_rulestheme_support_behavior
TOKENIZED_COLOR_USAGE
When multiple components reference brand or status colors
βœ… RULES (3)
Use centralized color tokens (e.g., `primary.500`, `error.700`)
Map token names to semantic intent, not fixed hex
Avoid direct hex or RGB usage in components
❌ ANTI-PATTERNS (2)
Hardcoding `#007AFF` in styles
Using different blue tones across components
πŸ’» CODE HINTS (1)
Use `theme.colors.semanticRole` references in design tokens
SCALED_SPACING_SYSTEM
When laying out elements with padding or margins
βœ… RULES (3)
Use spacing scale (e.g., 4px, 8px, 12px, 16px, etc.)
Avoid in-between pixel values not in scale
Apply same spacing units across padding/margin/grid
❌ ANTI-PATTERNS (2)
Using `13px` gap between items
Inconsistent padding inside similar cards
πŸ’» CODE HINTS (1)
Use spacing token classes or grid spacing utilities
TYPOGRAPHY_ROLE_ENFORCEMENT
When rendering headings, labels, or body text
βœ… RULES (3)
Define typography roles like `heading-md`, `body-sm`
Use tokens or classes that encode these roles
Avoid inline font overrides or size declarations
❌ ANTI-PATTERNS (2)
Setting `font-size: 15px` inline
Mixing heading levels visually
πŸ’» CODE HINTS (1)
Use predefined typography utility classes or token maps
VARIANT_ALIGNMENT_ACROSS_COMPONENTS
When a design system defines variants like `primary`, `secondary`, `ghost`
βœ… RULES (3)
Map variant prop to consistent styling rules
Align variant behavior across buttons, tags, alerts, etc.
Test visual parity across component families
❌ ANTI-PATTERNS (2)
Using `primary` as filled in one place, outline elsewhere
Variants looking inconsistent across component types
πŸ’» CODE HINTS (1)
Use shared variant map in theme configuration
ICON_SIZE_AND_ALIGNMENT_RULES
When using icons inline with text or inside components
βœ… RULES (3)
Standardize icon sizes per context (e.g., 16px in buttons)
Align icon center with text baseline when inline
Avoid mixing icon sets with differing aspect ratios
❌ ANTI-PATTERNS (2)
Inconsistent icon sizes in adjacent buttons
Uncentered icons next to labels
πŸ’» CODE HINTS (1)
Use icon wrapper with vertical-align utility
DARK_LIGHT_THEME_VISUAL_PARITY
When supporting multiple themes across the app
βœ… RULES (3)
Define tokens for both light and dark variants
Test components in both themes side-by-side
Avoid low contrast or unbalanced brightness in dark mode
❌ ANTI-PATTERNS (2)
Using same gray token for both themes
Neglecting to validate shadow and border visibility
πŸ’» CODE HINTS (1)
Use theme-aware token switcher or dual-theme preview tool
πŸ§ͺ VALIDATION
Render UI kits and real app screens across themes, breakpoints, and densities; verify color, spacing, type, icon, and variant consistency in all contexts.
#162Theming Matrix6 cells18 rules12 anti6 hints
Define how to structure, scope, and apply themes across components to ensure scalable visual customization.
theme_definition_scopetoken_application_layertheme_switching_mechanismcontextual_overridesglobal_vs_local_resolutiondesign_tool_integration
GLOBAL_THEME_TOKEN_PROVIDER
When defining the base color, spacing, and typography system for the entire app
βœ… RULES (3)
Define design tokens in a global theme object
Expose via theme provider context at root
Use semantic token names (e.g., primary.500)
❌ ANTI-PATTERNS (2)
Hardcoding styles in components
Duplicating token values across files
πŸ’» CODE HINTS (1)
Use ThemeProvider with centralized theme map
LOCAL_COMPONENT_THEME_OVERRIDES
When a component must visually differ in specific usage contexts
βœ… RULES (3)
Accept `theme` or `variant` props at component level
Merge overrides with global theme tokens
Document override surface clearly
❌ ANTI-PATTERNS (2)
Overriding deep internals via className hacks
Assuming global theme will cover all use cases
πŸ’» CODE HINTS (1)
Use shallow merge + variant switch in styling logic
MULTI_THEME_SUPPORT_WITH_RUNTIME_SWITCH
When the app must support multiple visual themes (e.g., light/dark)
βœ… RULES (3)
Store theme preference in localStorage or system setting
Provide runtime toggle mechanism
Recompute tokens based on active theme
❌ ANTI-PATTERNS (2)
Reloading entire app to change theme
Mixing incompatible tokens at runtime
πŸ’» CODE HINTS (1)
Use CSS variables with theme class switch or stateful context
CONTEXTUAL_THEME_INJECTION
When nested sections of the app require unique look and feel
βœ… RULES (3)
Use nested ThemeProviders for section-specific themes
Avoid leaking contextual tokens into outer scopes
Reset theme context on exit of scoped section
❌ ANTI-PATTERNS (2)
Applying theme globally for a local visual tweak
Letting deeply nested theme bleed globally
πŸ’» CODE HINTS (1)
Use layered theme contexts with controlled scope
THEME_TOKEN_LAYERING_FOR_VARIANTS
When multiple theme variants share base tokens but need targeted differences
βœ… RULES (3)
Layer variant-specific tokens on top of base
Use alias tokens to redirect variant mappings
Fallback to base when override is missing
❌ ANTI-PATTERNS (2)
Copy-pasting entire token sets per variant
Overriding core tokens with variant logic
πŸ’» CODE HINTS (1)
Use token aliasing and spread syntax in theme maps
DESIGN_TOOL_THEME_SYNC
When ensuring parity between design system and code
βœ… RULES (3)
Export design tokens in design-compatible format (e.g., JSON, Style Dictionary)
Version control theme tokens as source of truth
Run consistency checks across tokens in UI kit and codebase
❌ ANTI-PATTERNS (2)
Using different color names in Figma and code
Allowing token drift between design and implementation
πŸ’» CODE HINTS (1)
Use Style Dictionary + Figma Tokens plugin or API sync
πŸ§ͺ VALIDATION
Render app in multiple themes (global, scoped, runtime) with light/dark/user presets. Confirm isolation, override behavior, and visual integrity in design/code parity.
#163Spacing System Matrix6 cells18 rules12 anti6 hints
Define how to apply, scale, and enforce spacing throughout UI components to ensure rhythm, consistency, and maintainability.
spacing_scaleapplication_contextcomponent_typeresponsibility_layerdensity_variantresponsive_behavior
FIXED_SCALE_TOKEN_SPACING
When applying spacing in standard layout components
βœ… RULES (3)
Use spacing tokens like `space.2`, `space.4`, `space.6`
Avoid raw pixel or percentage values
Apply same tokens across margin, padding, gap
❌ ANTI-PATTERNS (2)
Mixing `px` and token units
Using non-token values like `13px`
πŸ’» CODE HINTS (1)
Use `theme.spacing[x]` or `class=gap-4`
COMPONENT_INTERNAL_SPACING_STANDARDIZATION
When composing internal elements like labels, inputs, buttons
βœ… RULES (3)
Define standard spacing per component family
Use `gap` or nested padding, not manual margins
Ensure spacing is responsive within breakpoint tiers
❌ ANTI-PATTERNS (2)
Manually spacing elements with margin overrides
Inconsistent gaps across repeated instances
πŸ’» CODE HINTS (1)
Use `gap-x-4 gap-y-2` or spacing tokens from config
PARENT_LAYOUT_CONTROLLED_SPACING
When container or grid controls spacing between children
βœ… RULES (3)
Set spacing at layout level, not inside children
Avoid coupling child margin to sibling behavior
Use `gap` in grid/flex parents only
❌ ANTI-PATTERNS (2)
Children using margin to simulate inter-gap
Mixing gap and margin in same axis
πŸ’» CODE HINTS (1)
Use `gap-6` on parent; zero margin on children
DENSITY_AWARE_SPACING_VARIANTS
When supporting compact, cozy, and comfortable layout modes
βœ… RULES (3)
Define spacing scale multipliers per density
Use variant props or theme switches to adapt spacing
Test component in all density modes
❌ ANTI-PATTERNS (2)
Using fixed spacing across all densities
Failing to preview low-density configurations
πŸ’» CODE HINTS (1)
Use `data-density` attribute + density tokens
RESPONSIVE_SPACING_TIERS
When spacing must change between breakpoints
βœ… RULES (3)
Define spacing tiers: `sm`, `md`, `lg`, `xl`
Use media queries or responsive classes for spacing
Align spacing tiers with typography and layout tiers
❌ ANTI-PATTERNS (2)
Fixed spacing regardless of screen size
Jumping from zero to too-large spacing at one breakpoint
πŸ’» CODE HINTS (1)
Use `sm:gap-2 md:gap-4 xl:gap-6`
SPACING_VISUAL_DEBUG_MODE
When verifying spacing rules across complex UIs
βœ… RULES (3)
Add outline/box-shadow debug class to all spaced zones
Expose toggles in dev tools to highlight spacing
Use spacing overlays to visualize rhythm
❌ ANTI-PATTERNS (2)
Relying solely on pixel measurements
Having no way to inspect spacing consistency
πŸ’» CODE HINTS (1)
Use `debug-spacing` class or dev overlay toggle
πŸ§ͺ VALIDATION
Render full layouts and components in multiple screen sizes and density variants. Verify token application, inter-component gaps, and visual rhythm with and without debug overlays.
#164Typography Matrix6 cells18 rules12 anti6 hints
Define how to structure, scale, and apply typography roles across UI components to ensure clarity, hierarchy, and consistency.
typography_rolescaling_methodapplication_contextresponsive_behaviorthematic_variation_supportstyle_tokenization
ROLE_BASED_TYPOGRAPHY_SYSTEM
When different text elements (titles, labels, body) need unique treatment
βœ… RULES (3)
Define a tokenized set of roles (e.g., heading-lg, label-sm)
Apply roles based on usage, not style
Avoid duplicating font styles ad hoc
❌ ANTI-PATTERNS (2)
Using raw `font-size` in every component
Reinventing font specs in each feature
πŸ’» CODE HINTS (1)
Use `class="typography-heading-md"` or `textStyle='body-sm'`
SCALE_TOKEN_MULTIPLIERS
When typography must scale with component density or app zoom
βœ… RULES (3)
Apply density-aware multipliers to base roles
Scale line-height proportionally with font-size
Clamp extreme sizes on very small/large screens
❌ ANTI-PATTERNS (2)
Using same font-size for mobile and desktop
Letting font scale break layout box
πŸ’» CODE HINTS (1)
Use CSS clamp() or Tailwind’s responsive font classes
CONTEXTUAL_ROLE_MAPPING
When text roles vary by visual region (e.g., card vs dialog vs table)
βœ… RULES (3)
Map same semantic role to different size/tone in context
Use theme-level overrides per zone
Expose mapping config to design system consumers
❌ ANTI-PATTERNS (2)
Hardcoding font size inside component
Forgetting to remap roles in dense layouts
πŸ’» CODE HINTS (1)
Use design tokens with context scope (e.g., `text.card.label`)
RESPONSIVE_TYPOGRAPHY_BREAKPOINTS
When typography must adjust across screen sizes
βœ… RULES (3)
Define breakpoints for all major roles
Avoid jumps in font-size between tiers
Test layout integrity with font scaling on
❌ ANTI-PATTERNS (2)
Keeping fixed size across breakpoints
Using hard media queries per component
πŸ’» CODE HINTS (1)
Use `sm:text-base md:text-lg xl:text-xl` or theme token maps
THEME_AWARE_TYPE_TOKENS
When supporting light/dark themes or tone-based styles
βœ… RULES (3)
Tokenize color, weight, and letter spacing
Bind tokens to theme context dynamically
Avoid inlined hex or font overrides in JSX
❌ ANTI-PATTERNS (2)
Forgetting type color in dark mode
Overriding font-weight inline with style attr
πŸ’» CODE HINTS (1)
Use `textStyle='label-bold'` or theme-aware utility classes
COMPOSITION_SAFE_TYPOGRAPHY_UNITS
When composing text within variable layouts (grids, modals, flyouts)
βœ… RULES (3)
Use `rem` or `em` units instead of `px`
Respect container box and padding limits
Align to baseline grid where applicable
❌ ANTI-PATTERNS (2)
Overflowing text from its container
Using absolute pixel units that ignore zoom
πŸ’» CODE HINTS (1)
Use `text-base leading-relaxed` and layout grid snapping
πŸ§ͺ VALIDATION
Render all components using typography roles across breakpoints, densities, and themes. Confirm readability, layout stability, and token usage correctness.
#165Color System Matrix6 cells18 rules12 anti6 hints
Resolve how to define, organize, and apply color tokens to achieve consistency, accessibility, and themeability.
token_scopesemantic_mappingtheme_variation_handlingcontrast_complianceapplication_methoddesign_tool_sync
GLOBAL_BASE_COLOR_TOKENS
When defining a base set of reusable color primitives
βœ… RULES (3)
Define core tokens like `gray.100`, `blue.500`, `red.700`
Ensure all themes derive from these primitives
Avoid mixing primitive and semantic usage in same file
❌ ANTI-PATTERNS (2)
Scattering raw hex codes across the codebase
Duplicating shades in each component
πŸ’» CODE HINTS (1)
Use `theme.colors.base.*` token definitions
SEMANTIC_ROLE_COLOR_MAPPING
When mapping visual meaning to color
βœ… RULES (3)
Define roles like `text.primary`, `bg.surface`, `border.subtle`
Map roles to base tokens via theme config
Keep role-token mapping centralized
❌ ANTI-PATTERNS (2)
Hardcoding `#000` as 'text color'
Letting components choose direct base tokens
πŸ’» CODE HINTS (1)
theme.colors.semantic -> base token indirection
THEME_MODE_COLOR_OVERRIDES
When supporting light, dark, or custom visual themes
βœ… RULES (3)
Override semantic token values per theme
Maintain same role names across modes
Test contrast of each role in every theme
❌ ANTI-PATTERNS (2)
Changing token names across modes
Forgetting contrast validation in dark mode
πŸ’» CODE HINTS (1)
Use CSS vars: `--color-text-primary` swapped per theme root
ACCESSIBLE_CONTRAST_COLOR_PAIRS
When applying text or UI elements on colored backgrounds
βœ… RULES (3)
Define approved foreground/background pairs
Use 4.5:1 for text, 3:1 for large/bold text
Test dynamic states (hover, active, disabled)
❌ ANTI-PATTERNS (2)
Assuming design is accessible without testing
Using subtle text over colored surfaces
πŸ’» CODE HINTS (1)
Use contrast checker (e.g., axe-core, WCAG tools)
TOKENIZED_COLOR_APPLICATION_PATTERNS
When applying colors inside components or stylesheets
βœ… RULES (3)
Use theme token references in CSS or JS
Avoid inline style hex codes
Fallback gracefully if token missing
❌ ANTI-PATTERNS (2)
Using `style={ color: '#444' }` in JSX
Missing token fallbacks causing render issues
πŸ’» CODE HINTS (1)
Use `theme.colors.semanticRole` or CSS var wrappers
DESIGN_TOKEN_EXPORT_FOR_TOOLING
When syncing codebase tokens with design tools
βœ… RULES (3)
Export tokens as JSON or Style Dictionary format
Automate push to Figma or other tools
Use single source of truth for token management
❌ ANTI-PATTERNS (2)
Manually copy-pasting token values
Using different color naming between tools
πŸ’» CODE HINTS (1)
Use Style Dictionary + Figma Tokens plugin
πŸ§ͺ VALIDATION
Render all theme modes with semantic tokens across UI. Confirm contrast compliance, token reuse, and sync with design tool exports.
#166Iconography Matrix6 cells18 rules12 anti7 hints
Resolves how and when to apply icons to UI elements for clarity, consistency, and accessibility.
interaction_contextsemantic_categorydensity_levelaccessibility_needvisual_weighticon_source
BUTTON_ACTION_ICON
When a button triggers a primary action like submit or send
βœ… RULES (3)
Use a leading icon aligned to text
Ensure icon represents action clearly (e.g., paper plane for send)
Size icon to 16–20px in normal density UI
❌ ANTI-PATTERNS (2)
Icons with ambiguous meaning
Using icon-only buttons without tooltip
πŸ’» CODE HINTS (2)
<Button icon='send'>Submit</Button>
aria-label='Send' for icon-only
ICON_ONLY_INDICATOR
When indicating status or state in space-constrained UI
βœ… RULES (3)
Use standard symbols (e.g. check, x, warning)
Color-code icon according to severity or state
Add tooltip on hover for screen reader parity
❌ ANTI-PATTERNS (2)
Color-only indicators
Non-standard custom shapes
πŸ’» CODE HINTS (1)
<StatusIcon status='success' />
NAVIGATION_MENU_ICON
When displaying vertical or horizontal navigation menus
βœ… RULES (3)
Use familiar icons (e.g. house, gear, person)
Align left of label, consistent spacing
Highlight active item with color/icon fill
❌ ANTI-PATTERNS (2)
Changing icon positions per item
Mixed icon styles within one menu
πŸ’» CODE HINTS (1)
<MenuItem icon='home'>Home</MenuItem>
FORM_FIELD_INLINE_ICON
When decorating or enhancing input fields with icons
βœ… RULES (3)
Use right-aligned icons inside input border
Do not obstruct typing area
Icon must not interfere with keyboard navigation
❌ ANTI-PATTERNS (2)
Icon overlaps text
Icon as placeholder
πŸ’» CODE HINTS (1)
<Input iconRight='search' />
ACCESSIBLE_ICON_USAGE
When designing for users with visual impairments
βœ… RULES (3)
Use aria-label or title for icon-only elements
Ensure sufficient contrast ratio (> 4.5:1)
Avoid using icon shape or color as sole indicator
❌ ANTI-PATTERNS (2)
Silent icons with no ARIA
Color-only indicators
πŸ’» CODE HINTS (1)
<Icon aria-label='Download' />
ICON_LIBRARY_INTEGRATION
When using icons from external libraries
βœ… RULES (3)
Prefer a single icon library per project
Tree-shake unused icons in build
Fallback to inline SVGs if icon not found
❌ ANTI-PATTERNS (2)
Mixing Material and Feather in same UI
Bundling full icon packs
πŸ’» CODE HINTS (1)
import { Check } from 'lucide-react'
πŸ§ͺ VALIDATION
Verify: icons match action/state, contrast accessible, tooltips exist for icon-only, spacing and alignment consistent, and single library used per interface.
#167Matrix 167 β€” Density Matrix6 cells18 rules18 anti6 hints
Define how to manage UI density levels (compact, cozy, comfortable) to optimize information display and usability across contexts and user preferences.
density_tierspacing_scale_factortypography_adjustmenttouch_target_sizingcontent_truncation_strategyuser_preference_binding
COMFORTABLE_LAYOUT_DEFAULT
When designing for general readability and relaxed interfaces
βœ… RULES (3)
Use 100% base spacing scale
Apply default font sizes
Ensure touch targets β‰₯ 48px
❌ ANTI-PATTERNS (3)
Cramped spacing for text
Reducing whitespace to fit more data
Overriding defaults inconsistently
πŸ’» CODE HINTS (1)
padding: var(--space-md); font-size: 1rem;
COMPACT_DENSITY_FOR_DATA_TABLES
When designing data-dense views for expert users
βœ… RULES (3)
Reduce spacing scale by 25%
Shrink font size slightly
Ensure touch targets β‰₯ 36px
❌ ANTI-PATTERNS (3)
Overlapping or unreadable labels
Using compact density globally
Decreasing accessibility contrast
πŸ’» CODE HINTS (1)
class: density-compact; font-size: 0.875rem;
COZY_INTERMEDIATE_MODE
When balancing display efficiency with comfort
βœ… RULES (3)
Reduce spacing by 10–15%
Maintain base font size
Allow user toggle between cozy and default
❌ ANTI-PATTERNS (3)
No toggle support for users
Inconsistent component scaling
No documentation of cozy variant
πŸ’» CODE HINTS (1)
toggleDensity('cozy') or useDensityClass('cozy')
DENSITY_RESPONSIVE_SWITCHING
When adapting density to device type or screen size
βœ… RULES (3)
Use media queries to infer density
Switch to compact on small devices
Allow override if user has set preference
❌ ANTI-PATTERNS (3)
Hardcoding single density per platform
Overriding user setting with device mode
No detection logic for screen breakpoints
πŸ’» CODE HINTS (1)
@media (max-width: 600px) { ...compact styles... }
USER_BOUND_DENSITY_TOGGLING
When user should control UI density mode
βœ… RULES (3)
Persist user setting to local storage
Expose clear toggle in settings or toolbar
Respect system-level preferences if available
❌ ANTI-PATTERNS (3)
Forcing UI changes without consent
No visual indicator of current density
No persistence across sessions
πŸ’» CODE HINTS (1)
localStorage.setItem('ui-density', 'cozy')
COMPONENT_DENSITY_VARIANTS
When a component must support all three density tiers
βœ… RULES (3)
Define density variants per component
Test all variants in visual regression tests
Avoid style overrides that break layout
❌ ANTI-PATTERNS (3)
Hardcoding spacing in component styles
Skipping tests on alternate densities
Allowing drift across density themes
πŸ’» CODE HINTS (1)
component.density = 'compact' // prop or theme var
πŸ§ͺ VALIDATION
Test layout across all densities (compact, cozy, comfortable). Validate visual balance, spacing, and user toggling behavior across breakpoints and platforms.
#168Accessibility Semantics Matrix6 cells12 rules6 anti10 hints
Determines how semantic HTML and ARIA attributes ensure accessibility β€” landmarks, roles, labels, and screen reader compatibility.
semantic_elementaria_attributescreen_readerkeyboard
a11y_001
When structuring page layout, use semantic landmarks like <header>, <main>, and <nav> for screen reader orientation.
βœ… RULES (2)
Each page should have one <main>
Use <nav> for grouped links
❌ ANTI-PATTERNS (1)
Using only <div>s for layout blocks
πŸ’» CODE HINTS (2)
<header>...</header>
<nav aria-label='Main menu'>...</nav>
a11y_002
When presenting modals or alerts, use appropriate ARIA roles like role='dialog' or role='alert' to announce context.
βœ… RULES (2)
Dialogs must trap focus
Alerts must auto-announce
❌ ANTI-PATTERNS (1)
No role on modals β†’ screen readers miss them
πŸ’» CODE HINTS (2)
<div role='dialog' aria-modal='true'>...</div>
<div role='alert'>Error occurred</div>
a11y_003
When an element needs a programmatic name, use aria-label or aria-labelledby for screen reader clarity.
βœ… RULES (2)
aria-label for short inline labels
aria-labelledby to reference visible labels
❌ ANTI-PATTERNS (1)
Unnamed buttons or icons with no accessible name
πŸ’» CODE HINTS (2)
<button aria-label='Close'>X</button>
<div aria-labelledby='section-title'>...</div>
a11y_004
When content updates dynamically (e.g. chat messages), use aria-live regions to inform screen readers of changes.
βœ… RULES (2)
aria-live='polite' for low priority
aria-live='assertive' for urgent changes
❌ ANTI-PATTERNS (1)
DOM updates without aria-live container
πŸ’» CODE HINTS (1)
<div aria-live='polite'>New message from Sarah</div>
a11y_005
When creating clickable elements, use <button> not <div onClick> to ensure keyboard and screen reader support.
βœ… RULES (2)
Use <button> for all actions
If using <div>, manually add role, tabindex, and key handlers
❌ ANTI-PATTERNS (1)
Clickable <div> without keyboard support
πŸ’» CODE HINTS (2)
<button onClick={save}>Save</button>
<div role='button' tabindex='0' onKeyDown=...>
a11y_006
When building accessible pages, include a skip navigation link at top of DOM to let keyboard users jump to main content.
βœ… RULES (2)
Link must be first in DOM order
Visible on focus
❌ ANTI-PATTERNS (1)
No skip link β†’ users must tab through header every time
πŸ’» CODE HINTS (1)
<a href='#main-content' class='skip-link'>Skip to content</a>
πŸ§ͺ VALIDATION
Verify: landmark elements used, dialogs and alerts have roles, labels provided, aria-live used for updates, buttons semantic, skip link enabled.
#169Keyboard Navigation Matrix6 cells18 rules12 anti6 hints
Define how to implement accessible, consistent, and predictable keyboard navigation across UI components.
navigation_scopefocus_order_strategyfocus_visible_handlinglooping_and_exitaria_roles_and_labelskeyboard_shortcuts_support
LINEAR_TAB_ORDER
When navigating through simple form fields or buttons in a single direction
βœ… RULES (3)
Ensure DOM order matches visual order
Use `tabindex=0` for interactive elements
Avoid removing focusable elements from flow unnecessarily
❌ ANTI-PATTERNS (2)
Using `tabindex=-1` without fallback
Placing items visually before DOM order
πŸ’» CODE HINTS (1)
Use semantic HTML + `tabindex=0`
FOCUS_TRAP_IN_MODAL
When user opens a modal or dialog overlay
βœ… RULES (3)
Trap tab key within modal boundaries
Return focus to trigger element on close
Include invisible sentinels or JS focus loop
❌ ANTI-PATTERNS (2)
Letting tab flow reach background content
Losing focus on modal open
πŸ’» CODE HINTS (1)
Use focus-trap libraries or sentinel elements
ARROW_KEY_GROUP_NAVIGATION
When navigating among grouped elements (e.g., menus, tabs, radio buttons)
βœ… RULES (3)
Use arrow keys to move focus within group
Update `aria-activedescendant` or manage roving tabindex
Loop or clamp movement at boundaries
❌ ANTI-PATTERNS (2)
Using tab for intra-group movement
Failing to announce active item
πŸ’» CODE HINTS (1)
Use roving tabindex or `aria-activedescendant` + keyboard handler
CUSTOM_SHORTCUT_TRIGGERING
When user presses keyboard shortcuts to trigger actions
βœ… RULES (3)
Register shortcuts with clear scope (global vs scoped)
Avoid collisions with browser/system keys
Show shortcut hints in UI where applicable
❌ ANTI-PATTERNS (2)
Attaching shortcuts to dynamic elements unpredictably
Using unannounced or undocumented keys
πŸ’» CODE HINTS (1)
Use `keydown` listeners on `window` or scoped containers
VISIBLE_FOCUS_INDICATORS
When user navigates via keyboard without mouse
βœ… RULES (3)
Apply custom focus ring or use browser default
Do not remove `outline` globally without alternative
Use `:focus-visible` to limit visual noise
❌ ANTI-PATTERNS (2)
Hiding focus state for aesthetics
Relying only on hover/focus fusion
πŸ’» CODE HINTS (1)
Use Tailwind `focus-visible:outline-blue-500` or similar
ESCAPE_TO_EXIT_OVERLAY
When user wants to dismiss modals, popovers, or menus via keyboard
βœ… RULES (3)
Bind `Escape` key to close active overlay
Return focus to logical prior element
Prevent propagation if nested overlay hierarchy
❌ ANTI-PATTERNS (2)
Forgetting Escape binding
Leaving overlays open after dismissal command
πŸ’» CODE HINTS (1)
Add `onKeyDown={e => e.key==='Escape' && close()}`
πŸ§ͺ VALIDATION
Test navigation flows using keyboard only: tabbing, arrow movement, modal traps, shortcut triggers, focus visibility, and overlay dismissals. Ensure accessibility via screen reader announcements.
#170Focus Management Matrix6 cells12 rules6 anti6 hints
Determines how keyboard focus is managed across UI β€” focus trapping in modals, tab order, focus restoration, and accessibility compliance.
focus_scopetab_ordertrap_behaviorrestoration
focus_001
When navigating a page with a keyboard, allow natural tab order (tabIndex=0) to follow DOM sequence.
βœ… RULES (2)
Assign tabIndex=0 to focusable elements
Avoid tabIndex > 0 unless overriding sequence
❌ ANTI-PATTERNS (1)
Using tabIndex > 1 arbitrarily and breaking expected flow
πŸ’» CODE HINTS (1)
<button tabIndex="0">Click</button>
focus_002
When repetitive nav precedes main content, provide a skip-to-content link for keyboard users.
βœ… RULES (2)
Place <a href='#main'>Skip to content</a> as first element
Set id='main' on primary container
❌ ANTI-PATTERNS (1)
Hiding skip link or placing it after nav visually only
πŸ’» CODE HINTS (1)
<a href='#main' class='skip-link'>Skip to content</a>
focus_003
When modal opens, trap focus inside dialog until dismissed.
βœ… RULES (2)
Cycle focus within modal using tab/shift+tab
Return focus to trigger on close
❌ ANTI-PATTERNS (1)
Allowing focus to escape modal to page behind
πŸ’» CODE HINTS (1)
useFocusTrap(modalRef);
focus_004
When modal closes, restore focus to element that triggered it.
βœ… RULES (2)
Track trigger element before opening modal
Call .focus() on close
❌ ANTI-PATTERNS (1)
Dropping user into top of page after modal closes
πŸ’» CODE HINTS (1)
triggerRef.current.focus();
focus_005
When building toolbars with arrow key nav, use roving tabindex to make only one element focusable at a time.
βœ… RULES (2)
Only active item has tabIndex=0
Arrow keys move focus and update tabIndex
❌ ANTI-PATTERNS (1)
Giving tabIndex=0 to all buttons, making tab jump across all
πŸ’» CODE HINTS (1)
items.forEach((el, i) => el.tabIndex = i === active ? 0 : -1);
focus_006
When auto-focusing a field on mount (e.g. login form), use programmatic .focus() after render.
βœ… RULES (2)
Use useEffect or ref callback to call .focus()
Delay until element is in DOM
❌ ANTI-PATTERNS (1)
Calling .focus() before element mounts
πŸ’» CODE HINTS (1)
useEffect(() => inputRef.current?.focus(), [])
πŸ§ͺ VALIDATION
Verify: tab order matches DOM, skip link works, focus traps in modals, restoration on close, roving tabindex in toolbars.
#171ARIA Roles Matrix6 cells18 rules12 anti6 hints
Determines which ARIA roles to apply to UI components to ensure semantic meaning, accessibility, and assistive technology support.
widget_typeinteraction_intentaccessibility_levelsemantic_equivalentkeyboard_behaviorrole_scope
ROLE_BUTTON_ACTION
When implementing a clickable element that triggers an immediate action
βœ… RULES (3)
Use role='button' on non-button elements that trigger actions
Add tabindex='0' to make focusable
Bind Enter and Space keys manually if not native button
❌ ANTI-PATTERNS (2)
Divs styled as buttons with no ARIA role
Missing keyboard support
πŸ’» CODE HINTS (1)
<div role='button' tabindex='0' onKeyDown=... />
ROLE_ALERT_LIVE_FEEDBACK
When presenting critical messages (e.g. errors, confirmations) that should be announced immediately
βœ… RULES (3)
Use role='alert' for live regions needing immediate attention
Do not require focus to read alert
Keep alert concise and visually connected
❌ ANTI-PATTERNS (2)
Using alert role for passive tips
Visually hidden alerts with no DOM insertion
πŸ’» CODE HINTS (1)
<div role='alert'>Form saved</div>
ROLE_TABLIST_NAV
When implementing tabbed navigation between views or panels
βœ… RULES (3)
Wrap tabs in role='tablist'
Assign each tab with role='tab' and panel with role='tabpanel'
Use aria-selected to indicate active tab
❌ ANTI-PATTERNS (2)
Missing role='tablist' wrapper
No aria-controls linkage between tab and panel
πŸ’» CODE HINTS (1)
<div role='tablist'><button role='tab'>...</button></div>
ROLE_DIALOG_MODAL
When presenting a modal dialog that blocks background interaction
βœ… RULES (3)
Use role='dialog' with aria-modal='true'
Trap focus inside modal while open
Provide aria-labelledby and aria-describedby
❌ ANTI-PATTERNS (2)
Missing aria-modal on modal dialogs
Leaving focusable elements behind modal
πŸ’» CODE HINTS (1)
<div role='dialog' aria-modal='true'>...</div>
ROLE_LISTBOX_SELECTION
When building a custom dropdown with selectable options
βœ… RULES (3)
Use role='listbox' and role='option' on children
Track selection with aria-selected
Support arrow key navigation
❌ ANTI-PATTERNS (2)
role='menu' used for selection lists
Omitting aria-selected
πŸ’» CODE HINTS (1)
<ul role='listbox'><li role='option'>Item</li></ul>
ROLE_PROGRESS_STATUS
When displaying ongoing progress (e.g. uploads, processing)
βœ… RULES (3)
Use role='progressbar' with aria-valuenow/aria-valuemin/aria-valuemax
Visually synchronize indicator with values
Avoid auto-announcing unless relevant
❌ ANTI-PATTERNS (2)
role='status' for visual progress bars
Missing aria-valuenow
πŸ’» CODE HINTS (1)
<div role='progressbar' aria-valuenow='40' aria-valuemin='0' aria-valuemax='100' />
πŸ§ͺ VALIDATION
Verify: each interactive component has appropriate role, required ARIA attributes present, keyboard behavior matches role spec, screen reader tests announce content correctly.
#172Screen Reader Flow Matrix6 cells18 rules12 anti6 hints
Define how to structure markup and roles to ensure predictable, accessible screen reader experiences across UI flows.
landmark_rolesheading_structurearia_labelingfocus_orderdynamic_content_announcementsemantic_grouping
LANDMARK_ROLE_DECLARATION
When structuring layout sections in a web app
βœ… RULES (3)
Use `<main>`, `<nav>`, `<header>`, `<footer>`, and `<aside>` where applicable
Supplement with `role=main` or `role=navigation` if needed
Ensure each landmark is unique per page
❌ ANTI-PATTERNS (2)
Omitting landmark roles on major layout blocks
Using duplicate `role=main` or multiple `<main>` tags
πŸ’» CODE HINTS (1)
Use semantic HTML5 tags or `role=*` attributes
NESTED_HEADING_STRUCTURE
When displaying nested UI regions like cards, dialogs, or tabs
βœ… RULES (3)
Use one `<h1>` per page, then descend hierarchically
Nest `<h2>`, `<h3>` etc. according to visual grouping
Avoid skipping levels arbitrarily
❌ ANTI-PATTERNS (2)
Using multiple `<h1>` elements
Jumping from `<h1>` to `<h4>` without structure
πŸ’» CODE HINTS (1)
Use logical heading tags, not just for style
ARIA_LABEL_AND_DESCRIBEDBY_MAPPING
When annotating components like inputs, modals, or controls
βœ… RULES (3)
Use `aria-label` for concise naming when no visible label exists
Use `aria-labelledby` to reference external label elements
Use `aria-describedby` to attach additional hints
❌ ANTI-PATTERNS (2)
Leaving inputs unlabeled
Conflicting labels from multiple ARIA attributes
πŸ’» CODE HINTS (1)
Set `aria-labelledby='label-id'` and `aria-describedby='hint-id'`
FOCUS_ORDER_MATCHES_VISUAL_FLOW
When designing multi-step UI flows with forms, modals, or widgets
βœ… RULES (3)
Place DOM elements in visual order of appearance
Avoid CSS-only repositioning that breaks tab order
Use tabindex only to fix edge cases, not control full flow
❌ ANTI-PATTERNS (2)
Reordering items visually but not in DOM
Overusing `tabindex` to hack focus order
πŸ’» CODE HINTS (1)
Use semantic HTML flow + test with keyboard only
ARIA_LIVE_REGION_FOR_UPDATES
When updating part of the UI dynamically without page reload
βœ… RULES (3)
Use `aria-live=polite` or `assertive` on containers
Update only relevant region’s content, not full layout
Avoid flooding with frequent or redundant updates
❌ ANTI-PATTERNS (2)
Relying on visual cues only for alerts
Placing `aria-live` on hidden or empty elements
πŸ’» CODE HINTS (1)
Use `<div aria-live='polite'>Status</div>` with dynamic content injection
SEMANTIC_GROUPING_VIA_LISTS_AND_ROLES
When listing items, steps, or options
βœ… RULES (3)
Use `<ul>`, `<ol>`, or `<dl>` where appropriate
Use `role=list` and `role=listitem` for custom markup
Announce total item count if helpful
❌ ANTI-PATTERNS (2)
Using `<div>`s with no roles for complex lists
Hiding grouping structure visually and semantically
πŸ’» CODE HINTS (1)
Use semantic HTML lists or ARIA roles when custom-rendering
πŸ§ͺ VALIDATION
Test screen reader behavior across flows with headings, landmarks, modals, live updates, and labels. Confirm order, announcements, and region recognition across popular screen readers.
#173UI State Indicators Matrix6 cells12 rules6 anti6 hints
Determines how UI communicates state β€” loading spinners, empty states, error states, success confirmations, and skeleton screens.
state_typeindicator_methodtimingaccessibility
uistate_001
When data is being fetched asynchronously, show centered spinner overlay to indicate progress.
βœ… RULES (2)
Use aria-busy=true on parent container
Visually center spinner in area being blocked
❌ ANTI-PATTERNS (1)
Spinners without contextual area or screen reader tags
πŸ’» CODE HINTS (1)
<div aria-busy='true'><Spinner /></div>
uistate_002
When no content is available (e.g. empty list), show friendly illustration with call-to-action (CTA) to encourage engagement.
βœ… RULES (2)
Use descriptive text and clear CTA button
Illustration should match product tone
❌ ANTI-PATTERNS (1)
Empty whitespace without explanation or CTA
πŸ’» CODE HINTS (1)
<EmptyState icon={<BoxIcon />} title='No items yet' action={<Button>Add Item</Button>} />
uistate_003
When a data fetch or user action fails, display an error message with retry option.
βœ… RULES (2)
Include error icon and clear description
Provide 'Retry' button bound to same action
❌ ANTI-PATTERNS (1)
Silent failures or cryptic error messages
πŸ’» CODE HINTS (1)
<ErrorMessage text='Failed to load' action={<Button onClick={retry}>Retry</Button>} />
uistate_004
When an operation succeeds (e.g. form submitted), show transient toast confirmation in screen corner.
βœ… RULES (2)
Use role='status' for screen readers
Auto-dismiss after 3–5 seconds
❌ ANTI-PATTERNS (1)
No feedback on successful actions
πŸ’» CODE HINTS (1)
showToast('Saved successfully', { status: 'success' })
uistate_005
When disabling controls, gray them out and attach tooltip explaining why.
βœ… RULES (2)
Set disabled and aria-disabled as needed
Tooltip should clarify disabled reason
❌ ANTI-PATTERNS (1)
Disabled buttons with no explanation
πŸ’» CODE HINTS (1)
<Tooltip label='Fill required fields first'><Button disabled>Submit</Button></Tooltip>
uistate_006
When loading large data in chunks, show progressive skeletons for each section as they load.
βœ… RULES (2)
Render skeletons only for unloaded areas
Replace progressively with data as it arrives
❌ ANTI-PATTERNS (1)
Showing single spinner for entire composite layout
πŸ’» CODE HINTS (1)
<Section>{loading ? <Skeleton /> : <Content />}</Section>
πŸ§ͺ VALIDATION
Verify: each UI state has a corresponding visible and accessible indicator, users can retry errors, success is confirmed, disabled elements are explained, and loading is scoped to relevant content.
#174Empty States Matrix6 cells18 rules12 anti6 hints
Define how to design and implement empty states across UI contexts to maintain clarity, continuity, and user engagement.
empty_state_typeuser_contextvisual_weightinteractivity_levellayout_placementmessaging_tone
INITIAL_STATE_NO_DATA_YET
When a user visits a page or feature with no prior activity
βœ… RULES (3)
Show icon or illustration with brief title
Include primary call-to-action (e.g., 'Create New')
Avoid loading indicators or error styling
❌ ANTI-PATTERNS (2)
Leaving area blank without explanation
Showing spinner indefinitely when no fetch occurs
πŸ’» CODE HINTS (1)
Use `<EmptyState type='initial' />` with CTA prop
FILTERED_EMPTY_RESULT
When search/filter yields no results
βœ… RULES (3)
Reflect applied filters or query in message
Offer reset or back button
Use lighter visual treatment than default empty
❌ ANTI-PATTERNS (2)
Suggesting error when user simply filtered too narrowly
Using same message as no-permission state
πŸ’» CODE HINTS (1)
Render `<EmptyState type='filtered' query={q} onReset={fn} />`
ACCESS_DENIED_EMPTY_STATE
When user lacks permission to view content
βœ… RULES (3)
Display lock icon or muted visual
Explain permission or role requirement
Link to request access or documentation
❌ ANTI-PATTERNS (2)
Saying 'no data' when data exists but is restricted
Offering irrelevant actions like create/edit
πŸ’» CODE HINTS (1)
Use `<EmptyState type='accessDenied' />` with link to support
ERROR_FETCH_FAILED_STATE
When backend or network error prevents data from loading
βœ… RULES (3)
Show error icon or red alert box
Include retry button and error context
Log or surface error ID when possible
❌ ANTI-PATTERNS (2)
Falling back to default 'empty state' message
Omitting retry capability
πŸ’» CODE HINTS (1)
Use `<EmptyState type='error' onRetry={fn} />` with errorId prop
SUCCESS_NO_MATCH_IN_PROGRESS_FLOW
When user completes valid step but no match or result is found
βœ… RULES (3)
Use positive/neutral tone (e.g., 'No matching records')
Avoid error visuals or language
Suggest alternate next step if applicable
❌ ANTI-PATTERNS (2)
Displaying generic failure feedback
Forgetting to acknowledge user action
πŸ’» CODE HINTS (1)
Render `<EmptyState type='successNoMatch' />` after submission
USER_DEFINED_STATE_SLOT
When developers want to inject custom visual or layout into empty state
βœ… RULES (3)
Expose `renderCustom` or `children` slot
Provide layout guardrails for size and spacing
Document expected prop signature and styles
❌ ANTI-PATTERNS (2)
Hardcoding empty visuals without escape hatch
Allowing unbounded custom elements to break layout
πŸ’» CODE HINTS (1)
Use `<EmptyState>{customRender()}</EmptyState>` or `renderCustom` prop
πŸ§ͺ VALIDATION
Trigger each empty state scenario (initial, filtered, error, access, etc.) across components. Verify messaging, actions, visuals, and customization APIs function correctly.
#175Loading States Matrix6 cells12 rules6 anti6 hints
Determines how loading states are displayed β€” skeleton screens, progress bars, optimistic UI, and perceived performance techniques.
loading_patternperceived_performanceprogress_typecancellation
load_001
When data is expected shortly (≀1s), show a skeleton screen as a visual placeholder to reduce perceived wait time.
βœ… RULES (2)
Use animated gray blocks shaped like final content
Replace skeletons with actual data once loaded
❌ ANTI-PATTERNS (1)
Leaving content blank while waiting
πŸ’» CODE HINTS (1)
<Skeleton variant='text' width='80%' height='1rem' />
load_002
When loading time is predictable or file size known, use a determinate progress bar to show exact completion percentage.
βœ… RULES (2)
Update progress value in real-time
Label progress with percentage if appropriate
❌ ANTI-PATTERNS (1)
Using spinner when duration is known
πŸ’» CODE HINTS (1)
<ProgressBar value={uploadProgress} label={`${uploadProgress}%`} />
load_003
When loading time is unknown, display an indeterminate spinner to indicate the system is working.
βœ… RULES (2)
Use circular or linear spinner for indefinite waits
Avoid spinner-only views longer than 5s
❌ ANTI-PATTERNS (1)
Leaving user with no context for long duration
πŸ’» CODE HINTS (1)
<Spinner size='md' />
load_004
When user action is likely to succeed (e.g. like button), update UI immediately before server confirmation.
βœ… RULES (2)
Revert state if request fails
Track optimistic updates for reconciliation
❌ ANTI-PATTERNS (1)
Never reconciling after failed optimistic update
πŸ’» CODE HINTS (1)
setLiked(true); api.like().catch(() => setLiked(false))
load_005
When loading multiple content sections, prioritize above-the-fold items and defer below-the-fold to reduce first-paint delay.
βœ… RULES (2)
Lazy-load below-fold components after main viewport renders
Use IntersectionObserver or scroll position triggers
❌ ANTI-PATTERNS (1)
Blocking UI on full content load
πŸ’» CODE HINTS (1)
<LazyLoad threshold={0.1}>...</LazyLoad>
load_006
When user navigates away or cancels action mid-load, abort the request and restore previous state.
βœ… RULES (2)
Use AbortController to cancel fetch
Rollback optimistic or partial state
❌ ANTI-PATTERNS (1)
Continuing fetch after component unmount
πŸ’» CODE HINTS (1)
const controller = new AbortController(); fetch(url, { signal: controller.signal }); controller.abort();
πŸ§ͺ VALIDATION
Verify: skeletons show for short waits, spinners not overused, progress bar accurate, optimistic state reversible, above-fold loads first, cancellations roll back state.
#176Error States Matrix6 cells18 rules12 anti6 hints
Determines how and where to represent error states in the UI to ensure user clarity, remediation, and visual consistency.
error_scopeuser_visibilityinteraction_timingrecovery_affordancelayout_impactseverity_level
INLINE_FIELD_ERROR
When a user inputs invalid data into a form field
βœ… RULES (3)
Render error message directly below or beside field
Use red text and icon for visibility
Update live on blur or submit
❌ ANTI-PATTERNS (2)
Displaying error in unrelated location
Overwriting placeholder with error text
πŸ’» CODE HINTS (1)
<Input error='Email is invalid' />
FORM_GLOBAL_ERROR
When the form submission fails due to server validation
βœ… RULES (3)
Place message block at top of form container
Include anchor links to each field error
Preserve field-level errors alongside
❌ ANTI-PATTERNS (2)
Only showing summary with no field context
Placing summary below fold
πŸ’» CODE HINTS (1)
<AlertBox level='error'>Please fix the errors below</AlertBox>
FULL_SCREEN_FATAL_ERROR
When the entire view cannot load or crashes
βœ… RULES (3)
Replace view with dedicated error screen
Provide explanation and reload/return CTA
Log error to telemetry backend
❌ ANTI-PATTERNS (2)
Partially rendered broken screens
Error stacked on top of existing layout
πŸ’» CODE HINTS (1)
<ErrorScreen title='Something went wrong' onRetry={...} />
FIELD_GROUP_ERROR_DECORATION
When a logical group of fields is invalid (e.g. password + confirm)
βœ… RULES (3)
Outline group box with error color
Render message below group, not per field
Anchor to first failed field in group
❌ ANTI-PATTERNS (2)
Showing same error on every field
No visual indicator around grouped logic
πŸ’» CODE HINTS (1)
<FieldGroup error='Passwords do not match'>...</FieldGroup>
PASSIVE_TOAST_ERROR
When a background action fails non-critically
βœ… RULES (3)
Use toast with timeout and dismiss option
Keep error message under 2 lines
Log failure silently in background
❌ ANTI-PATTERNS (2)
Using modal for non-blocking errors
Auto-closing toast before user sees it
πŸ’» CODE HINTS (1)
toast.error('Failed to sync, retrying...')
INLINE_ASYNC_VALIDATION_ERROR
When validating input asynchronously (e.g. username availability)
βœ… RULES (3)
Display error below field once async check completes
Use spinner while validating
Debounce requests to avoid spam
❌ ANTI-PATTERNS (2)
Blocking form until async validation completes
Showing stale async errors
πŸ’» CODE HINTS (1)
<ValidationMessage status='error' text='Username already taken' />
πŸ§ͺ VALIDATION
Verify: error visibility aligned with severity, full-screen failures logged, async errors debounce correctly, field errors anchored, and toast/errors use correct scope and tone.
#177Success States Matrix6 cells18 rules12 anti6 hints
Define how to structure and present success states across the UI to affirm user actions and guide next steps.
success_typevisual_emphasis_levelaction_followupplacement_contextdismissal_behaviormessaging_tone
INLINE_SUCCESS_CONFIRMATION
When confirming a form submission or small action inline
βœ… RULES (3)
Display success text near the triggering element
Use subtle green or check icon styling
Auto-dismiss after short duration if no next action
❌ ANTI-PATTERNS (2)
Redirecting user on minor success
Using modal for trivial feedback
πŸ’» CODE HINTS (1)
Use `<InlineSuccess message='Saved!' />` component
MODAL_SUCCESS_CONFIRMATION
When confirming completion of a major flow or task
βœ… RULES (3)
Show modal with title, icon, summary message
Include 1–2 next-step actions
Trap focus and allow keyboard dismissal
❌ ANTI-PATTERNS (2)
Closing modal automatically
Showing vague success like 'Done' with no context
πŸ’» CODE HINTS (1)
Use `<SuccessModal onNext={fn} />` after completion
TOAST_SUCCESS_NOTIFICATION
When confirming background task completion or async result
βœ… RULES (3)
Use toast in corner of screen with short message
Auto-dismiss after 3–5 seconds
Allow manual dismissal and avoid queuing too many
❌ ANTI-PATTERNS (2)
Stacking toasts indefinitely
Using toast as primary success UI for forms
πŸ’» CODE HINTS (1)
Use `toast.success('Export complete')`
EMBEDDED_SUCCESS_BANNER
When confirming configuration or setup saved on a page
βœ… RULES (3)
Render banner at top or inline with config area
Use alert-success styling with icon and close button
Keep persistent until user dismisses
❌ ANTI-PATTERNS (2)
Showing toast far from configuration context
Using red or neutral styling for success
πŸ’» CODE HINTS (1)
Use `<Banner type='success' persist />` in settings UI
STEP_SUCCESS_TRANSITION_STATE
When navigating between steps in a wizard or multi-step form
βœ… RULES (3)
Show visual check or animation briefly
Delay next step slightly to confirm success
Allow manual step advancement or skip
❌ ANTI-PATTERNS (2)
Advancing instantly without feedback
Blocking transition behind unnecessary confirmation
πŸ’» CODE HINTS (1)
Use `setTimeout(() => goToNextStep(), 500)`
SUCCESS_STATE_SLOT_CUSTOMIZATION
When allowing product teams to change visuals or content in success states
βœ… RULES (3)
Expose slot or prop for message override
Allow icon override or illustration injection
Document fallback visuals and copy rules
❌ ANTI-PATTERNS (2)
Hardcoding visuals in all success UIs
Requiring fork to change copy
πŸ’» CODE HINTS (1)
Use `<SuccessState icon={CustomIcon} message='Custom' />`
πŸ§ͺ VALIDATION
Trigger each success scenario in staging: inline, modal, toast, banner, step, and slot override. Confirm styling, dismissal, keyboard interaction, and contextual relevance.
#178Motion in UI Matrix6 cells18 rules12 anti6 hints
Define when and how to apply UI motion to enhance clarity, continuity, and feedback without harming usability or performance.
motion_typetrigger_contextduration_rangeeasing_functioninterruption_behavioraccessibility_consideration
PAGE_TRANSITION_SLIDE_FADE
When navigating between top-level pages in a single-page application
βœ… RULES (3)
Use directional slide (left/right) + fade
Limit duration to 200–400ms
Ensure motion follows navigation direction
❌ ANTI-PATTERNS (2)
Using full screen fade with no spatial hint
Running transition over 500ms
πŸ’» CODE HINTS (1)
Use `framer-motion` with `AnimatePresence` and `motion.div`
ELEMENT_ENTRANCE_FADE_IN
When displaying new content dynamically inside an existing view
βœ… RULES (3)
Use opacity fade-in over 150–250ms
Stagger entrance of sibling elements by 30–50ms
Avoid pushing layout during animation
❌ ANTI-PATTERNS (2)
Sliding elements into view that change position
Fading in over 500ms (too slow)
πŸ’» CODE HINTS (1)
Use CSS `opacity` + `transition-delay` or `framer-motion` stagger
FEEDBACK_SUCCESS_BOUNCE
When confirming a positive action like save or complete
βœ… RULES (3)
Use bounce or scale-up effect < 300ms
Play once, no looping
Anchor animation to icon or checkmark, not full modal
❌ ANTI-PATTERNS (2)
Repeating bounce effect
Animating large area for minor feedback
πŸ’» CODE HINTS (1)
Use `transform: scale()` with `ease-out-back`
LOADING_INDICATOR_SPIN
When waiting for async action like fetch or submit
βœ… RULES (3)
Use infinite linear rotation of spinner
Avoid progress bars unless real progress can be measured
Ensure contrast and visibility
❌ ANTI-PATTERNS (2)
Using spinner inside button without spacing
Faking progress with timed bars
πŸ’» CODE HINTS (1)
Use `@keyframes spin` or `animate-spin` in Tailwind
COLLAPSE_TOGGLE_SLIDE
When expanding or collapsing a section in-place
βœ… RULES (3)
Slide open vertically with `max-height` + `overflow: hidden`
Animate over 200–300ms with `ease-in-out`
Keep trigger button visible throughout
❌ ANTI-PATTERNS (2)
Fading content in/out during collapse
Jump cuts with no transition
πŸ’» CODE HINTS (1)
Use `max-height` CSS animation or `framer-motion` height variant
PREFERENCE_REDUCE_MOTION_SUPPORT
When user has OS preference to reduce animation
βœ… RULES (3)
Detect `prefers-reduced-motion` media query
Disable or shorten all non-essential animations
Provide skip animation paths where possible
❌ ANTI-PATTERNS (2)
Ignoring user system preference
Animating background or parallax regardless
πŸ’» CODE HINTS (1)
Use `@media (prefers-reduced-motion: reduce)` to override animations
πŸ§ͺ VALIDATION
Test all motion flows (page, element, feedback, toggle) with reduced motion mode on/off. Verify durations, triggers, and interruptibility. Check keyboard navigation compatibility.
#179Visual Feedback Matrix6 cells18 rules12 anti6 hints
Define how and when to apply visual feedback cues in UI elements to reinforce user actions, system state, and interactivity.
feedback_typetrigger_sourcetiming_and_durationsemantic_color_rolefeedback_scopeaccessibility_equivalence
ACTIVE_HOVER_INDICATION
When a user hovers over a clickable UI element
βœ… RULES (3)
Change background or border on hover
Use subtle motion or color shift
Avoid disrupting layout or text content
❌ ANTI-PATTERNS (2)
Overly aggressive animation on hover
No visual change on hover for buttons or links
πŸ’» CODE HINTS (1)
Use `:hover` pseudo-class or Tailwind `hover:` utilities
CLICK_PRESS_FEEDBACK
When a user clicks or taps a button
βœ… RULES (3)
Apply press-down visual (e.g., scale or shadow reduction)
Limit duration to under 150ms
Revert to normal on mouseup or after async transition
❌ ANTI-PATTERNS (2)
Delaying feedback until async completes
Only showing spinner with no input response
πŸ’» CODE HINTS (1)
Use `:active` state or `animate-press` utility class
LOADING_INDICATOR_FEEDBACK
When a user triggers an async process
βœ… RULES (3)
Show loading spinner or pulse near triggering element
Disable button or form field during async
Replace icon/text briefly if necessary
❌ ANTI-PATTERNS (2)
Starting async with no visual indication
Using full-page spinner for small action
πŸ’» CODE HINTS (1)
Use `isLoading` state with conditional spinner in button
FIELD_VALIDATION_FEEDBACK
When a user inputs invalid or incomplete data
βœ… RULES (3)
Show red border or icon on error
Display inline error message near field
Update feedback live on change where possible
❌ ANTI-PATTERNS (2)
Using only color to signal error
Showing validation only on submit without field context
πŸ’» CODE HINTS (1)
Apply `aria-invalid`, error text, and `border-red-500`
SUCCESS_STATE_CONFIRMATION
When a user completes a task or submits valid data
βœ… RULES (3)
Display green check icon or success banner
Keep feedback visible for 2–5 seconds or until dismiss
Place message near context of action
❌ ANTI-PATTERNS (2)
Using neutral styling that doesn’t affirm success
Removing feedback too quickly without notice
πŸ’» CODE HINTS (1)
Use `<SuccessBanner message='Saved' />` or similar
PASSIVE_SYSTEM_STATE_INDICATORS
When a system state changes without direct user action
βœ… RULES (3)
Use subtle label, icon, or tag to indicate status
Animate or pulse only if attention is required
Provide tooltip or detail on hover
❌ ANTI-PATTERNS (2)
Hiding passive system state entirely
Overloading with alerts for low-priority info
πŸ’» CODE HINTS (1)
Use `status-dot`, `badge`, or `tooltip` components
πŸ§ͺ VALIDATION
Trigger hover, click, load, error, success, and passive state changes in UI. Confirm visual feedback appears consistently, quickly, and accessibly for each interaction.
#180Matrix 180 β€” UI Decomposition Matrix6 cells18 rules18 anti6 hints
Define how to break down complex UI views into manageable, testable, and reusable component structures while maintaining clear boundaries and data flow.
decomposition_strategycomponent_granularitystate_distributionprop_drilling_avoidanceboundary_definitiontesting_isolation
FLAT_COMPONENT_HIERARCHY
When building a simple or medium complexity UI
βœ… RULES (3)
Group logic by feature, not by container
Avoid deeply nested presentational components
Prefer composition over containment when possible
❌ ANTI-PATTERNS (3)
Nesting for stylistic layout only
Adding wrappers for every visual block
Combining unrelated concerns
πŸ’» CODE HINTS (1)
<FeatureCard><FeatureStats /></FeatureCard>
CONTAINER_PRESENTATIONAL_SPLIT
When needing to separate logic from UI
βœ… RULES (3)
Put side-effects and state in container
Keep presentational component stateless
Pass props explicitly
❌ ANTI-PATTERNS (3)
Mixing API calls and markup in same file
Accessing context from deep visual nodes
Coupling style logic to data fetching
πŸ’» CODE HINTS (1)
<UserContainer><UserCard /></UserContainer>
STATE_LIFTING_FOR_SHARED_CONTEXT
When multiple components rely on shared state
βœ… RULES (3)
Lift state to nearest common ancestor
Pass down state and setters via props or context
Avoid deeply nested updates from children
❌ ANTI-PATTERNS (3)
Independent duplicate states
Circular state updates between peers
Tight coupling via shared module scope
πŸ’» CODE HINTS (1)
<FormProvider><Field /><Submit /></FormProvider>
PROP_DRILLING_ESCAPE_HATCH
When deeply nested components require access to global/shared data
βœ… RULES (3)
Use context providers for cross-tree data
Minimize number of context consumers
Keep context shape small and versioned
❌ ANTI-PATTERNS (3)
Passing props through 4+ levels
Overusing context for local state
Creating mega context objects
πŸ’» CODE HINTS (1)
<ThemeContext.Provider value={theme}><App /></ThemeContext.Provider>
COMPONENT_BOUNDARY_CLARITY
When splitting UI across many files or teams
βœ… RULES (3)
Define public vs internal component API
Use folders to isolate feature domains
Document props and contract assumptions
❌ ANTI-PATTERNS (3)
Exposing internals via default exports
Mixing unrelated components in shared folder
Missing prop typing or description
πŸ’» CODE HINTS (1)
export const DashboardWidget: React.FC<Props> = ...
ISOLATED_TESTABLE_UNITS
When needing confidence in UI behavior across changes
βœ… RULES (3)
Avoid hidden dependencies across components
Expose inputs/outputs clearly via props
Use shallow rendering or test harnesses
❌ ANTI-PATTERNS (3)
Testing behavior through indirect children
Mocking entire UI trees for unit tests
Making component stateful unnecessarily
πŸ’» CODE HINTS (1)
render(<Button onClick={...} />) β†’ expect(click).toFire()
πŸ§ͺ VALIDATION
Refactor real screens using this matrix. Measure test coverage, state flow clarity, and change scope containment before and after decomposition.
β–Ό πŸ–±οΈ L7 β€” Interaction 30 matrices
#181Event Propagation Matrix6 cells12 rules6 anti6 hints
Determines how events propagate through the DOM β€” capturing, bubbling, stopping propagation, and when to use each phase.
propagation_phasecontrol_methoduse_caseside_effects
evprop_001
When handling most UI events (click, input), rely on bubbling phase to allow parent containers to respond without attaching listeners to every child.
βœ… RULES (2)
Events bubble from child to parent unless stopped
Attach listeners at container level when delegation is desired
❌ ANTI-PATTERNS (1)
Attaching redundant listeners to each child for common events
πŸ’» CODE HINTS (1)
parent.addEventListener('click', e => { if (e.target.matches('.child')) ... })
evprop_002
When early interception is needed (e.g. analytics, global guards), use capturing phase by setting the capture flag to true.
βœ… RULES (2)
Set { capture: true } when adding listener
Capture runs from root down before bubbling
❌ ANTI-PATTERNS (1)
Expecting capture to override bubbling unless explicitly set
πŸ’» CODE HINTS (1)
window.addEventListener('click', handler, { capture: true })
evprop_003
When an event should not bubble beyond its current target, call stopPropagation in the handler to prevent parent response.
βœ… RULES (2)
Call event.stopPropagation() inside the handler
Only use when child must fully own the event
❌ ANTI-PATTERNS (1)
Stopping propagation unnecessarily and breaking delegation
πŸ’» CODE HINTS (1)
button.addEventListener('click', e => e.stopPropagation())
evprop_004
When multiple handlers are attached to the same element and only the first should run, call stopImmediatePropagation.
βœ… RULES (2)
Prevents other handlers on same element from firing
Useful in guarded conditional logic
❌ ANTI-PATTERNS (1)
Assuming stopPropagation also halts same-element handlers
πŸ’» CODE HINTS (1)
element.addEventListener('click', e => { e.stopImmediatePropagation(); ... })
evprop_005
When default browser behavior (e.g. form submission, link navigation) must be suppressed, call preventDefault on the event.
βœ… RULES (2)
Call event.preventDefault() before browser handles default action
Use only for user-triggered events
❌ ANTI-PATTERNS (1)
Calling preventDefault on synthetic or passive events without effect
πŸ’» CODE HINTS (1)
form.addEventListener('submit', e => { e.preventDefault(); ... })
evprop_006
When handling large lists or dynamic content, use event delegation via bubbling to manage interactions efficiently.
βœ… RULES (2)
Attach one handler to parent container
Use event.target or closest() to find clicked child
❌ ANTI-PATTERNS (1)
Binding per-element handlers in dynamic lists
πŸ’» CODE HINTS (1)
list.addEventListener('click', e => { const item = e.target.closest('.item'); if (item) ... })
πŸ§ͺ VALIDATION
Verify: bubbling/capturing phases behave as expected, stopPropagation blocks correctly, preventDefault suppresses defaults, delegation handles dynamic content.
#182Event Bubbling Matrix6 cells24 rules18 anti6 hints
To decide how and when events should propagate up the DOM or component tree, and how to intercept or delegate them effectively.
Event Origin (User vs System)DOM Depth (Shallow vs Deep)Component Type (Interactive vs Container)Propagation Intent (Bubble vs Stop)Listener Scope (Global vs Local)Modifier Presence (Shift/Ctrl/Alt)Event Type (Click, Focus, Submit, etc.)
SHALLOW_CLICK_CONTAINER_COMPONENT
When a click occurs inside a shallow container component
βœ… RULES (5)
Attach a single event listener to the container
Use event.target to inspect the originating element
Filter by class or data-attribute inside handler
Avoid attaching multiple listeners to children
Ensure tabindex or role is correctly set if needed
❌ ANTI-PATTERNS (3)
Attaching listeners to every child element
Blindly trusting event.target without verification
Using innerHTML for delegation
πŸ’» CODE HINTS (1)
container.addEventListener('click', (e) => { if (e.target.matches('.item')) ... })
DEEP_FOCUS_STOP_ON_CHILD
When a deeply nested input receives focus and parent should not react
βœ… RULES (3)
Use event.stopPropagation() on focus handler in child
Ensure useCapture is false on parent listeners
Test interactions with both tab and mouse focus
❌ ANTI-PATTERNS (3)
Not stopping propagation and expecting isolation
Handling both capture and bubble on same element
Overriding native focus behavior globally
πŸ’» CODE HINTS (1)
input.addEventListener('focus', e => e.stopPropagation())
KEYBOARD_SHORTCUTS_GLOBAL_CAPTURE
When keyboard shortcuts must work across the app
βœ… RULES (4)
Attach keydown listener on document during capture phase
Check for modifier keys explicitly (Ctrl/Meta)
Prevent default only when shortcut matches
Avoid interference with input/textarea fields
❌ ANTI-PATTERNS (3)
Listening on window instead of document
Blocking default on all keydown events
Assuming keyCode is consistent across browsers
πŸ’» CODE HINTS (1)
document.addEventListener('keydown', handler, true)
FORM_SUBMIT_BUBBLE_TO_VALIDATE
When a form submit should be centrally validated
βœ… RULES (4)
Use event delegation from form parent to handle submit
Validate event.target as form element
Prevent default only after validation fails
Allow native HTML5 validation unless overridden
❌ ANTI-PATTERNS (3)
Cancelling submit unconditionally
Adding submit handlers to each form individually
Not checking event.target type
πŸ’» CODE HINTS (1)
container.addEventListener('submit', e => { if (!validate(e.target)) e.preventDefault() })
MODAL_ESC_KEY_ISOLATION
When pressing Escape inside a modal should close it but not affect background
βœ… RULES (4)
Add keydown listener to modal element
Use stopPropagation for ESC inside modal
Ensure modal has focusable trap or aria-modal
Fallback to document listener if modal is unfocused
❌ ANTI-PATTERNS (3)
ESC listener only on document with no scope check
Modal closes even if another overlay is active
Modal doesn’t trap focus
πŸ’» CODE HINTS (1)
modal.addEventListener('keydown', e => { if (e.key === 'Escape') { e.stopPropagation(); closeModal(); } })
DRAG_DROP_INTERACTION_BUBBLE_CONTROL
When a drag operation triggers drop zones across components
βœ… RULES (4)
Allow dragenter/dragleave to bubble up
Use data-transfer type to determine target role
Stop propagation if drop zone has exclusive handling
Use preventDefault on dragover to allow drop
❌ ANTI-PATTERNS (3)
Stopping propagation on all drag events by default
Allowing every drop zone to activate simultaneously
Not checking drop zone eligibility
πŸ’» CODE HINTS (1)
dropZone.addEventListener('dragover', e => e.preventDefault())
πŸ§ͺ VALIDATION
Use event logs and manual interaction testing (DevTools) to verify propagation path, check handler scope, and confirm that bubbling/stopping works as defined per case. Use unit tests to simulate event propagation through nested DOM trees.
#183Matrix 183 β€” Event Capturing Matrix6 cells18 rules18 anti6 hints
To determine when and how to use event capturing instead of bubbling to intercept UI events at an earlier phase.
Capture Target Level (Document, Container, Leaf)Event Type (Click, Focus, Wheel, etc.)Priority Context (Security, UX, Accessibility)Component Nesting DepthIntent to Override Bubble PhasePerformance Sensitivity
SECURITY_PREVENT_CLICKJACKING
When protecting UI from malicious iframe overlays
βœ… RULES (3)
Use capturing listener on top container
Validate pointer coordinates against viewport
Cancel suspicious clicks during capture phase
❌ ANTI-PATTERNS (3)
Only relying on bubbling to block clicks
Missing coordinate validation
Using inline JS for protection
πŸ’» CODE HINTS (1)
document.addEventListener('click', protectClick, true)
TOOLTIP_DELAYED_CAPTURE_CANCEL
When hovering over nested tooltips and needing early cancel
βœ… RULES (3)
Use capture phase to detect mouseenter early
Cancel or delay nested tooltip activations
Ensure tooltips respect parent visibility constraints
❌ ANTI-PATTERNS (3)
Using only bubble listeners for hover chaining
Allowing simultaneous tooltip rendering
Assuming stopPropagation in bubble affects siblings
πŸ’» CODE HINTS (1)
tooltipEl.addEventListener('mouseenter', onEnter, true)
SCROLL_LOCK_CAPTURE_MODE
When locking scroll in modals or overlays
βœ… RULES (3)
Add wheel/touchstart listener on capture phase
Prevent scroll when overlay is open
Allow exception for internal scrollable regions
❌ ANTI-PATTERNS (3)
Adding listeners in bubble phase only
Blocking all scroll unconditionally
Ignoring nested scroll targets
πŸ’» CODE HINTS (1)
overlay.addEventListener('wheel', lockScroll, true)
ACCESSIBILITY_GLOBAL_FOCUS_TRACKING
When tracking focus transitions globally
βœ… RULES (3)
Use focus/blur listeners in capture phase
Track last active element and new target
Integrate with ARIA live regions if needed
❌ ANTI-PATTERNS (3)
Relying on bubbling which misses blur phase
Using setTimeout for focus diffing
Skipping integration with assistive tools
πŸ’» CODE HINTS (1)
document.addEventListener('focus', handleFocus, true)
MULTI_LAYER_DRAG_INTERCEPT
When dragging across nested droppable zones
βœ… RULES (3)
Listen to drag events in capture mode
Detect entering/leaving zones at correct depth
Apply styling or cancel default early
❌ ANTI-PATTERNS (3)
Using only bubble handlers for dragover
Relying on target instead of relatedTarget
Not distinguishing zone levels
πŸ’» CODE HINTS (1)
zone.addEventListener('dragover', onDragOver, true)
PERFORMANCE_CRITICAL_CAPTURE_PATHS
When performance-sensitive UI needs early discard of noisy events
βœ… RULES (3)
Add minimal capture listeners for noisy events
Throttle or debounce high-frequency triggers
Avoid layout thrashing during capture phase
❌ ANTI-PATTERNS (3)
Debouncing only in bubble phase
Handling all events regardless of context
Triggering reflows during capture
πŸ’» CODE HINTS (1)
document.addEventListener('mousemove', captureAndThrottle, true)
πŸ§ͺ VALIDATION
Use event inspector tools to verify listener capture order. Validate behavior in nested components and simulate edge cases (e.g. drag-overlapping zones, modal scroll leaks).
#184Default Behavior Matrix6 cells18 rules12 anti6 hints
Define and control default interaction behaviors to ensure predictability, accessibility, and alignment across UI events.
event_typeelement_contextpreventable_defaultuser_override_capabilityplatform_consistencyaccessibility_consideration
FORM_SUBMIT_RELOAD_BLOCK
When user submits a form via `<form>` element in a SPA
βœ… RULES (3)
Call `event.preventDefault()` in form handler
Handle submission asynchronously
Disable submit button during async to prevent double submission
❌ ANTI-PATTERNS (2)
Letting default reload happen in SPA
Not disabling button during network request
πŸ’» CODE HINTS (1)
`<form onSubmit={e => { e.preventDefault(); handleSubmit(); }}`
LINK_NAVIGATION_OVERRIDE
When a `<a href>` link is used to trigger client-side routing
βœ… RULES (3)
Intercept click event on anchor
Use router navigation method (e.g., `navigate('/home')`)
Maintain focus ring and keyboard accessibility
❌ ANTI-PATTERNS (2)
Allowing native reload on client navigation
Using `div` or `span` instead of semantic link
πŸ’» CODE HINTS (1)
Use `<Link to='/about' />` from routing library
ESCAPE_KEY_DEFAULT_DISMISSAL
When user presses Escape key in a modal or dropdown
βœ… RULES (3)
Bind keydown handler to Escape
Call `preventDefault()` only if modal is open
Return focus to trigger element
❌ ANTI-PATTERNS (2)
Leaving modal open after Escape
Not restoring focus to opener
πŸ’» CODE HINTS (1)
`onKeyDown={e => e.key==='Escape' && closeModal()}`
SCROLL_LOCK_ON_OVERLAY
When displaying modal, drawer, or popover overlay
βœ… RULES (3)
Apply `overflow: hidden` to body on open
Remove scroll lock on close
Allow scroll within overlay if content overflows
❌ ANTI-PATTERNS (2)
Allowing body to scroll under modal
Blocking scroll in modal content itself
πŸ’» CODE HINTS (1)
Use `document.body.style.overflow = 'hidden'` on open
FOCUS_PREVENT_SCROLL_JUMP
When programmatically focusing an element inside scrollable container
βœ… RULES (3)
Use `preventScroll: true` in focus options
Ensure container scroll is manually managed
Avoid auto-scroll on re-render
❌ ANTI-PATTERNS (2)
Calling `element.focus()` with scroll jump
Letting DOM updates cause layout shift
πŸ’» CODE HINTS (1)
`element.focus({ preventScroll: true })`
TEXT_SELECTION_ALLOWANCE_IN_INPUTS
When user interacts with input or textarea
βœ… RULES (3)
Avoid intercepting mouseup or selection events
Do not override `user-select` styles in input areas
Preserve browser-native shortcuts (e.g., Ctrl+A, Cmd+C)
❌ ANTI-PATTERNS (2)
Blocking text selection via `user-select: none`
Hijacking selection for analytics or styling
πŸ’» CODE HINTS (1)
Ensure input areas do not have interfering listeners or CSS
πŸ§ͺ VALIDATION
Test user-triggered defaults (form, link, modal, focus) with keyboard, mouse, and screen reader. Confirm appropriate use of `preventDefault`, fallback behavior, and accessibility support.
#185Matrix 185 β€” Prevent Default Matrix6 cells18 rules18 anti6 hints
To determine when and how to prevent default browser behaviors in order to gain precise control over user interactions.
Event Type (submit, keydown, wheel, etc.)Interaction Context (form, link, scroll, etc.)User Intent ClarityBrowser Default ImpactPlatform Consistency NeedFallback Availability
FORM_SUBMIT_VALIDATION_GUARD
When validating form fields before allowing submission
βœ… RULES (3)
Use preventDefault inside submit handler
Run synchronous validation first
Allow submit only after all checks pass
❌ ANTI-PATTERNS (3)
Letting browser submit before validation
Using return false in HTML handlers
Triggering validation on unrelated events
πŸ’» CODE HINTS (1)
form.addEventListener('submit', e => { if (!isValid()) e.preventDefault(); })
LINK_CLICK_ROUTING_INTERCEPT
When hijacking anchor links for SPA routing
βœ… RULES (3)
Call preventDefault for internal links
Update browser history manually
Respect modifier keys (Ctrl, Cmd) for native open-in-new-tab
❌ ANTI-PATTERNS (3)
Preventing all clicks including external links
Hijacking modified-click behavior
Delaying route updates unnecessarily
πŸ’» CODE HINTS (1)
anchor.addEventListener('click', e => { if (isInternal(e)) { e.preventDefault(); routeTo(...); } })
WHEEL_SCROLL_CONTROL
When overriding scroll behavior for custom UI
βœ… RULES (3)
Add wheel listener and call preventDefault
Throttle or debounce wheel delta handling
Respect user settings for reduced motion
❌ ANTI-PATTERNS (3)
Blocking scroll unconditionally on body
Handling scroll in bubble phase only
Ignoring touch equivalents
πŸ’» CODE HINTS (1)
canvas.addEventListener('wheel', e => { e.preventDefault(); handleZoom(e); }, { passive: false })
ESCAPE_KEY_MODAL_BEHAVIOR
When closing modal or dialog with Escape
βœ… RULES (3)
Check e.key === 'Escape'
Call preventDefault and stopPropagation
Only act if modal is active
❌ ANTI-PATTERNS (3)
Applying to all ESC keys globally
Not checking modal state
Using deprecated keyCode checks
πŸ’» CODE HINTS (1)
document.addEventListener('keydown', e => { if (e.key === 'Escape') { e.preventDefault(); closeModal(); } })
TOUCH_GESTURE_OVERRIDES
When capturing touch gestures like swipe or pinch
βœ… RULES (3)
Add touchstart/touchmove listeners with passive: false
Call preventDefault if gesture matches custom handler
Detect platform-specific quirks (iOS zoom, etc.)
❌ ANTI-PATTERNS (3)
Using passive: true which disables preventDefault
Blocking all touch without gesture detection
Failing to test on multiple platforms
πŸ’» CODE HINTS (1)
el.addEventListener('touchmove', e => { if (isSwipe(e)) e.preventDefault(); }, { passive: false })
KEYBOARD_SHORTCUT_PREVENT_NATIVE
When defining keyboard shortcuts that conflict with browser defaults
βœ… RULES (3)
Detect specific shortcut (e.g. Ctrl+S)
Call preventDefault and run custom action
Avoid blocking unrelated key combos
❌ ANTI-PATTERNS (3)
Blocking all keydown without filters
Overriding system shortcuts
Failing to support assistive tech
πŸ’» CODE HINTS (1)
window.addEventListener('keydown', e => { if (e.ctrlKey && e.key === 's') { e.preventDefault(); saveDoc(); } })
πŸ§ͺ VALIDATION
Use browser devtools to inspect default action suppression. Simulate each event and confirm no unintended side effects across platforms.
#186Event Delegation Matrix6 cells12 rules6 anti6 hints
Determines how event delegation is used to handle events efficiently β€” attaching one listener to a parent instead of many to children.
delegation_scopeevent_typetarget_matchingperformance_impact
evdel_001
When handling many child click events, attach a single click listener to the parent and check target inside handler.
βœ… RULES (2)
Attach one click listener to container element
Use event.target to find clicked child
❌ ANTI-PATTERNS (1)
Adding individual click listeners to each child element
πŸ’» CODE HINTS (1)
parent.addEventListener('click', e => { if (e.target.matches('.btn')) ... })
evdel_002
When delegating events on dynamic elements, use data-attributes for precise target identification.
βœ… RULES (2)
Use e.target.closest('[data-action]') to match handler
Store action name in data-action attribute
❌ ANTI-PATTERNS (1)
Hardcoding tag names or IDs in selector
πŸ’» CODE HINTS (1)
if (e.target.closest('[data-action=remove]')) { removeItem(); }
evdel_003
When rendering dynamic elements after page load, ensure parent is listening and delegation works for new children.
βœ… RULES (2)
Bind event once to parent container
New child nodes inherit event context via bubbling
❌ ANTI-PATTERNS (1)
Rebinding listeners every time list changes
πŸ’» CODE HINTS (1)
container.addEventListener('click', e => { if (e.target.matches('.item')) ... })
evdel_004
In delegated handlers, use event.target for clicked element and event.currentTarget for bound element.
βœ… RULES (2)
event.target is the actual clicked node
event.currentTarget is the parent with listener
❌ ANTI-PATTERNS (1)
Confusing target and currentTarget in logic
πŸ’» CODE HINTS (1)
console.log(e.target, e.currentTarget)
evdel_005
When handling delegated events, selectively stop propagation if needed to prevent parent handlers from executing.
βœ… RULES (2)
Use e.stopPropagation() only when necessary
Log propagation behavior during debugging
❌ ANTI-PATTERNS (1)
Blindly calling stopPropagation on all handlers
πŸ’» CODE HINTS (1)
e.stopPropagation();
evdel_006
When dealing with many similar elements (100+), use delegation to reduce memory usage and improve performance.
βœ… RULES (2)
Attach one listener to parent instead of many to children
Benchmark both methods if performance is critical
❌ ANTI-PATTERNS (1)
Binding 100+ individual listeners
πŸ’» CODE HINTS (1)
document.querySelector('#list').addEventListener('click', handler);
πŸ§ͺ VALIDATION
Verify: delegation scope matches structure, event targets resolved correctly, dynamically added elements are handled, stopPropagation used selectively, and memory/perf profiles show improvement over direct binding.
#187Matrix 187 β€” Input Events Matrix6 cells18 rules18 anti6 hints
To define consistent handling of input-related events across devices and input types, ensuring reliable user interaction tracking.
input_source_typeevent_normalization_strategycross_platform_handlingaccessibility_mappingevent_routing_scopeinput_buffering_strategy
KEYBOARD_KEYDOWN_LIVE_UPDATE
When capturing key presses to update UI instantly
βœ… RULES (3)
Use keydown to detect key intent
Avoid heavy logic in keydown to prevent lag
Throttle updates for high-speed typing
❌ ANTI-PATTERNS (3)
Using input when raw key is needed
Updating full layout on every key
Blocking default key behavior
πŸ’» CODE HINTS (1)
el.addEventListener('keydown', e => handleKey(e.key))
TEXT_INPUT_FIELD_VALIDATION
When validating user input in text fields
βœ… RULES (3)
Use input event for live content tracking
Debounce validation logic
Handle edge cases for IME composition
❌ ANTI-PATTERNS (3)
Using change event for real-time feedback
Firing validation synchronously
Ignoring IME input lifecycle
πŸ’» CODE HINTS (1)
inputEl.addEventListener('input', debounce(validate))
TEXTAREA_AUTOSIZE_REACTIVITY
When autosizing a textarea as user types
βœ… RULES (3)
Listen to input event on textarea
Measure scrollHeight and update style
Avoid layout thrash via requestAnimationFrame
❌ ANTI-PATTERNS (3)
Using keyup which lags input
Setting height on every input without diff
Triggering reflow in handler loop
πŸ’» CODE HINTS (1)
textarea.addEventListener('input', resizeOnInput)
CHANGE_EVENT_FOR_FINALIZED_INPUT
When reacting to committed field values only
βœ… RULES (3)
Use change event for blur/final commit
Avoid updating state on every keystroke
Ensure validation runs after change
❌ ANTI-PATTERNS (3)
Binding change and input with same logic
Using change for real-time display
Ignoring blur as a trigger
πŸ’» CODE HINTS (1)
el.addEventListener('change', onChange)
CONTENTEDITABLE_INPUT_TRACKING
When tracking user changes in rich text editors
βœ… RULES (3)
Use input for contentEditable changes
Normalize browser differences
Handle undo/redo stack separately
❌ ANTI-PATTERNS (3)
Using key events only for mutation detection
Assuming input.value exists
Letting innerHTML overwrite blindly
πŸ’» CODE HINTS (1)
editable.addEventListener('input', trackRichContent)
IME_COMPOSITION_EVENT_HANDLING
When supporting East Asian or complex script input
βœ… RULES (3)
Listen to compositionstart/update/end
Block validation until compositionend
Merge with input/change pipeline safely
❌ ANTI-PATTERNS (3)
Running validation during composition
Ignoring composition events
Treating IME as keydown
πŸ’» CODE HINTS (1)
el.addEventListener('compositionend', finalizeComposition)
πŸ§ͺ VALIDATION
Simulate keyboard, IME, and touch input across fields. Use browser devtools to trace event order and test live feedback vs. committed state behavior.
#188Matrix 188 β€” Pointer Events Matrix6 cells18 rules18 anti6 hints
To define reliable usage of pointer events across input types, ensuring consistent behavior for hover, press, drag, and multitouch scenarios.
Pointer Type (mouse, pen, touch)Event Phase (start, move, end)Target Stability (static vs dynamic elements)Gesture Intent (tap, drag, swipe, press)Fallbacks for Non-Pointer BrowsersEvent Combination Safety
TAP_START_FEEDBACK_PATTERN
When user initiates tap on interactive element
βœ… RULES (3)
Use pointerdown for universal tap start
Apply visual press state immediately
Avoid delay for touch events
❌ ANTI-PATTERNS (3)
Using click for first visual response
Delaying feedback until pointerup
Relying on touchstart and mousedown separately
πŸ’» CODE HINTS (1)
el.addEventListener('pointerdown', highlightButton)
DRAG_MOVE_ACCURATE_TRACKING
When tracking user drag gesture across screen
βœ… RULES (3)
Use pointermove for unified drag motion
Track pointerId for multi-touch
Throttle updates for high-frequency movement
❌ ANTI-PATTERNS (3)
Using mousemove/touchmove separately
Forgetting to check pointerId
Triggering layout shifts on every move
πŸ’» CODE HINTS (1)
el.addEventListener('pointermove', trackDrag)
RELEASE_EVENT_CLEANUP
When gesture or press ends and cleanup is needed
βœ… RULES (3)
Use pointerup to detect gesture end
Remove visual press states or ghost highlights
Detach temporary event handlers if any
❌ ANTI-PATTERNS (3)
Missing cleanup on cancel
Using only click for gesture end
Leaving visual feedback active
πŸ’» CODE HINTS (1)
el.addEventListener('pointerup', endGesture)
POINTER_CANCEL_RESILIENCE
When gesture is aborted by browser or system
βœ… RULES (3)
Listen to pointercancel for robustness
Reset interaction state and UI
Log cancel events for diagnostics if needed
❌ ANTI-PATTERNS (3)
Ignoring pointercancel
Letting aborted gestures hang
Not cleaning up side effects
πŸ’» CODE HINTS (1)
el.addEventListener('pointercancel', resetUI)
MULTI_TOUCH_GESTURE_SUPPORT
When handling more than one finger on screen
βœ… RULES (3)
Track multiple pointerIds independently
Calculate vector between touch points
Respect gesture start/end per pointerId
❌ ANTI-PATTERNS (3)
Assuming single pointer at a time
Overwriting data between touches
Hardcoding logic to mouse only
πŸ’» CODE HINTS (1)
store[pointerId] = { x, y }
FALLBACK_FOR_UNSUPPORTED_DEVICES
When user agent doesn't support pointer events
βœ… RULES (3)
Detect pointer event support before use
Fallback to mouse/touch events as needed
Wrap handlers to unify APIs
❌ ANTI-PATTERNS (3)
Only supporting pointer events blindly
Duplicating full logic paths
Missing event abstraction layer
πŸ’» CODE HINTS (1)
if (!window.PointerEvent) { el.addEventListener('touchstart', legacyTap) }
πŸ§ͺ VALIDATION
Simulate pointer, mouse, and touch interactions. Verify consistent behavior, responsive visual states, and proper gesture termination across input types.
#189Keyboard Events Matrix6 cells12 rules6 anti6 hints
Determines how keyboard events are handled β€” shortcuts, key combinations, focus-aware handlers, and accessibility compliance.
event_typemodifier_keysscopeaccessibility
key_001
When implementing keyboard shortcuts (e.g. Ctrl+S), use keydown event to catch action before default browser behavior.
βœ… RULES (2)
Bind shortcut to keydown, not keyup
Prevent default browser action if applicable
❌ ANTI-PATTERNS (1)
Using keyup β†’ action triggers after browser default (e.g. save dialog)
πŸ’» CODE HINTS (1)
window.addEventListener('keydown', e => { if (e.ctrlKey && e.key === 's') { e.preventDefault(); save(); } })
key_002
When defining cross-platform shortcuts (e.g. Ctrl+K on Windows, Cmd+K on Mac), detect modifier per OS and bind accordingly.
βœ… RULES (2)
Use navigator.platform or e.metaKey to detect platform
Normalize keybinding behavior across OS
❌ ANTI-PATTERNS (1)
Hardcoding Ctrl for Mac users β†’ Cmd+K fails
πŸ’» CODE HINTS (1)
if (e.metaKey || e.ctrlKey) { /* handle K */ }
key_003
When binding global shortcuts, restrict execution to non-input elements to avoid interfering with typing.
βœ… RULES (2)
Check e.target.tagName !== 'INPUT' before executing shortcut
Allow opt-out for focused textareas and inputs
❌ ANTI-PATTERNS (1)
Triggering global shortcuts while typing in input fields
πŸ’» CODE HINTS (1)
if (!['INPUT','TEXTAREA'].includes(e.target.tagName)) { handleGlobalShortcut() }
key_004
When modal or dropdown is open, bind Escape key to close the component and return focus to trigger element.
βœ… RULES (2)
Focus should return to opener after dismissal
Support Esc key for all dismissible overlays
❌ ANTI-PATTERNS (1)
Overlay remains open or focus lost after Esc
πŸ’» CODE HINTS (1)
if (e.key === 'Escape') { closeModal(); trigger.focus(); }
key_005
When user presses Enter inside a form, trigger submission unless form element explicitly prevents it.
βœ… RULES (2)
Submit form only if valid and no preventDefault active
Highlight invalid fields on submit attempt
❌ ANTI-PATTERNS (1)
Silent failure on Enter press due to missing handler
πŸ’» CODE HINTS (1)
form.addEventListener('submit', fn); input.addEventListener('keydown', e => { if (e.key === 'Enter') form.submit() })
key_006
When navigating menus, lists, or dropdowns, bind arrow keys (↑ ↓) to move focus through items and maintain active index.
βœ… RULES (2)
Track focusedIndex and wrap on boundaries
Use e.preventDefault() to override default scroll
❌ ANTI-PATTERNS (1)
Allowing browser scroll or tab order to handle list navigation
πŸ’» CODE HINTS (1)
if (e.key==='ArrowDown') focusNext(); if (e.key==='ArrowUp') focusPrev();
πŸ§ͺ VALIDATION
Verify: keydown used for shortcuts, Ctrl/Cmd modifiers handled cross-platform, global handlers skip input fields, Escape dismisses overlays, Enter submits forms, arrows navigate focus.
#190Matrix 190 β€” Touch Events Matrix6 cells18 rules18 anti6 hints
To define best practices for handling touch events on mobile and hybrid devices, balancing responsiveness, gesture fidelity, and cross-platform consistency.
Touch Event Type (start, move, end, cancel)Target Area StabilityScroll vs Gesture IntentionTouch Precision (single vs multi-touch)PreventDefault UsageCross-Platform Quirks
TOUCH_START_INITIAL_CAPTURE
When a touch begins on a tappable element
βœ… RULES (3)
Use touchstart to mark gesture beginning
Capture position and time of first contact
Avoid triggering on passive listeners if preventDefault is needed
❌ ANTI-PATTERNS (3)
Ignoring passive listener restrictions
Delaying gesture start tracking
Treating all touches as click immediately
πŸ’» CODE HINTS (1)
el.addEventListener('touchstart', onTouchStart, { passive: false })
TOUCH_MOVE_SCROLL_OR_GESTURE
When finger moves after initial contact
βœ… RULES (3)
Track delta from touchstart point
Determine threshold for gesture vs scroll
PreventDefault only if confident about intent
❌ ANTI-PATTERNS (3)
Preventing all move events by default
Ignoring delta direction
Allowing jitter to cancel gesture
πŸ’» CODE HINTS (1)
el.addEventListener('touchmove', detectScrollIntent, { passive: false })
TOUCH_END_ACTION_TRIGGER
When touch completes and action is needed
βœ… RULES (3)
Use touchend to confirm gesture end
Validate gesture path and time before acting
Ignore if touch was canceled or moved outside bounds
❌ ANTI-PATTERNS (3)
Firing action on touchstart
Ignoring movement during touch
Using click fallback unnecessarily
πŸ’» CODE HINTS (1)
el.addEventListener('touchend', onTouchEnd)
TOUCH_CANCEL_RESILIENCE
When system interrupts touch (e.g., phone call, popup)
βœ… RULES (3)
Listen to touchcancel for safety
Clear gesture state and visual feedback
Log cancel if useful for UX telemetry
❌ ANTI-PATTERNS (3)
Assuming all touches end cleanly
Letting gesture logic persist after cancel
Not detaching temporary handlers
πŸ’» CODE HINTS (1)
el.addEventListener('touchcancel', resetTouchState)
MULTI_TOUCH_PINCH_ZOOM
When recognizing pinch gestures on touch screens
βœ… RULES (3)
Detect two simultaneous touch points
Measure distance delta between points
Throttle update rate for smooth scale
❌ ANTI-PATTERNS (3)
Treating any two touches as pinch
Failing to reset after fingers lifted
Forgetting gesture start conditions
πŸ’» CODE HINTS (1)
track[touch.identifier] = { x, y }
TOUCH_TO_MOUSE_FALLBACK_COMPAT
When supporting browsers that fire synthetic mouse events
βœ… RULES (3)
Detect synthetic mouse events after touch
Suppress duplicate click if touch already handled
Test on real devices with known quirks
❌ ANTI-PATTERNS (3)
Letting both touch and mouse handlers fire
Not distinguishing real vs synthetic events
Assuming simulator matches real device
πŸ’» CODE HINTS (1)
if (e.sourceCapabilities && e.sourceCapabilities.firesTouchEvents) return;
πŸ§ͺ VALIDATION
Use mobile device simulators and real touch hardware. Trace full touch lifecycle and verify action timing, gesture fidelity, and cleanup on cancel.
#191Matrix 191 β€” Gesture Recognition Matrix6 cells18 rules18 anti6 hints
To standardize gesture recognition logic across input types and devices, ensuring reliable mapping from motion to intent.
Gesture Type (swipe, pinch, press, rotate)Input Source (touch, pen, pointer)Minimum Movement ThresholdTime-Based Recognition WindowMulti-Point CoordinationDisambiguation Rules
SWIPE_HORIZONTAL_RECOGNITION
When detecting left/right swipe gestures
βœ… RULES (3)
Track touchstart and touchend delta on X axis
Set minimum distance (e.g., 30px) to count as swipe
Ignore if Y delta exceeds X by ratio > 0.5
❌ ANTI-PATTERNS (3)
Triggering swipe on every small flick
Not canceling vertical scroll vs swipe
Missing directional threshold
πŸ’» CODE HINTS (1)
if (Math.abs(deltaX) > 30 && Math.abs(deltaY / deltaX) < 0.5) { ... }
PINCH_ZOOM_DISTANCE_VECTOR
When user places two fingers and moves them apart or closer
βœ… RULES (3)
Track initial two touch points and vector length
Compare to current distance continuously
Apply zoom factor proportional to change
❌ ANTI-PATTERNS (3)
Using scale value without debounce
Allowing jitter to affect zoom
Assuming one-touch is enough to zoom
πŸ’» CODE HINTS (1)
let scale = newDist / initialDist
LONG_PRESS_TRIGGER_INTENT
When holding finger down on element for >500ms
βœ… RULES (3)
Start timer on touchstart
Clear timer on touchend or move
Trigger action only if duration exceeded
❌ ANTI-PATTERNS (3)
Starting timer too late
Not clearing on move
Reacting too early under 300ms
πŸ’» CODE HINTS (1)
setTimeout(triggerAction, 500)
ROTATE_TWIST_GESTURE_TRACKING
When user performs twist motion with two fingers
βœ… RULES (3)
Calculate angle between initial and current finger vectors
Apply rotation only if movement exceeds angular threshold
Throttle updates to avoid overprocessing
❌ ANTI-PATTERNS (3)
Using linear delta instead of angle
Not accounting for clockwise vs counter
Rotating on small jittery changes
πŸ’» CODE HINTS (1)
angle = Math.atan2(dy, dx)
MULTI_TOUCH_COHERENCE_ENFORCEMENT
When multiple fingers interact with the same element
βœ… RULES (3)
Track each touch ID separately
Verify all points start on same target
Cancel gesture if mismatch occurs
❌ ANTI-PATTERNS (3)
Merging touch identifiers prematurely
Assuming all touches target same node
Ignoring lifted or lost touch points
πŸ’» CODE HINTS (1)
if (touch1.target !== touch2.target) cancelGesture()
GESTURE_END_RECOVERY_AND_RESET
When gesture ends or is aborted
βœ… RULES (3)
Clear gesture tracking variables
Cancel any timers or animations
Emit log or metrics if needed
❌ ANTI-PATTERNS (3)
Leaving stale state between gestures
Triggering next gesture too early
Overwriting shared memory prematurely
πŸ’» CODE HINTS (1)
touchState = {}
πŸ§ͺ VALIDATION
Test gestures on multi-input devices. Use visual logs or overlays to show thresholds and trigger points. Verify cancel and reset logic behaves predictably.
#192Drag and Drop Matrix6 cells12 rules6 anti7 hints
Determines how drag and drop interactions are implemented β€” drag handles, drop zones, reorder logic, and accessibility alternatives.
drag_methoddrop_validationreorder_logicaccessibility
dragdrop_001
When implementing simple drag and drop using the native HTML5 API, allow all draggable items to be dropped unless otherwise specified.
βœ… RULES (2)
Set draggable=true on source
Use ondrop + ondragover to accept drop
❌ ANTI-PATTERNS (1)
Not calling preventDefault in ondragover β†’ drop ignored
πŸ’» CODE HINTS (2)
<div draggable='true'>Item</div>
e.preventDefault(); dropZone.append(dragged)
dragdrop_002
When implementing drag via pointer events, validate drop targets based on item type (e.g. only allow images into gallery).
βœ… RULES (2)
Set data-type attribute on dragged item
Drop target must verify match before accepting
❌ ANTI-PATTERNS (1)
Dropping all items into all zones regardless of type
πŸ’» CODE HINTS (1)
if (e.target.dataset.accepts !== dragged.dataset.type) return
dragdrop_003
When providing a drag handle in UI, use a grab icon (≑) and make only that element draggable, not the whole item.
βœ… RULES (2)
Place grab icon in predictable position (e.g. left edge)
Set draggable=true only on handle
❌ ANTI-PATTERNS (1)
Making entire row draggable causes accidental drags
πŸ’» CODE HINTS (1)
<div class='handle' draggable='true'>≑</div>
dragdrop_004
When validating drop zones, assign class based on accepted item type and style accordingly.
βœ… RULES (2)
Use class names to indicate accepted type visually
Reject non-matching drops
❌ ANTI-PATTERNS (1)
No visual indication of what can be dropped
πŸ’» CODE HINTS (1)
<div class='dropzone image-only'>
dragdrop_005
When reordering list items via drag, splice array at old index and insert at new, updating DOM order accordingly.
βœ… RULES (2)
Track fromIndex and toIndex
Trigger UI re-render after reorder
❌ ANTI-PATTERNS (1)
Reordering visually without updating underlying array
πŸ’» CODE HINTS (1)
const [item] = list.splice(from, 1); list.splice(to, 0, item)
dragdrop_006
When supporting keyboard-only users, allow list reordering via up/down arrows and space to grab/drop.
βœ… RULES (2)
Use aria-grabbed and aria-dropeffect
Move focus with arrow keys, toggle drag with space
❌ ANTI-PATTERNS (1)
No drag support for screen reader or keyboard users
πŸ’» CODE HINTS (1)
if (e.key===' ' && !dragging) startDrag(); else if (e.key==='ArrowDown') moveFocusDown()
πŸ§ͺ VALIDATION
Verify: drag uses correct method, drop zones filter properly, handles are constrained, reorder logic syncs state and DOM, and keyboard alternatives work with ARIA semantics.
#193Matrix 193 β€” Hover Intent Matrix6 cells18 rules18 anti6 hints
To determine when and how to trigger hover-based UI affordances by inferring deliberate user intent rather than accidental pointer motion.
Pointer Type (mouse, pen, touch emulated)Hover Duration ThresholdPointer VelocityTarget StabilityUI Sensitivity LevelEscape & Re-enter Logic
HOVER_ON_DELAY_FOR_TOOLTIP
When user points to icon and tooltip should appear
βœ… RULES (3)
Require 300–500ms hover duration
Ignore hover if pointer quickly exits
Only trigger after pointer slows down
❌ ANTI-PATTERNS (3)
Showing tooltip instantly
Triggering on fast mouseover
Not verifying pointer dwell time
πŸ’» CODE HINTS (1)
setTimeout(showTooltip, 400) if pointer remains
HOVER_OFF_GRACE_PERIOD
When user leaves hover area but might return
βœ… RULES (3)
Wait 100–200ms before hiding hover element
Cancel hide if pointer returns quickly
Use shared hover state across group elements
❌ ANTI-PATTERNS (3)
Hiding immediately on mouseout
Not tracking related targets
Resetting state unnecessarily
πŸ’» CODE HINTS (1)
onMouseLeave: setTimeout(hide, 150); onMouseEnter: clearTimeout()
TOUCH_DEVICE_HOVER_FALLBACK
When touch device lacks real hover
βœ… RULES (3)
Detect if hover is unsupported
Use first tap to show hover UI
Require second tap for primary action
❌ ANTI-PATTERNS (3)
Assuming hover always available
Triggering click and hover simultaneously
Not adapting to platform capabilities
πŸ’» CODE HINTS (1)
if (!window.matchMedia('(hover: hover)').matches) { ... }
HOVER_FOR_CONTEXTUAL_CONTROLS
When hovering over card or block reveals actions
βœ… RULES (3)
Delay control reveal slightly (~200ms)
Fade in actions, not snap
Hide controls on exit with short grace
❌ ANTI-PATTERNS (3)
Always showing controls
Making hover affordance too subtle
Ignoring pointer exit
πŸ’» CODE HINTS (1)
useEffect(() => setShow(true), [hovered])
PEN_HOVER_DISTINCTION
When stylus hovers but hasn’t touched screen
βœ… RULES (3)
Detect pointerType === 'pen'
Trigger hover affordance when within hover range
Avoid interference with finger gestures
❌ ANTI-PATTERNS (3)
Treating pen same as mouse
Blocking stylus hover due to touch logic
Not checking pointerType
πŸ’» CODE HINTS (1)
if (e.pointerType === 'pen') showStylusUI()
INTENT_EXIT_LOGIC_REFINEMENT
When pointer barely exits and re-enters hover area
βœ… RULES (3)
Measure exit distance and velocity
Ignore exits under threshold radius
Use hysteresis before hiding
❌ ANTI-PATTERNS (3)
Reacting instantly to minor leave
Resetting hover on sub-pixel exit
Failing to smooth pointer jitter
πŸ’» CODE HINTS (1)
track pointer trajectory to detect intentional leave
πŸ§ͺ VALIDATION
Use cursor tracking tools and latency measurements. Verify tooltip and control appearance timing, especially under fast transitions and hybrid input environments.
#194Matrix 194 β€” Click vs Tap Matrix6 cells18 rules18 anti6 hints
To distinguish and properly handle 'click' versus 'tap' interactions across input types, ensuring semantic clarity and performance.
Input Modality (mouse, touch, stylus)Event Timing PrecisionSynthetic Event DetectionElement TypePlatform-Specific BehaviorUser Expectation Alignment
CLICK_FOR_DESKTOP_INTERACTION
When user clicks with mouse on button element
βœ… RULES (3)
Listen for 'click' event on buttons
Use native HTML button where possible
Defer logic to event handler not inline onclick
❌ ANTI-PATTERNS (3)
Binding both mousedown and click together
Attaching logic to multiple mouse events redundantly
Ignoring accessibility roles
πŸ’» CODE HINTS (1)
button.addEventListener('click', handleClick)
TAP_ON_TOUCH_FOR_MOBILE_UI
When finger taps on touchscreen element
βœ… RULES (3)
Detect 'touchend' and ensure minimal movement
Synthesize 'tap' abstraction over touch lifecycle
Avoid 300ms delay by using viewport meta tags
❌ ANTI-PATTERNS (3)
Using only click which may lag on mobile
Not validating touch sequence before firing
Firing on touchstart without end
πŸ’» CODE HINTS (1)
touchEl.addEventListener('touchend', detectTap)
DUPLICATE_EVENT_SUPPRESSION
When both touch and click fire for same action
βœ… RULES (3)
Track last touch time globally
Suppress click if touch happened recently
Use passive touch listeners with caution
❌ ANTI-PATTERNS (3)
Allowing both click and touch to execute logic
Not gating click handlers
Blindly trusting event.sourceCapabilities
πŸ’» CODE HINTS (1)
if (Date.now() - lastTouch < 500) return;
HYBRID_UI_INPUT_NORMALIZATION
When app must support both desktop and mobile
βœ… RULES (3)
Abstract interaction into semantic handlers (e.g., onActivate)
Normalize event sources in wrapper
Detect platform and input mode at runtime
❌ ANTI-PATTERNS (3)
Splitting logic paths per input type
Duplicating DOM logic in handlers
Assuming desktop-style interaction always
πŸ’» CODE HINTS (1)
const onActivate = e => (e.type === 'touchend' ? tap() : click())
ACCESSIBILITY_CLICK_RELIANCE
When ensuring keyboard and screen reader users activate buttons
βœ… RULES (3)
Use native buttons or role='button' with key handlers
Map Enter and Space to same logic as click
Ensure ARIA attributes are correct
❌ ANTI-PATTERNS (3)
Using divs without roles or tabindex
Handling only pointer events
Omitting keyboard support entirely
πŸ’» CODE HINTS (1)
el.addEventListener('keydown', e => { if (e.key === 'Enter') handleClick(); })
PLATFORM_QUIRK_CORRECTIONS
When dealing with inconsistent click/tap behavior across devices
βœ… RULES (3)
Detect and correct platform-specific bugs
Use fast-click libraries or native viewports as needed
Guard against phantom clicks in iOS/Android
❌ ANTI-PATTERNS (3)
Ignoring known tap delays on legacy browsers
Overcorrecting with aggressive preventDefault
Not testing on real devices
πŸ’» CODE HINTS (1)
<meta name='viewport' content='width=device-width, initial-scale=1'>
πŸ§ͺ VALIDATION
Test on hybrid devices and simulators. Ensure no duplicate event fires, consistent trigger timing, and alignment with platform interaction conventions.
#195Debounce Matrix6 cells12 rules6 anti6 hints
Determines when and how to debounce or throttle event handlers β€” preventing excessive execution for search, resize, scroll, and input events.
techniquetrigger_typedelay_strategycancellation
debounce_001
When handling search inputs, debounce the handler to wait until the user stops typing before executing the query.
βœ… RULES (2)
Set delay of 300–500ms after last keypress
Ignore intermediate input events while typing
❌ ANTI-PATTERNS (1)
Triggering search on every keystroke
πŸ’» CODE HINTS (1)
const debounced = debounce(handleSearch, 400);
debounce_002
When listening to scroll events, throttle the handler to execute at most once every interval.
βœ… RULES (2)
Use throttle with interval (e.g. 100ms)
Ignore intermediate scroll events between intervals
❌ ANTI-PATTERNS (1)
Calling expensive logic on every scroll frame
πŸ’» CODE HINTS (1)
const throttled = throttle(onScroll, 100);
debounce_003
When the goal is to trigger an action only after user stops interacting, use trailing execution mode.
βœ… RULES (2)
Set leading: false, trailing: true
Fire only after final event in burst
❌ ANTI-PATTERNS (1)
Using leading:true in contexts that expect delay
πŸ’» CODE HINTS (1)
debounce(fn, 300, { leading: false, trailing: true })
debounce_004
When using debounce or throttle in components, cancel pending timers on unmount or route change.
βœ… RULES (2)
Call cancel() in useEffect cleanup
Avoid running outdated handler
❌ ANTI-PATTERNS (1)
Letting trailing calls fire after component unmounts
πŸ’» CODE HINTS (1)
useEffect(() => { return () => debounced.cancel(); }, [])
debounce_005
When optimizing for fast vs slow typists, adapt debounce delay based on typing speed history.
βœ… RULES (2)
Use shorter delay for fast, longer for slow typists
Measure inter-keypress interval
❌ ANTI-PATTERNS (1)
Fixed delay regardless of user typing pattern
πŸ’» CODE HINTS (1)
const delay = calcDelayFromTypingSpeed(); debounce(fn, delay);
debounce_006
When updating layout or visuals on scroll/resize, throttle handler using requestAnimationFrame for smooth performance.
βœ… RULES (2)
Use RAF to limit execution to frame rate
Cancel scheduled RAF if new one is queued
❌ ANTI-PATTERNS (1)
Using setTimeout for visual sync work
πŸ’» CODE HINTS (1)
let raf; function handler() { if (!raf) raf = requestAnimationFrame(() => { update(); raf = null; }); }
πŸ§ͺ VALIDATION
Verify: debounce fires only after user pause, throttle limits handler frequency, trailing-only prevents premature exec, cancel logic prevents stale runs, adaptive delay adjusts to speed, and RAF syncs to frame.
#196Throttle Matrix6 cells12 rules6 anti6 hints
Determines how throttling limits event handler execution β€” fixed interval, leading/trailing edge, and RAF-based throttling.
throttle_methodedge_behaviorintervalcancellation
throttle_001
When an event handler (e.g. scroll, resize) fires rapidly, throttle with fixed interval and leading edge to fire immediately then suppress.
βœ… RULES (2)
Invoke handler on first trigger in interval
Suppress all other calls until interval passes
❌ ANTI-PATTERNS (1)
Handler executes multiple times during interval window
πŸ’» CODE HINTS (1)
throttle(fn, { wait: 100, leading: true, trailing: false })
throttle_002
When deferring handler until user finishes action, use trailing edge throttle to wait until no events arrive in interval.
βœ… RULES (2)
Do not invoke immediately
Execute after last event in X ms window
❌ ANTI-PATTERNS (1)
Firing multiple times or before user finishes interaction
πŸ’» CODE HINTS (1)
throttle(fn, { wait: 300, leading: false, trailing: true })
throttle_003
When syncing UI updates to screen refresh rate (e.g. animations), throttle with requestAnimationFrame to avoid jank.
βœ… RULES (2)
Call handler inside RAF callback
Cancel pending RAF on cleanup
❌ ANTI-PATTERNS (1)
Using setInterval/setTimeout for animation frame work
πŸ’» CODE HINTS (1)
let id = requestAnimationFrame(fn); cancelAnimationFrame(id)
throttle_004
When throttled handler is used in React component, cancel pending execution on unmount to prevent memory leaks.
βœ… RULES (2)
Create throttled handler with cancel method
Call cancel on componentWillUnmount/useEffect cleanup
❌ ANTI-PATTERNS (1)
Leaving throttled callback active after unmount
πŸ’» CODE HINTS (1)
useEffect(() => { return () => throttled.cancel() }, [])
throttle_005
When supporting diverse devices, adjust throttle interval based on detected CPU/GPU capacity or battery saving mode.
βœ… RULES (2)
Detect device performance profile
Increase interval on low-end devices
❌ ANTI-PATTERNS (1)
Fixed interval regardless of device speed
πŸ’» CODE HINTS (1)
const interval = isLowEndDevice() ? 500 : 100
throttle_006
When needing both immediate reaction and finalization, use throttle that fires at leading and trailing edge.
βœ… RULES (2)
Set both leading and trailing to true
Avoid logic duplication inside handler
❌ ANTI-PATTERNS (1)
Calling handler twice with same logic
πŸ’» CODE HINTS (1)
throttle(fn, { wait: 200, leading: true, trailing: true })
πŸ§ͺ VALIDATION
Verify: throttled handlers fire as configured (once per interval, at edge), RAF bound to animation frame, handlers cancel on unmount, and adaptive logic scales with device.
#197Matrix 197 β€” Interaction Latency Matrix6 cells18 rules18 anti6 hints
Define how to measure, budget, and optimize the latency between user interaction and system response to maintain perceived performance and responsiveness.
latency_budget_tiermeasurement_methodoptimization_strategyperceived_performance_targetinput_modality_sensitivitydegradation_handling
FIRST_RESPONSE_VISUAL_FEEDBACK
When user performs an action expecting immediate UI response
βœ… RULES (3)
Target < 100ms for visual feedback
Use lightweight transition effect
Decouple feedback from business logic delay
❌ ANTI-PATTERNS (3)
Waiting for full result to show animation
Triggering layout reflow before feedback
Animating large DOM subtree synchronously
πŸ’» CODE HINTS (1)
button.addClass('pressed'); setTimeout(() => showResult(), 0)
INPUT_MODALITY_BASED_TARGETS
When supporting diverse input types (touch, keyboard, gamepad)
βœ… RULES (3)
Set tighter thresholds for touch (≀ 50ms)
Allow looser delay for keyboard/gamepad
Normalize feedback duration across inputs
❌ ANTI-PATTERNS (3)
Assuming one-size latency target
Forgetting to test on touch devices
Blocking input queue on slow transitions
πŸ’» CODE HINTS (1)
if (inputType === 'touch') budget = 50; else budget = 100;
LATENCY_MEASUREMENT_INSTRUMENTATION
When collecting metrics on user interaction timing
βœ… RULES (3)
Use PerformanceObserver or equivalent
Capture interactionStart β†’ responsePaint
Log to telemetry stream for analysis
❌ ANTI-PATTERNS (3)
Measuring DOMContentLoaded instead of interaction
Skipping user-perceived delay logging
Only profiling backend
πŸ’» CODE HINTS (1)
performance.mark('start'); ... mark('paint'); measure()
INTERACTION_BUDGET_ALLOCATION
When designing multi-phase UI interactions
βœ… RULES (3)
Define end-to-end latency budget (e.g., 300ms)
Split budget: feedback (50), processing (150), render (100)
Abort phases exceeding allocated time
❌ ANTI-PATTERNS (3)
Letting animation delay total response
Ignoring frontend budget in favor of backend
No enforcement of timing limits
πŸ’» CODE HINTS (1)
if (Date.now() - start > phaseBudget) abort()
LATENCY_OPTIMIZATION_PATHWAYS
When interaction exceeds desired latency envelope
βœ… RULES (3)
Trace input β†’ response path via flamegraph
Eliminate sync XHRs or blocking reflows
Prefetch data or cache UI state if possible
❌ ANTI-PATTERNS (3)
Retrying with same slow path
Ignoring layout thrash
Optimizing only backend latency
πŸ’» CODE HINTS (1)
requestIdleCallback(), async chunking, prefetch()
DEGRADATION_HANDLING_FALLBACKS
When performance budget is exceeded unexpectedly
βœ… RULES (3)
Disable non-critical animations or features
Show loading indicator if >200ms
Queue low-priority effects post-interaction
❌ ANTI-PATTERNS (3)
Letting slow interactions freeze UI
Triggering spinners after delay
Running all codepaths regardless of load
πŸ’» CODE HINTS (1)
if (elapsed > 200) showSpinner(); else proceed()
πŸ§ͺ VALIDATION
Use interaction trace tools to measure start-to-feedback latency. Run regression benchmarks across input types and log budget adherence across devices.
#198Matrix 198 β€” Feedback Timing Matrix6 cells18 rules18 anti6 hints
To define precise timing guidelines for visual, auditory, and haptic feedback in response to user actions.
Feedback Type (visual, haptic, audio)Action CriticalityLatency ToleranceFeedback DurationInput ModalityPlatform Consistency
VISUAL_FEEDBACK_FOR_TAP
When user taps a button on mobile UI
βœ… RULES (3)
Show visual feedback within 50ms
Use press state or ripple effect
Ensure feedback remains for 100–300ms
❌ ANTI-PATTERNS (3)
Delaying feedback until action completes
No visual response on interaction
Showing effect too briefly to notice
πŸ’» CODE HINTS (1)
addClass('active'); setTimeout(removeClass, 150)
AUDIO_FEEDBACK_FOR_COMPLETION
When action completes and confirmation is needed
βœ… RULES (3)
Play audio cue on success only
Use short, non-intrusive sound (<500ms)
Respect user sound settings and mute
❌ ANTI-PATTERNS (3)
Playing sound before task finishes
Using loud or long sounds
Ignoring accessibility audio settings
πŸ’» CODE HINTS (1)
if (settings.soundOn) playSound('ding')
HAPTIC_FEEDBACK_FOR_CRITICAL_ACTION
When user performs a destructive or irreversible action
βœ… RULES (3)
Trigger haptic only on confirmation
Use stronger vibration pattern (e.g. 50ms pulse)
Avoid repeated vibration for same gesture
❌ ANTI-PATTERNS (3)
Haptic on every interaction
Weak vibration for critical action
Overlapping haptic feedback
πŸ’» CODE HINTS (1)
navigator.vibrate([50])
LOADING_INDICATOR_DELAY_THRESHOLD
When an operation may take time to resolve
βœ… RULES (3)
Wait 200ms before showing loader
Cancel loader if action resolves quickly
Use placeholder shimmer under 1s
❌ ANTI-PATTERNS (3)
Showing loader instantly
Flickering spinner for fast actions
Blocking UI without feedback
πŸ’» CODE HINTS (1)
setTimeout(showSpinner, 200)
FEEDBACK_CHAINING_FOR_MULTI_STEPS
When actions require multiple phases of response
βœ… RULES (3)
Show progress visually across steps
Signal phase completion with feedback
Avoid overlapping multiple feedback types
❌ ANTI-PATTERNS (3)
Providing all feedback at once
Skipping mid-phase confirmations
Stacking audio and haptic simultaneously
πŸ’» CODE HINTS (1)
updateProgress(); playSound('stepDone')
CROSS_PLATFORM_FEEDBACK_ALIGNMENT
When designing app for multiple platforms
βœ… RULES (3)
Match animation and feedback timing across OSes
Adjust duration based on platform standards
Test on native hardware for accuracy
❌ ANTI-PATTERNS (3)
Assuming same delay feels equal on all devices
Using hardcoded delays without testing
Ignoring platform-specific haptics
πŸ’» CODE HINTS (1)
const delay = isiOS ? 120 : 100
πŸ§ͺ VALIDATION
Use real device testing and event logging. Measure feedback latency, duration, and user-perceived timing quality. Include edge cases and transition states.
#199Accessibility Events Matrix6 cells12 rules6 anti6 hints
Determines how events are made accessible β€” keyboard equivalents, screen reader announcements, focus management, and ARIA live regions.
event_equivalentannouncement_methodfocus_handlingcompliance
access_001
When a clickable UI element is activated by mouse click, ensure equivalent activation using keyboard Enter or Space.
βœ… RULES (2)
Bind both click and keydown handlers
Use role=button when not a <button> element
❌ ANTI-PATTERNS (1)
Only listening for click events on interactive divs
πŸ’» CODE HINTS (1)
element.addEventListener('keydown', e => e.key==='Enter' && onClick())
access_002
When tooltip is shown on hover, show same tooltip on keyboard focus for non-mouse users.
βœ… RULES (2)
Bind tooltip to both mouseenter and focus events
Ensure tooltip content is focusable or announced
❌ ANTI-PATTERNS (1)
Tooltips that appear only on hover and not focus
πŸ’» CODE HINTS (1)
element.onmouseenter = element.onfocus = showTooltip
access_003
When content updates dynamically (e.g. error, chat), use aria-live region to announce changes to screen readers.
βœ… RULES (2)
Use aria-live='polite' or 'assertive' on container
Update container textContent to trigger announcement
❌ ANTI-PATTERNS (1)
DOM update without aria-live β†’ screen readers silent
πŸ’» CODE HINTS (1)
<div aria-live='polite'>{{message}}</div>
access_004
When interaction completes (e.g. modal close), move focus to logical next element for continuity.
βœ… RULES (2)
Store last focused element before modal
Restore focus after modal closes or redirect to next UI focus point
❌ ANTI-PATTERNS (1)
Focus lost in DOM after dialog closes
πŸ’» CODE HINTS (1)
lastFocusedElement.focus()
access_005
When a non-button element is clickable, assign role=button and support keyboard activation.
βœ… RULES (2)
Add role=button + tabindex=0
Support Enter/Space via keydown handler
❌ ANTI-PATTERNS (1)
Clickable <div> with no role or keyboard support
πŸ’» CODE HINTS (1)
<div role='button' tabindex='0' onkeydown=handleKey />
access_006
When validating accessibility events, define test steps using screen readers (NVDA, VoiceOver) for key interactions.
βœ… RULES (2)
Document interaction scenario and expected spoken feedback
Include test results in accessibility audit
❌ ANTI-PATTERNS (1)
No manual testing plan for critical a11y flows
πŸ’» CODE HINTS (1)
// Step: Focus submit β†’ Screen reader reads 'Submit button'
πŸ§ͺ VALIDATION
Verify: all interactive elements are keyboard accessible, tooltips activate on focus, aria-live regions announce updates, focus returns logically post-interaction, and screen reader testing confirms expected spoken feedback.
#200Matrix 200 β€” Custom Events Matrix6 cells18 rules18 anti6 hints
To guide how and when to create, dispatch, and handle custom events across components or modules.
Event Scope (local, component, global)Payload StructureDispatch TimingBubbling BehaviorDefault Prevention SupportEvent Naming Convention
LOCAL_COMPONENT_EMIT
When a component needs to notify parent of internal change
βœ… RULES (3)
Use dispatchEvent with CustomEvent
Keep event name scoped to component domain
Pass minimal structured detail object
❌ ANTI-PATTERNS (3)
Using global events for local needs
Passing raw objects or functions in detail
Triggering multiple redundant events
πŸ’» CODE HINTS (1)
this.dispatchEvent(new CustomEvent('item:select', { detail: { id } }))
GLOBAL_CUSTOM_SIGNAL
When signaling app-wide state change
βœ… RULES (3)
Use window or document to dispatch
Standardize event naming (e.g., app:ready)
Document available global events
❌ ANTI-PATTERNS (3)
Firing from random DOM nodes
Changing global app state with unclear trigger
Not documenting global contract
πŸ’» CODE HINTS (1)
document.dispatchEvent(new CustomEvent('app:ready'))
EVENT_WITH_PREVENTABLE_DEFAULT
When consumer may cancel default component behavior
βœ… RULES (3)
Set cancelable: true on CustomEvent
Check return value of dispatchEvent
Skip default action if prevented
❌ ANTI-PATTERNS (3)
Not allowing consumers to intercept
Ignoring preventDefault result
Using cancelable without checking result
πŸ’» CODE HINTS (1)
const evt = new CustomEvent('dialog:close', { cancelable: true }); if (!el.dispatchEvent(evt)) return;
NAMESPACED_EVENT_NAMING
When defining new event types
βœ… RULES (3)
Use colon (:) to namespace logically
Prefix with module or feature name
Avoid generic names like 'change' or 'action'
❌ ANTI-PATTERNS (3)
Using native DOM event names
Mixing unrelated meanings in same event
Omitting module context
πŸ’» CODE HINTS (1)
'search:query:update' instead of 'update'
ASYNC_DISPATCH_AFTER_COMMIT
When event should only fire after DOM/UI update
βœ… RULES (3)
Defer dispatch with requestAnimationFrame or setTimeout
Confirm DOM reflects expected state
Avoid blocking user input during wait
❌ ANTI-PATTERNS (3)
Dispatching during state transition
Assuming synchronous flow
Causing jank via synchronous DOM ops
πŸ’» CODE HINTS (1)
requestAnimationFrame(() => el.dispatchEvent(...))
CUSTOM_EVENT_TESTING_AND_LOGGING
When debugging or verifying event flows
βœ… RULES (3)
Log event dispatch and reception in dev mode
Expose test utilities to simulate events
Use devtools or proxies to trace
❌ ANTI-PATTERNS (3)
Letting events silently fail
Not exposing test access to internal events
Logging in production unintentionally
πŸ’» CODE HINTS (1)
console.debug('[event]', e.type, e.detail)
πŸ§ͺ VALIDATION
Use event listeners and test harnesses to simulate, intercept, and observe custom events. Ensure cancelable flows behave correctly and event scope is respected.
#201Matrix 201 β€” Event Naming Matrix6 cells18 rules18 anti6 hints
To enforce consistent, descriptive, and collision-resistant naming conventions for events across systems.
Event Origin (native, custom, synthetic)Semantic ClarityNamespace StrategyComponent ScopeTrigger TypeCross-System Compatibility
CUSTOM_EVENT_MODULE_PREFIXING
When defining events in reusable modules
βœ… RULES (3)
Prefix event names with module identifier
Use kebab or colon case for structure
Avoid bare nouns as names
❌ ANTI-PATTERNS (3)
Using 'update' or 'submit' alone
Not indicating ownership or origin
Mismatching event casing
πŸ’» CODE HINTS (1)
'form:input:update' or 'chat-message:received'
NATIVE_EVENT_AVOIDANCE
When naming custom events that may overlap
βœ… RULES (3)
Check event name against standard DOM event list
Avoid names like 'click', 'input', 'change'
Use distinct composite names
❌ ANTI-PATTERNS (3)
Overloading 'submit' or 'focus' with new meanings
Relying on context to differentiate
Shadowing causing unexpected browser behavior
πŸ’» CODE HINTS (1)
'modal:confirm' instead of 'submit'
EMITTED_EVENT_ROLE_INFIXING
When event reflects action from specific actor
βœ… RULES (3)
Include actor role in name if relevant
Use infix like 'user', 'system', 'client', etc.
Favor clarity over brevity
❌ ANTI-PATTERNS (3)
Ambiguous subjects in emitted event
Using only verb
Forgetting user/system distinction
πŸ’» CODE HINTS (1)
'user:message:sent' or 'system:task:retry'
TRIGGER_VERB_ALIGNMENT
When selecting the verb for event name
βœ… RULES (3)
Choose from curated verb list (open, select, toggle, etc.)
Match verb to lifecycle or transition phase
Document meanings in design system
❌ ANTI-PATTERNS (3)
Overloading same verb for unrelated triggers
Using colloquial verbs ('poke', 'zap')
Mixing tense or mood arbitrarily
πŸ’» CODE HINTS (1)
'dropdown:open' and 'modal:close'
NAMESPACE_HIERARCHY_ALIGNMENT
When system includes multiple subsystems or domains
βœ… RULES (3)
Use colon-separated namespaces to mirror component tree
Ensure top-level aligns with app/module
Avoid flat names across complex systems
❌ ANTI-PATTERNS (3)
Overloading same event in multiple modules
Skipping intermediate levels
Making namespace too deep (more than 4 levels)
πŸ’» CODE HINTS (1)
'app:chat:input:send'
EVENT_DOC_AND_DISCOVERABILITY
When publishing events for consumption
βœ… RULES (3)
Document all custom events in dev docs
Expose event name lists via tooling
Tag emitted events in logs when active
❌ ANTI-PATTERNS (3)
Undocumented internal events
Hardcoded strings scattered in code
No way to trace or grep event names
πŸ’» CODE HINTS (1)
export const EVENT_CHAT_SEND = 'chat:message:send'
πŸ§ͺ VALIDATION
Review all event names for consistency. Run linters or regexes to check naming alignment. Validate uniqueness and log tagging in staging environments.
#202Matrix 202 β€” Event Payload Matrix6 cells18 rules18 anti6 hints
Define how to structure, document, validate, and consume event payloads to ensure reliable data exchange across UI and system components.
payload_structure_typeserialization_formatversioning_strategyvalidation_requirementconsumer_contract_typesecurity_and_sanitization
FLAT_OBJECT_PAYLOAD_FOR_SIMPLE_EVENTS
When emitting events like button click or toggle
βœ… RULES (3)
Use flat key-value object
Avoid nesting unless necessary
Keep payload ≀ 3 fields if possible
❌ ANTI-PATTERNS (3)
Sending full application state
Overusing nested objects
Attaching unrelated metadata
πŸ’» CODE HINTS (1)
{ type: 'click', targetId: 'btn-1' }
NESTED_PAYLOAD_FOR_COMPLEX_FORMS
When submitting or validating full structured forms
βœ… RULES (3)
Structure payload to mirror form group layout
Include validation-ready formats
Serialize optional fields as null or omit explicitly
❌ ANTI-PATTERNS (3)
Flattening nested groups
Mixing nulls and empties inconsistently
Embedding form markup or labels
πŸ’» CODE HINTS (1)
{ address: { city: 'NY', zip: '10001' }, contact: { email: 'x@y.com' } }
VERSIONED_PAYLOAD_SCHEMA_EVOLUTION
When event consumers evolve independently from producers
βœ… RULES (3)
Embed version in payload or header
Document schema changes in changelog
Use semantic versioning for breaking changes
❌ ANTI-PATTERNS (3)
Overwriting schema fields in-place
Not tracking version history
Relying on consumer to infer structure
πŸ’» CODE HINTS (1)
{ version: '1.2.0', data: {...} }
VALIDATED_PAYLOAD_WITH_SCHEMA
When payload is critical to business logic or API integration
βœ… RULES (3)
Validate against JSON Schema or equivalent
Fail fast on schema mismatch
Expose validation errors in logs
❌ ANTI-PATTERNS (3)
Skipping validation in non-production
Silent fallbacks on bad input
Logging raw payloads with PII
πŸ’» CODE HINTS (1)
ajv.validate(schema, payload)
DOCUMENTED_PAYLOAD_FOR_CONTRACT_EVENTS
When events are published for external systems or teams
βœ… RULES (3)
Document field meanings and types
Include sample payloads in docs
Publish contract versions with changelog
❌ ANTI-PATTERNS (3)
Sharing undocumented event APIs
Relying on tribal knowledge
Providing outdated payload samples
πŸ’» CODE HINTS (1)
docs/events/event-type.md with JSON examples
SANITIZED_PAYLOAD_FOR_SECURITY
When event payload may include user or external input
βœ… RULES (3)
Escape dangerous characters before emit
Strip untrusted HTML/scripts
Whitelist allowed fields/types
❌ ANTI-PATTERNS (3)
Passing raw input directly
Allowing scriptable fields to propagate
Not enforcing type constraints on input
πŸ’» CODE HINTS (1)
sanitize(payload); emitEvent(type, payload)
πŸ§ͺ VALIDATION
Validate payload schemas against real emitted events. Run tests for version mismatch, missing fields, and injection risks. Confirm consumers can parse each variant.
#203Matrix 203 β€” Event Ordering Matrix6 cells18 rules18 anti6 hints
Define how to control, preserve, and reason about the order of events in reactive UI systems to ensure predictable behavior.
event_source_typetemporal_priorityhandler_registration_orderbubbling_vs_capturingasynchronous_vs_synchronousstate_dependency_ordering
SYNCHRONOUS_UI_EVENT_FLOW
When handling native UI events like click or keydown
βœ… RULES (3)
Register handlers in deterministic order
Use capturing or bubbling intentionally
Avoid async side-effects during sync event phase
❌ ANTI-PATTERNS (3)
Mixing sync and async updates in same handler
Relying on DOM event ordering alone
Chaining effects based on external state
πŸ’» CODE HINTS (1)
addEventListener('click', handler, { capture: true })
ASYNC_EVENT_CHAINING_STRATEGY
When triggering events across promise or timeout boundaries
βœ… RULES (3)
Tag events with causality or sequence IDs
Chain event dispatch within .then() blocks
Avoid interleaving unrelated async triggers
❌ ANTI-PATTERNS (3)
Dispatching unrelated events in shared timeout
Assuming order of microtasks vs timeouts
Forgetting to cancel stale chains
πŸ’» CODE HINTS (1)
Promise.resolve().then(() => dispatchEvent(...))
BUBBLING_ORDER_CONTROL
When multiple elements handle same bubbling event
βœ… RULES (3)
Know registration order affects bubbling phase
Use stopPropagation to short-circuit
Log bubbling path for diagnostics
❌ ANTI-PATTERNS (3)
Assuming random handler wins
Letting multiple handlers act without order
Skipping propagation control
πŸ’» CODE HINTS (1)
e.stopPropagation()
CAPTURE_PHASE_PRECEDENCE_USE
When early interception of interaction is needed
βœ… RULES (3)
Register with capture: true
Avoid redundant handling in bubble phase
Use for audit, veto, or high-trust logic
❌ ANTI-PATTERNS (3)
Handling sensitive logic in late bubble phase
Duplicate handlers across both phases
Skipping capture when needed for order
πŸ’» CODE HINTS (1)
el.addEventListener('submit', intercept, true)
STATE_DEPENDENT_EVENT_ORDERING
When event response depends on shared application state
βœ… RULES (3)
Read state before side-effect
Avoid mutating state mid-flow
Batch state changes before event chain
❌ ANTI-PATTERNS (3)
Mutating global state inside early handler
Assuming later handlers see same state
Triggering re-renders mid-order chain
πŸ’» CODE HINTS (1)
flushUpdates(); dispatchEvent(type)
MULTI_SOURCE_EVENT_COLLISION_HANDLING
When multiple sources emit overlapping events
βœ… RULES (3)
Debounce or throttle noisy sources
Resolve priority explicitly between emitters
Log collision scenarios in test
❌ ANTI-PATTERNS (3)
Relying on timing luck
Ignoring collision between subsystems
Letting both handlers mutate same state
πŸ’» CODE HINTS (1)
useEventBuffer(); scheduleNext()
πŸ§ͺ VALIDATION
Create test cases simulating multiple overlapping events. Confirm deterministic order, no race conditions, and correct propagation phase behavior.
#204Event Idempotency Matrix6 cells12 rules6 anti6 hints
Determines how duplicate event triggers are prevented β€” double-click guards, submission locks, and optimistic deduplication.
dedup_methodtrigger_typelock_durationuser_feedback
idemp_001
When a user clicks a submit button, disable it immediately to prevent duplicate submissions.
βœ… RULES (2)
Set disabled=true on button on first click
Re-enable only after response received or error
❌ ANTI-PATTERNS (1)
Allowing repeated clicks while request pending
πŸ’» CODE HINTS (1)
button.disabled = true; fetch(...).finally(() => button.disabled = false)
idemp_002
When user clicks rapidly (e.g. rating stars), debounce the handler to limit to one call per X milliseconds.
βœ… RULES (2)
Debounce delay should match UX expectations (e.g. 300ms)
Discard extra events within window
❌ ANTI-PATTERNS (1)
Handling every click in real time causing overload
πŸ’» CODE HINTS (1)
const handler = debounce(sendRating, 300)
idemp_003
When submitting a form, set an isSubmitting flag to block parallel submissions.
βœ… RULES (2)
Set isSubmitting=true before sending request
Reset to false on success/failure
❌ ANTI-PATTERNS (1)
Allowing concurrent submits due to missing lock state
πŸ’» CODE HINTS (1)
if (isSubmitting) return; isSubmitting = true; await submit().finally(() => isSubmitting = false)
idemp_004
When sending POST or PUT to backend, include unique Idempotency-Key header to deduplicate retries server-side.
βœ… RULES (2)
Use UUID per client-side intent
Backend must reject duplicate keys or return cached result
❌ ANTI-PATTERNS (1)
No idempotency for non-GET leading to duplicate side effects
πŸ’» CODE HINTS (1)
headers['Idempotency-Key'] = uuidv4()
idemp_005
When payload is repeated within short time (e.g. 1s), discard or ignore as likely duplicate.
βœ… RULES (2)
Compare hash of last N payloads
Set short TTL (e.g. 1s) per unique action
❌ ANTI-PATTERNS (1)
Blindly accept rapid-fire identical requests
πŸ’» CODE HINTS (1)
if (recentHashes.has(hash)) return; recentHashes.add(hash)
idemp_006
When locking input during submission, show spinner or progress indicator to communicate wait state.
βœ… RULES (2)
Show loading spinner inside button or beside input
Hide spinner on completion or error
❌ ANTI-PATTERNS (1)
Locking UI without any visible feedback
πŸ’» CODE HINTS (1)
<button disabled><Spinner /> Submitting...</button>
πŸ§ͺ VALIDATION
Verify: duplicate triggers are blocked on client and server, visual feedback shown during lock, idempotency keys used, and debounce or payload hash dedup is effective.
#205Matrix 205 β€” Event Replay Matrix6 cells18 rules18 anti6 hints
Define how and when to replay events in reactive systems to restore application state, support debugging, or ensure consistency across environments.
replay_trigger_typeevent_persistence_methodserialization_formatreplay_scopeside_effect_safetyidempotency_strategy
REPLAY_FOR_SESSION_RESTORATION
When restoring UI after user refresh or re-entry
βœ… RULES (3)
Store relevant events in local/session storage
Replay only events affecting state, not side-effects
Ensure version compatibility before replay
❌ ANTI-PATTERNS (3)
Replaying stale or incompatible events
Triggering network actions again
Missing cleanup for expired sessions
πŸ’» CODE HINTS (1)
JSON.parse(sessionStorage.getItem('eventLog'))
REPLAY_FOR_TEST_AUTOMATION
When simulating user flows for automated UI tests
βœ… RULES (3)
Use deterministic event logs
Serialize with timestamps and metadata
Mock external responses for isolation
❌ ANTI-PATTERNS (3)
Hardcoding test delays
Replaying non-deterministic async behavior
Skipping validation of replay results
πŸ’» CODE HINTS (1)
cy.readFile('recordedEvents.json').then(replay)
REPLAY_AFTER_CONNECTION_RECOVERY
When reconnecting after network interruption
βœ… RULES (3)
Buffer unsynced events during offline
Validate server state before replay
Use idempotent updates to avoid duplication
❌ ANTI-PATTERNS (3)
Blindly resending all offline actions
Skipping server reconciliation step
Replaying in wrong order
πŸ’» CODE HINTS (1)
replayBufferedEvents().then(sync)
REPLAY_FOR_DEBUG_TIMETRAVEL
When inspecting application behavior over time
βœ… RULES (3)
Capture full event log with state snapshots
Allow replay in controlled sandbox
Enable pause/step controls for timeline
❌ ANTI-PATTERNS (3)
Logging only final state
Allowing side effects during debug replay
No tooling for visualizing replay flow
πŸ’» CODE HINTS (1)
devtools.load(events).enableTimeTravel()
REPLAY_FOR_CONSISTENCY_AUDIT
When verifying that different environments behave identically
βœ… RULES (3)
Log input and output events per environment
Replay same inputs across all targets
Compare outputs and highlight diffs
❌ ANTI-PATTERNS (3)
Ignoring timing variance
Assuming browser rendering consistency
Comparing DOM snapshots only
πŸ’» CODE HINTS (1)
replay(events, { mode: 'audit' })
SAFE_REPLAY_WITH_EFFECT_SUPPRESSION
When events cause side effects like API calls or navigation
βœ… RULES (3)
Mark replay mode in system context
Bypass effectful handlers conditionally
Log all suppressed effects
❌ ANTI-PATTERNS (3)
Triggering real network calls during replay
Failing silently on effect mismatch
Running analytics/logs again during replay
πŸ’» CODE HINTS (1)
if (isReplayMode) skipEffect()
πŸ§ͺ VALIDATION
Log event history and replay scenarios in CI. Test replay correctness under version upgrades, network recovery, and test automation. Confirm no double execution or unexpected mutations.
#206Matrix 206 β€” Event Logging Matrix6 cells18 rules18 anti6 hints
Define how to log interaction events for diagnostics, analytics, and audit trails β€” covering what to capture, where to store, how to correlate, and how to protect user privacy in event logs.
log_scopelog_detail_levellog_destinationcorrelation_strategypii_protectionretention_policy
SESSION_LEVEL_ANALYTICS_EVENTS
When tracking user behavior for product analytics
βœ… RULES (3)
Log event type and timestamp
Anonymize user/session ID
Batch and transmit to analytics service
❌ ANTI-PATTERNS (3)
Sending raw user email
Logging full input text
Storing session logs unencrypted
πŸ’» CODE HINTS (1)
logEvent('page_view', { path: '/checkout' })
COMPONENT_LEVEL_UI_EVENTS
When debugging behavior inside specific component
βœ… RULES (3)
Tag events with component ID
Include state snapshot before/after
Throttle high-frequency logs
❌ ANTI-PATTERNS (3)
Spamming logs on every render
Missing context around event trigger
Logging only when error occurs
πŸ’» CODE HINTS (1)
logger.debug('btn-click', { id: 'delete', state })
AUDIT_TRAIL_FOR_CRITICAL_ACTIONS
When recording irreversible or security-sensitive actions
βœ… RULES (3)
Log user ID, action type, and timestamp
Include request IP/device metadata
Store in write-once or append-only storage
❌ ANTI-PATTERNS (3)
Allowing audit logs to be altered
Excluding admin/system actions
Writing to volatile log store
πŸ’» CODE HINTS (1)
audit.write({ action: 'delete', user, time })
CHAINED_EVENT_CORRELATION
When tracing events across multiple layers or microservices
βœ… RULES (3)
Pass correlation ID with every event
Log parent-child event relationship
Record time deltas between hops
❌ ANTI-PATTERNS (3)
Logging each service in isolation
Creating new ID at each step
Losing causality in async chains
πŸ’» CODE HINTS (1)
span = startTrace('checkout'); span.log('payment.init')
PII_SANITIZATION_PIPELINE
When logging events that may include user input
βœ… RULES (3)
Use redaction filters on input fields
Whitelist safe fields explicitly
Test logs using fake data for verification
❌ ANTI-PATTERNS (3)
Logging entire form payloads
Letting dynamic keys bypass filters
Testing with real PII in staging logs
πŸ’» CODE HINTS (1)
sanitizeLog({ name, email }) β†’ { name, email: '[REDACTED]' }
LOG_RETENTION_AND_EXPIRATION_CONTROL
When managing log storage across environments
βœ… RULES (3)
Apply tiered retention by log type
Delete expired logs automatically
Encrypt and archive sensitive logs
❌ ANTI-PATTERNS (3)
Keeping all logs indefinitely
Storing audit logs without redundancy
Ignoring GDPR/CCPA expiry rules
πŸ’» CODE HINTS (1)
logConfig = { ttl: '30d', rotate: true }
πŸ§ͺ VALIDATION
Trigger synthetic interactions, log outputs, and trace correlation IDs across services. Verify retention, redaction, audit enforcement, and log volume controls across environments.
#207Matrix 207 β€” Event Debugging Matrix6 cells18 rules18 anti6 hints
Define how to inspect, trace, and diagnose issues in event-driven UI systems by revealing propagation, payloads, and execution context.
debugging_scopeevent_logging_methodpropagation_tracingpayload_visualizationdevtool_integration_levelreproducibility_support
INLINE_EVENT_CONSOLE_LOGGING
When debugging a specific interaction in a component
βœ… RULES (3)
Log event type and target
Include payload if available
Use clear message format
❌ ANTI-PATTERNS (3)
Leaving console logs in production
Logging entire event object blindly
Using vague log messages
πŸ’» CODE HINTS (1)
console.debug('[event]', e.type, e.detail)
EVENT_PROPAGATION_INSPECTION
When events are handled in multiple DOM layers
βœ… RULES (3)
Use event listeners in both capture and bubble phase
Log propagation path and phase
Use stopPropagation to test control
❌ ANTI-PATTERNS (3)
Assuming handler order without test
Using only one phase for debugging
Overriding stopPropagation during test
πŸ’» CODE HINTS (1)
addEventListener('click', handler, true)
VISUAL_OVERLAY_FOR_EVENT_TARGETING
When unsure which elements are receiving input
βœ… RULES (3)
Highlight event.target in real time
Display event type near pointer
Use low-opacity overlay for minimal distraction
❌ ANTI-PATTERNS (3)
Blocking input events with overlays
Rendering overlays on every element
Missing cleanup logic
πŸ’» CODE HINTS (1)
drawOverlay(e.target.getBoundingClientRect())
REPLAYABLE_EVENT_LOGS
When reproducing nondeterministic UI bugs
βœ… RULES (3)
Log timestamped event sequences
Include normalized payloads
Provide toggle to enable logging
❌ ANTI-PATTERNS (3)
Always capturing user data
Logging too verbosely
Missing metadata for replay
πŸ’» CODE HINTS (1)
events.push({ type, targetId, time })
BROWSER_DEVTOOLS_EVENT_BREAKPOINTS
When isolating event-driven logic in runtime
βœ… RULES (3)
Use Chrome/Firefox event listener breakpoints
Watch event.target and state deltas
Test in capture and bubble phase
❌ ANTI-PATTERNS (3)
Skipping built-in devtools
Pausing in unrelated event chains
Forgetting to remove breakpoints
πŸ’» CODE HINTS (1)
DevTools β†’ Event Listeners β†’ Break on 'click'
REMOTE_EVENT_DEBUGGING_IN_PROD
When diagnosing issues that occur only in production
βœ… RULES (3)
Whitelist debuggable event types
Anonymize payloads and strip PII
Throttle remote logging volume
❌ ANTI-PATTERNS (3)
Logging sensitive user data
Sending all interactions by default
No opt-out for debug mode
πŸ’» CODE HINTS (1)
sendToDebugStream({ type, traceId, summary })
πŸ§ͺ VALIDATION
Simulate interactions and trace propagation, log output, and visual overlays. Confirm that target, phase, and payload match expectations. Replay logs if debugging nondeterminism.
#208Matrix 208 β€” Event Testing Matrix6 cells18 rules18 anti6 hints
Define how to simulate, assert, and verify event-driven behavior through automated and manual testing strategies across UI components.
test_granularityevent_simulation_methodassertion_typecoverage_scopeframework_supportfailure_diagnosability
UNIT_EVENT_HANDLER_TESTING
When verifying standalone event handler logic
βœ… RULES (3)
Use direct invocation of handler
Mock event objects with expected shape
Assert side effects or return value
❌ ANTI-PATTERNS (3)
Testing through full UI stack unnecessarily
Skipping edge cases in input
Mocking event too loosely
πŸ’» CODE HINTS (1)
handler({ target: ..., preventDefault: fn }) β†’ expect(fn).toBeCalled()
COMPONENT_LEVEL_EVENT_SIMULATION
When testing interaction on rendered UI components
βœ… RULES (3)
Render component in test harness
Simulate DOM event (click, input, etc.)
Assert resulting behavior or state
❌ ANTI-PATTERNS (3)
Triggering internal methods directly
Missing assertions on visible outcome
Ignoring async updates after event
πŸ’» CODE HINTS (1)
fireEvent.click(screen.getByText('Submit'))
END_TO_END_EVENT_VERIFICATION
When validating complete user workflows
βœ… RULES (3)
Automate real input via Cypress or Playwright
Assert UI state, network calls, and mutations
Include retry logic for flaky timing
❌ ANTI-PATTERNS (3)
Testing single screen in isolation
Relying only on visible feedback
Ignoring backend state validation
πŸ’» CODE HINTS (1)
cy.get('button').click(); cy.wait('@api');
NEGATIVE_EVENT_CASE_COVERAGE
When ensuring robustness under bad or missing inputs
βœ… RULES (3)
Test events with missing fields
Trigger wrong sequence of events
Simulate blocked or canceled interactions
❌ ANTI-PATTERNS (3)
Only testing happy path
Ignoring malformed inputs
No validation on skipped interactions
πŸ’» CODE HINTS (1)
fireEvent.keyDown(input, { key: 'Tab' })
CROSS_PLATFORM_EVENT_TESTING
When supporting varied environments (mobile, desktop, screenreader)
βœ… RULES (3)
Test on real devices or emulators
Simulate touch, keyboard, pointer separately
Assert consistency in timing and output
❌ ANTI-PATTERNS (3)
Testing only on desktop
Ignoring accessibility input methods
Relying on mouse-only behavior
πŸ’» CODE HINTS (1)
simulateTouchSwipe(component); simulateKeyPress(component, 'Enter')
EVENT_TEST_DIAGNOSTIC_LOGGING
When debugging test flakiness or failure
βœ… RULES (3)
Log event type and target on test start
Dump component state pre/post event
Store trace logs for CI analysis
❌ ANTI-PATTERNS (3)
No logs on failed tests
Unstructured logs that can't be searched
Missing diff of before/after state
πŸ’» CODE HINTS (1)
logger.info('event', e.type, stateBefore, stateAfter)
πŸ§ͺ VALIDATION
Run automated test suites across unit, component, and E2E. Track event coverage, pass/fail ratio, and reproducibility of negative and cross-platform cases.
#209Matrix 209 β€” Interaction Failure Matrix6 cells18 rules18 anti6 hints
Define how to detect, handle, and recover from user interaction failures in UI systems, preserving flow continuity and user trust.
failure_typedetection_methoduser_feedback_mechanismrecovery_strategylogging_and_visibilitypreventive_mitigation
CLICK_NO_RESPONSE
When user clicks a button and nothing happens
βœ… RULES (3)
Set max delay threshold for UI feedback
Show fallback UI if no response
Log unhandled interaction events
❌ ANTI-PATTERNS (3)
No visible change on click
Swallowing exceptions in handlers
No analytics for failed interactions
πŸ’» CODE HINTS (1)
setTimeout(() => showFallback(), 300)
KEYBOARD_INPUT_IGNORED
When user types but no character is entered
βœ… RULES (3)
Log ignored keystrokes
Show inline tip or hint for expected focus
Redirect focus if appropriate
❌ ANTI-PATTERNS (3)
Swallowing key events in global listener
No feedback on input rejection
Letting ghost focus absorb input
πŸ’» CODE HINTS (1)
if (!e.defaultPrevented) trackIgnoredKey(e.key)
DRAG_DROP_FAILURE_RECOVERY
When drag/drop interaction fails silently
βœ… RULES (3)
Revert to original state on drop failure
Show toast explaining failure
Highlight valid drop zones preemptively
❌ ANTI-PATTERNS (3)
Letting item disappear with no action
No explanation for invalid drop
Disabling undo after failure
πŸ’» CODE HINTS (1)
onDropFailure(() => restoreItem())
TOUCH_GESTURE_UNRECOGNIZED
When swipe or pinch does not trigger expected result
βœ… RULES (3)
Log failed gesture attempts
Display gesture guide or tooltip
Allow retry without reset
❌ ANTI-PATTERNS (3)
No feedback for invalid gesture
Hard resetting app on failure
Blaming hardware without test
πŸ’» CODE HINTS (1)
onGestureFail(() => showHint('Try swiping slower'))
FORM_SUBMISSION_FAILURE
When user submits form but backend fails
βœ… RULES (3)
Persist form data in local state
Show error message with retry CTA
Log submission context for debugging
❌ ANTI-PATTERNS (3)
Losing user data on failed submit
Showing generic error with no detail
Not allowing user to fix and retry
πŸ’» CODE HINTS (1)
saveToDraft(); showError('Couldn’t submit. Try again.')
FOCUS_TRAP_BREAKAGE
When modal or dialog loses focus control
βœ… RULES (3)
Detect tab loop escape
Refocus inside modal automatically
Log trap break for QA tracking
❌ ANTI-PATTERNS (3)
Letting tab exit modal silently
No refocus on backdrop click
Unlogged accessibility errors
πŸ’» CODE HINTS (1)
focusTrap.onEscape(() => restoreFocus())
πŸ§ͺ VALIDATION
Simulate broken flows across all input types. Track error logs, measure recovery timing, and validate presence of UI fallback or retry guidance.
#210Interaction Recovery Matrix6 cells12 rules9 anti10 hints
Determines how failed interactions are recovered β€” retry prompts, undo support, autosave, and graceful error handling in event flows.
recovery_typetriggeruser_communicationdata_preservation
interact_001
When a user action (e.g. form submission) fails due to a recoverable error, show retry button and descriptive message.
βœ… RULES (2)
Detect failure reason and provide actionable retry
Preserve input state to allow retry without reentry
❌ ANTI-PATTERNS (2)
Generic error with no retry option
Resetting form state after failure
πŸ’» CODE HINTS (2)
<button onclick=retry()>Retry</button>
setError('Network timeout. Click retry.')
interact_002
When a destructive action is taken (e.g. delete item), support undo via Ctrl+Z or UI undo button.
βœ… RULES (2)
Push reversible actions to history stack
Display undo hint after critical change
❌ ANTI-PATTERNS (2)
Permanent delete without undo
No visual cue of undo availability
πŸ’» CODE HINTS (2)
undoStack.push(action)
document.addEventListener('keydown', e => e.ctrlKey && e.key === 'z' && undo())
interact_003
When a user is typing into an input field, periodically save draft to avoid data loss in case of crash or refresh.
βœ… RULES (2)
Debounce saves every 5s or on blur
Use localStorage/sessionStorage for persistence
❌ ANTI-PATTERNS (2)
Saving on every keystroke
Only saving on submit
πŸ’» CODE HINTS (2)
debounce(() => localStorage.setItem('draft', input.value), 5000)
input.onblur = saveDraft
interact_004
When a user navigates away from a form mid-edit, preserve current state and restore on return.
βœ… RULES (2)
Save form state on beforeunload or route change
Restore form state on mount if draft exists
❌ ANTI-PATTERNS (1)
Discarding unsaved input when user navigates
πŸ’» CODE HINTS (2)
window.onbeforeunload = () => saveForm(form)
if (draft) hydrateForm(draft)
interact_005
When an exception is thrown in an interaction handler (e.g. onClick), catch it with an error boundary and show graceful fallback UI.
βœ… RULES (2)
Wrap event logic in try/catch or component boundary
Show meaningful message or recovery button
❌ ANTI-PATTERNS (1)
Unhandled exceptions that crash UI
πŸ’» CODE HINTS (1)
<ErrorBoundary fallback={<RetryUI />}><Button onClick=handleClick /></ErrorBoundary>
interact_006
When interaction fails due to network or offline state, queue the action and replay once connectivity resumes.
βœ… RULES (2)
Store failed interactions in offline queue
Listen for online event and retry queued actions
❌ ANTI-PATTERNS (1)
Dropping failed requests without notice
πŸ’» CODE HINTS (1)
queue.push(action); window.addEventListener('online', retryQueue)
πŸ§ͺ VALIDATION
Verify: retry visible and preserves input, undo stack functional, autosave triggered properly, draft restored on return, event errors caught gracefully, and queued actions retried after recovery.
β–Ό 🌐 L8 β€” Integration 30 matrices
#211API Boundary Matrix6 cells12 rules6 anti8 hints
Determines where API boundaries are drawn β€” what is exposed, what is internal, how requests/responses are shaped, and how versioning works across boundaries.
boundary_typeexposure_levelcontract_formatversioning
api_001
When exposing a public REST API, version endpoints explicitly and define contracts via OpenAPI.
βœ… RULES (2)
Use path-based versioning (e.g. /v1/resource)
Publish OpenAPI spec for consumers
❌ ANTI-PATTERNS (1)
Changing request/response shape without version bump
πŸ’» CODE HINTS (2)
GET /v1/products
openapi: 3.0.0
api_002
For service-to-service internal APIs, use strongly-typed contracts (e.g. protobuf) and evolve schemas with backward compatibility.
βœ… RULES (2)
Use gRPC or protobuf schemas
Avoid removing fields or changing types
❌ ANTI-PATTERNS (1)
Relying on untyped JSON between services
πŸ’» CODE HINTS (1)
message Order { string id = 1; repeated Item items = 2; }
api_003
When using a Backend-for-Frontend (BFF) pattern, shape DTOs per frontend view to minimize over-fetching and logic duplication.
βœ… RULES (2)
Assemble DTOs from multiple internal services
Expose only what UI needs
❌ ANTI-PATTERNS (1)
Returning raw backend entities with extra irrelevant fields
πŸ’» CODE HINTS (1)
return { title: product.name, price: product.displayPrice }
api_004
Define a clear mapping layer between transport DTOs and internal models to decouple domain from API shape.
βœ… RULES (2)
Map API DTOs to domain objects via mapper classes
Avoid leaking internal naming or structure
❌ ANTI-PATTERNS (1)
Using internal domain object as API response directly
πŸ’» CODE HINTS (1)
ProductDto.from(product)
api_005
Use an API Gateway to enforce routing, rate limiting, auth and path rewriting based on routing policy.
βœ… RULES (2)
Define path rules in gateway config
Enforce authentication at gateway layer
❌ ANTI-PATTERNS (1)
Embedding routing logic into individual microservices
πŸ’» CODE HINTS (1)
route /v1 β†’ service-a
api_006
For GraphQL APIs, expose a single endpoint that supports flexible queries while enforcing schema contract.
βœ… RULES (2)
Use schema-first design
Enforce resolvers per type with access control
❌ ANTI-PATTERNS (1)
Over-fetching due to uncontrolled nested queries
πŸ’» CODE HINTS (2)
POST /graphql
type Product { name: String price: Float }
πŸ§ͺ VALIDATION
Verify: all public APIs are versioned and documented, internal APIs use typed contracts, BFF responses match UI needs, mapping layer exists between DTOs and domain models, API gateway routes and protects correctly, GraphQL endpoint supports introspection and validation.
#212Request Lifecycle Matrix6 cells12 rules6 anti8 hints
Determines the lifecycle of an API request β€” from initiation through loading states, response handling, error recovery, and retry to final state.
lifecycle_phasestate_trackingerror_handlingcancellation
reqlife_001
When initiating an API request, set a loading state immediately to reflect progress to the UI.
βœ… RULES (2)
Set isLoading=true before sending request
Disable UI elements (e.g. buttons) to prevent resubmission
❌ ANTI-PATTERNS (1)
UI appears idle while request is in progress
πŸ’» CODE HINTS (2)
setState({ isLoading: true });
button.disabled = true
reqlife_002
When the response is successful, update the UI with the result and clear the loading state.
βœ… RULES (2)
Write data to view model or state
Set isLoading=false after success
❌ ANTI-PATTERNS (1)
Leaving stale data visible after successful response
πŸ’» CODE HINTS (1)
setState({ data: response.data, isLoading: false });
reqlife_003
When a request fails, store the error message and allow user retry.
βœ… RULES (2)
Set error state with message
Display retry button or option
❌ ANTI-PATTERNS (1)
Swallowing errors silently or showing generic alert only
πŸ’» CODE HINTS (2)
setState({ error: err.message })
<button onClick={retry}>Retry</button>
reqlife_004
When the user cancels an in-flight request, use AbortController to terminate fetch early.
βœ… RULES (2)
Create controller before fetch
Call controller.abort() on cancel
❌ ANTI-PATTERNS (1)
Letting in-flight request complete even after user navigated away
πŸ’» CODE HINTS (1)
const controller = new AbortController(); fetch(url, { signal: controller.signal }); controller.abort();
reqlife_005
When same request is triggered multiple times quickly, prevent duplicates by checking or caching in-flight state.
βœ… RULES (2)
Track requests in a Set or Map
Do not send request if already pending
❌ ANTI-PATTERNS (1)
Allowing multiple identical requests in parallel
πŸ’» CODE HINTS (1)
if (pendingRequests.has(url)) return;
reqlife_006
When a request exceeds expected duration, fail gracefully with fallback or retry.
βœ… RULES (2)
Set timeout manually if not built-in
Provide cached data or user feedback
❌ ANTI-PATTERNS (1)
Hanging UI with no error or fallback after 30s
πŸ’» CODE HINTS (1)
setTimeout(() => controller.abort(), 5000);
πŸ§ͺ VALIDATION
Verify: loading state toggles correctly, data/state updated after response, error/retry path shown to user, cancellation via AbortController works, duplicate requests blocked, timeouts handled with fallback.
#213Matrix 213 β€” Response Handling Matrix6 cells18 rules18 anti6 hints
Define how to structure, classify, and act on responses from APIs, services, or other I/O systems to ensure safe and predictable handling across layers.
response_classificationparsing_strategysuccess_condition_definitionside_effect_triggeringtimeout_and_retry_policyresponse_logging_scope
SUCCESS_PAYLOAD_EXTRACTION
When receiving a successful API response with nested data
βœ… RULES (3)
Check HTTP status code or equivalent success indicator
Parse only validated fields from payload
Trigger state update after transformation
❌ ANTI-PATTERNS (3)
Blindly trusting response structure
Skipping null/undefined checks
Updating UI before payload is validated
πŸ’» CODE HINTS (1)
if (res.status === 200) setData(res.data.items)
EMPTY_RESPONSE_HANDLING
When external service returns no data or empty body
βœ… RULES (3)
Define default fallback structure
Warn user if contextually abnormal
Skip downstream logic if blocking
❌ ANTI-PATTERNS (3)
Rendering blank UI without message
Throwing error on legitimate empty result
Passing undefined to logic expecting arrays
πŸ’» CODE HINTS (1)
if (!data || data.length === 0) showEmptyState()
RETRYABLE_TRANSIENT_FAILURES
When receiving 5xx, network errors, or timeouts
βœ… RULES (3)
Detect transient failure categories
Apply exponential backoff for retries
Abort retries after fixed attempts
❌ ANTI-PATTERNS (3)
Retrying indefinitely
Failing silently
Retrying client-side 4xx responses
πŸ’» CODE HINTS (1)
retryWithBackoff(fn, { maxAttempts: 3 })
MULTI_RESPONSE_AGGREGATION
When coordinating results from multiple API calls
βœ… RULES (3)
Wait for all or fallback with partial mode
Normalize structures into common model
Tag partial/incomplete results if needed
❌ ANTI-PATTERNS (3)
Failing entire flow if one call fails
Merging incompatible payloads
Assuming response order guarantees
πŸ’» CODE HINTS (1)
Promise.allSettled(requests).then(joinResponses)
ASYNC_RESPONSE_DECODING_STRATEGY
When payloads are streamed or encoded
βœ… RULES (3)
Use streaming parsers or incremental decoding
Run parsing in worker thread if large
Log decoding errors with position/context
❌ ANTI-PATTERNS (3)
Decoding synchronously on main thread
Assuming fixed encoding format
Ignoring partial decode failures
πŸ’» CODE HINTS (1)
reader.read().then(decodeChunk)
RESPONSE_LOGGING_AND_METRICS
When monitoring system health and performance
βœ… RULES (3)
Log status code and endpoint per request
Tag anomalies or slow responses
Forward metrics to observability platform
❌ ANTI-PATTERNS (3)
Logging full payloads in prod
Not sampling high-frequency endpoints
No alerting for abnormal patterns
πŸ’» CODE HINTS (1)
logResponse({ path, status, latency })
πŸ§ͺ VALIDATION
Simulate various response patterns: success, empty, retryable, partial. Confirm extraction, aggregation, and retry logic behave as defined. Monitor logs and metrics for classification accuracy.
#214HTTP Method Semantics Matrix6 cells12 rules6 anti7 hints
Determines correct usage of HTTP methods β€” GET for reads, POST for creation, PUT/PATCH for updates, DELETE for removal β€” ensuring idempotency and cacheability per method.
http_methodidempotencycacheabilitypayload_semantics
http_001
When retrieving data without side-effects, use GET which is safe, idempotent, and cacheable.
βœ… RULES (2)
Use GET for read-only operations
Support browser and CDN caching with proper headers
❌ ANTI-PATTERNS (1)
Modifying server state via GET request
πŸ’» CODE HINTS (1)
GET /users/42 β†’ 200 OK
http_002
When creating new resources or triggering side effects, use POST β€” it's not idempotent and typically non-cacheable.
βœ… RULES (2)
Use POST to create or trigger non-repeatable actions
Ensure server handles duplicate submissions if retried
❌ ANTI-PATTERNS (1)
Using POST to update known resources (use PUT/PATCH instead)
πŸ’» CODE HINTS (1)
POST /users β†’ { name: 'Alice' }
http_003
When fully replacing a known resource, use PUT β€” it's idempotent but generally not cached.
βœ… RULES (2)
PUT replaces entire resource at known URI
Repeat PUT with same payload yields same result
❌ ANTI-PATTERNS (1)
Using PUT for partial updates β€” prefer PATCH
πŸ’» CODE HINTS (1)
PUT /users/42 β†’ { name: 'Updated' }
http_004
When partially updating resources, use PATCH β€” it can be idempotent if guarded with proper preconditions.
βœ… RULES (2)
Use PATCH with ETag or If-Match headers for safe partial updates
Define diff-based payload
❌ ANTI-PATTERNS (1)
Using PATCH without any precondition enforcement
πŸ’» CODE HINTS (1)
PATCH /users/42 β†’ { name: 'Patched' } with If-Match
http_005
When removing resources, use DELETE β€” it is idempotent since repeated calls have the same effect.
βœ… RULES (2)
Ensure DELETE returns 204 or 200 even if resource is already deleted
DELETE should not error on second call
❌ ANTI-PATTERNS (1)
Failing DELETE on non-existent resource
πŸ’» CODE HINTS (1)
DELETE /users/42 β†’ 204 No Content
http_006
When retrieving headers or checking capabilities without a body, use HEAD or OPTIONS β€” they are safe and side-effect free.
βœ… RULES (2)
HEAD returns headers only, no body
OPTIONS checks method support (CORS/preflight)
❌ ANTI-PATTERNS (1)
Sending large payloads with HEAD or OPTIONS
πŸ’» CODE HINTS (2)
HEAD /users/42
OPTIONS /users
πŸ§ͺ VALIDATION
Verify: GET used for read-only with cache, POST for create with side effects, PUT for full replacement, PATCH for partial updates with conditions, DELETE is idempotent, HEAD/OPTIONS used for metadata or preflight.
#215Status Code Matrix6 cells12 rules6 anti6 hints
Determines correct HTTP status code usage β€” 2xx for success, 3xx for redirects, 4xx for client errors, 5xx for server errors β€” ensuring consistent API contracts.
status_rangesemanticsclient_actionretry_eligibility
status_001
When a request completes successfully and returns a response body, respond with 200 OK.
βœ… RULES (2)
Include entity in response body (e.g., JSON payload)
Set Content-Type correctly
❌ ANTI-PATTERNS (1)
Returning 200 with empty body for create or delete operations
πŸ’» CODE HINTS (1)
res.status(200).json(data)
status_002
When a new resource is created via POST, respond with 201 Created and include Location header.
βœ… RULES (2)
Set Location header to point to created resource URI
Optionally include resource in body
❌ ANTI-PATTERNS (1)
Returning 200 for POST creation without Location
πŸ’» CODE HINTS (1)
res.status(201).location('/resource/123').json(newResource)
status_003
When an operation succeeds but has no content to return, use 204 No Content.
βœ… RULES (2)
Ensure no response body is sent
Used for DELETE or PUT with no body
❌ ANTI-PATTERNS (1)
Sending JSON/null body with 204 status
πŸ’» CODE HINTS (1)
res.status(204).send()
status_004
When client sends invalid or missing input data, respond with 400 Bad Request.
βœ… RULES (2)
Return descriptive error message
Include validation details if available
❌ ANTI-PATTERNS (1)
Using 500 for input validation failures
πŸ’» CODE HINTS (1)
res.status(400).json({ error: 'Missing field: name' })
status_005
When a client requests a resource that doesn’t exist, return 404 Not Found.
βœ… RULES (2)
Do not leak internal details
Log internally if needed
❌ ANTI-PATTERNS (1)
Returning 200 with error in body for not-found cases
πŸ’» CODE HINTS (1)
res.status(404).json({ error: 'User not found' })
status_006
When an unexpected error occurs on the server, respond with 500 Internal Server Error.
βœ… RULES (2)
Return generic error message to client
Log full stack trace internally
❌ ANTI-PATTERNS (1)
Exposing exception stack trace to client
πŸ’» CODE HINTS (1)
res.status(500).json({ error: 'Internal server error' })
πŸ§ͺ VALIDATION
Verify: 200 used for success with body, 201 for creation with Location, 204 with no body, 400 on input errors, 404 for missing, 500 for server failure.
#216Matrix 216 β€” Error Response Matrix6 cells18 rules18 anti6 hints
Define how to classify, propagate, and display error responses from APIs or IO systems, ensuring clarity, security, and recoverability across layers.
error_classificationuser_visibility_levelrecovery_capabilitysecurity_and_pii_exposurelogging_policyretry_guidance
CLIENT_SIDE_VALIDATION_ERRORS
When user input fails local validation before submission
βœ… RULES (3)
Highlight field inline
Explain issue in plain language
Prevent request dispatch
❌ ANTI-PATTERNS (3)
Showing generic error toast
Letting invalid input reach server
Using technical jargon for user errors
πŸ’» CODE HINTS (1)
setError('email', 'Must be valid format')
SERVER_BUSINESS_RULE_ERRORS
When server returns 400-series error for logic violations
βœ… RULES (3)
Parse error code and map to friendly text
Log server message for support
Allow user to correct and retry
❌ ANTI-PATTERNS (3)
Dumping raw server message to UI
Assuming all 400s are malformed input
Swallowing error without feedback
πŸ’» CODE HINTS (1)
if (err.code === 'OUT_OF_STOCK') showNotice('Item unavailable')
NETWORK_OR_TIMEOUT_ERRORS
When requests fail due to connectivity or delay
βœ… RULES (3)
Detect network failure or fetch timeout
Display retry button or auto-retry logic
Avoid blaming user for infra issues
❌ ANTI-PATTERNS (3)
Showing spinner forever
Hiding network errors silently
Triggering same request blindly again
πŸ’» CODE HINTS (1)
if (!navigator.onLine || timeout) showRetryModal()
FATAL_SERVER_ERRORS_500_RANGE
When backend returns internal error with no client fix
βœ… RULES (3)
Show generic apology message
Log incident with correlation ID
Route to failover path if available
❌ ANTI-PATTERNS (3)
Showing stacktrace to user
Looping retries on 500
Ignoring error for critical flows
πŸ’» CODE HINTS (1)
captureError(err, { context: 'checkout' })
SECURITY_RELATED_ERRORS
When authentication or authorization fails
βœ… RULES (3)
Avoid revealing protected resource existence
Redirect to login if token expired
Use vague but helpful language (e.g. 'Access denied')
❌ ANTI-PATTERNS (3)
Exposing role or permission detail
Throwing unhandled 401/403
Revealing endpoint logic via error text
πŸ’» CODE HINTS (1)
if (status === 403) redirect('/access-denied')
ERROR_LOGGING_AND_USER_FEEDBACK_LOOP
When error affects user experience and requires team visibility
βœ… RULES (3)
Send sanitized error to backend logger
Display toast or banner if helpful
Link to support if recurring
❌ ANTI-PATTERNS (3)
Logging full stack with PII
Telling user to 'try again later' without context
No capture of transient issues
πŸ’» CODE HINTS (1)
logClientError(e, { route, userId })
πŸ§ͺ VALIDATION
Trigger each error type in isolation. Verify user message clarity, log content, retry behavior, and that sensitive data is not exposed in any layer.
#217Retry Strategy Matrix6 cells12 rules6 anti6 hints
Determines when and how failed requests are retried β€” exponential backoff, jitter, max attempts, and distinguishing transient from permanent failures.
failure_typebackoff_strategymax_attemptscircuit_integration
retry_001
When a transient error (e.g. timeout or HTTP 503) occurs, retry using exponential backoff to reduce pressure on remote system.
βœ… RULES (2)
Retry on 408, 429, 500, 502, 503, 504
Backoff with base delay 200ms doubling each attempt
❌ ANTI-PATTERNS (1)
Retrying instantly or on non-retryable codes like 400, 401
πŸ’» CODE HINTS (1)
delay = Math.min(3200, 200 * 2 ** attempt)
retry_002
When a permanent error occurs (e.g. HTTP 400, 404), fail fast without retries to avoid wasting compute.
βœ… RULES (2)
Do not retry on client errors unless 408 or 429
Surface failure immediately to caller
❌ ANTI-PATTERNS (1)
Retrying 400/404/401 repeatedly expecting recovery
πŸ’» CODE HINTS (1)
if (status in [400,404,401]) throw error
retry_003
When using backoff, add jitter to avoid retry synchronization across clients (thundering herd).
βœ… RULES (2)
Randomize delay within [0, backoff]
Use full jitter or decorrelated jitter variants
❌ ANTI-PATTERNS (1)
All clients retrying with identical schedule
πŸ’» CODE HINTS (1)
delay = Math.random() * base * 2 ** attempt
retry_004
When retrying, cap number of attempts to avoid infinite retry loops and resource exhaustion.
βœ… RULES (2)
Set retry cap (e.g. 3 or 5 attempts)
Abort and log after cap reached
❌ ANTI-PATTERNS (1)
Retry loops without exit condition
πŸ’» CODE HINTS (1)
if (attempts > 5) throw MaxRetriesExceeded
retry_005
When retrying non-GET operations (e.g. POST), include idempotency key to allow safe retries without side effects.
βœ… RULES (2)
Send Idempotency-Key header on first request
Server must store result or reject duplicate keys
❌ ANTI-PATTERNS (1)
Retrying POST without key β†’ causes double insert
πŸ’» CODE HINTS (1)
headers['Idempotency-Key'] = uuidv4()
retry_006
When repeated retries fail, trigger circuit breaker to block further attempts and initiate fallback.
βœ… RULES (2)
Track retry failures in breaker state
Open circuit after threshold (e.g. 5 failures in 30s)
❌ ANTI-PATTERNS (1)
Ignoring retry failure stats β†’ no circuit protection
πŸ’» CODE HINTS (1)
if (failures > 5) circuit.open()
πŸ§ͺ VALIDATION
Verify: retries occur only for retryable failures, backoff includes jitter, retries capped, idempotency enforced, and circuit opens on repeated failure.
#218Timeout Strategy Matrix6 cells12 rules10 anti6 hints
Determines timeout policies for different request types β€” connect timeout, read timeout, overall deadline, and cascading timeout budgets.
timeout_typedurationfallbackpropagation
timeout_001
When initiating outbound connections, set a short connect timeout (e.g. 2–5s) to fail fast if remote is unreachable.
βœ… RULES (2)
Set connect timeout separately from read timeout
Fail connection attempts quickly to avoid hanging user experience
❌ ANTI-PATTERNS (2)
Using default system timeout (can be >30s)
Applying same timeout to both connect and read phases
πŸ’» CODE HINTS (1)
axios.create({ timeout: 5000, timeoutErrorMessage: 'Connect timeout' })
timeout_002
When waiting for response after successful connection, set read timeout (e.g. 10–30s) to abort stalled responses.
βœ… RULES (2)
Apply after TCP connection established
Abort read if time exceeds configured duration
❌ ANTI-PATTERNS (2)
Relying only on connect timeout (no read timeout)
Unlimited wait for backend response
πŸ’» CODE HINTS (1)
fetch(url, { signal: AbortSignal.timeout(15000) })
timeout_003
When designing service interactions, define end-to-end deadline budget across all hops (e.g. 1s for total roundtrip).
βœ… RULES (2)
Track elapsed time from entry point
Fail requests if overall deadline exceeded even if downstream accepts it
❌ ANTI-PATTERNS (1)
Each hop uses full timeout, causing additive delay
πŸ’» CODE HINTS (1)
if (elapsed > deadline) return HTTP 504
timeout_004
When forwarding requests to downstreams, subtract elapsed time and pass reduced timeout budget to next hop.
βœ… RULES (2)
Track total allowed time and decrement per service call
Inject timeout context into outbound headers
❌ ANTI-PATTERNS (1)
Restarting full timeout at each service boundary
πŸ’» CODE HINTS (1)
X-Timeout-Ms: deadline - elapsed
timeout_005
When timeout occurs, return cached or stale data instead of error to maintain degraded functionality.
βœ… RULES (2)
Use fallback only for non-critical freshness data
Clearly indicate response is stale in metadata
❌ ANTI-PATTERNS (2)
Serving stale data as fresh without indication
Using fallback when action must complete (e.g. payment)
πŸ’» CODE HINTS (1)
catch TimeoutError β†’ return cache.get(key) + { stale: true }
timeout_006
When controlling timeout client-side, use AbortController to cancel fetch or async ops after configured time.
βœ… RULES (2)
Create controller and set timeout logic
Attach signal to fetch or async call
❌ ANTI-PATTERNS (2)
Not cleaning up abort controller
Multiple timers conflicting
πŸ’» CODE HINTS (1)
const ctrl = new AbortController(); setTimeout(() => ctrl.abort(), 10000); fetch(url, { signal: ctrl.signal })
πŸ§ͺ VALIDATION
Verify: connect/read timeouts set correctly, deadline enforced across hops, cascading budget passed downstream, stale fallback used only when safe, AbortController cancels ops on time.
#219Matrix 219 β€” Rate Limiting Matrix6 cells18 rules18 anti6 hints
Define how to implement and enforce rate limiting on API calls β€” both for consumers and providers β€” covering quotas, throttling, bursts, feedback, and monitoring.
rate_limit_scopeenforcement_mechanismquota_tracking_methodburst_handling_policyconsumer_feedback_strategymonitoring_and_alerting
PER_USER_LIMIT_WITH_TOKEN_BUCKET
When protecting API per authenticated user
βœ… RULES (3)
Use token bucket with defined refill rate
Track tokens per user/session
Allow brief burst above steady rate
❌ ANTI-PATTERNS (3)
Flat limits for all users
No differentiation by plan
Dropping requests silently
πŸ’» CODE HINTS (1)
bucket.consume(userId) β†’ 429 if empty
GLOBAL_LIMIT_WITH_LEAKY_BUCKET
When protecting backend from global overload
βœ… RULES (3)
Use leaky bucket with drain rate
Throttle excess with 503 or Retry-After
Apply circuit breaker at system edge
❌ ANTI-PATTERNS (3)
Letting bursts spike DB load
Over-committing upstream
Allowing queue growth unchecked
πŸ’» CODE HINTS (1)
if (!bucket.allow()) throw 503
API_KEY_QUOTA_TRACKING_AND RESET
When enforcing quotas per API client
βœ… RULES (3)
Track usage by API key
Reset quotas daily or monthly
Expose remaining quota in headers
❌ ANTI-PATTERNS (3)
Not resetting counters
No public feedback on usage
Same quota across tiers
πŸ’» CODE HINTS (1)
X-RateLimit-Remaining: 152
BURST_ALLOWANCE_WITH_JITTER
When allowing temporary spikes above baseline
βœ… RULES (3)
Allow small overages with decay
Add jitter to avoid synchronization
Use backoff after burst consumed
❌ ANTI-PATTERNS (3)
Fixed reset window
Immediate lockout after burst
Aligned bursts from all users
πŸ’» CODE HINTS (1)
burstWindow = base + random(0, 500ms)
CLIENT_FEEDBACK_ON_LIMIT_EXCEEDED
When clients exceed their quota
βœ… RULES (3)
Respond with 429 status
Include Retry-After or wait hints
Expose usage stats in dashboard or headers
❌ ANTI-PATTERNS (3)
Returning 500 on limit
No guidance on retry
No user-facing quota visibility
πŸ’» CODE HINTS (1)
HTTP 429 Retry-After: 120
REALTIME_ALERTING_ON_QUOTA_BREACH
When monitoring usage by tier or client
βœ… RULES (3)
Set thresholds for each plan or role
Alert on quota breach or anomaly
Log source IP, token, path
❌ ANTI-PATTERNS (3)
No alerts until system failure
No per-client observability
Letting trial users exhaust shared pool
πŸ’» CODE HINTS (1)
alert('rate_limit_exceeded', { apiKey, usage })
πŸ§ͺ VALIDATION
Simulate burst traffic. Trigger per-user and global limit violations. Observe retry headers, backoff, alerting, and graceful degradation.
#220Matrix 220 β€” Pagination Matrix6 cells18 rules18 anti6 hints
Define how to choose and implement pagination strategies across APIs, UIs, and databases, balancing usability, performance, and scalability.
pagination_methodcursor_vs_offsetstate_persistence_strategybackend_capability_alignmentclient_navigation_behaviorscalability_limitations
OFFSET_BASED_PAGINATION_SIMPLE_LISTS
When retrieving static lists with low concurrency
βœ… RULES (3)
Use limit and offset parameters
Display total pages or item count
Avoid for large or dynamic datasets
❌ ANTI-PATTERNS (3)
Using offset when data mutates frequently
Paginating without bounding limit
Assuming total count is fast
πŸ’» CODE HINTS (1)
GET /items?limit=20&offset=40
CURSOR_BASED_PAGINATION_REALTIME_FEEDS
When paging through live or fast-changing data
βœ… RULES (3)
Use opaque cursor tokens
Return next/prev cursors in response
Enforce ordering guarantee on source
❌ ANTI-PATTERNS (3)
Encoding offset as cursor
Returning unordered results
Forgetting to invalidate old cursors
πŸ’» CODE HINTS (1)
GET /feed?cursor=abc123
INFINITE_SCROLL_UI_PATTERN
When user expects seamless scrolling without pagination UI
βœ… RULES (3)
Detect scroll threshold for fetch
Debounce load requests to avoid flood
Show loading indicator at bottom
❌ ANTI-PATTERNS (3)
Triggering fetch on every scroll event
No visual feedback of loading
Not handling end of list
πŸ’» CODE HINTS (1)
useIntersectionObserver(fetchMore)
PAGE_STATE_PERSISTENCE_ON_NAVIGATION
When navigating away and returning to a paginated view
βœ… RULES (3)
Store current page or cursor in route or memory
Restore scroll position on return
Avoid redundant refetching if cache valid
❌ ANTI-PATTERNS (3)
Always resetting to page 1
Hardcoding page state outside of routing
Invalidating cache on minor route changes
πŸ’» CODE HINTS (1)
router.push('/items?page=3')
HYBRID_BACKEND_PAGINATION_SUPPORT
When backend must support both cursor and offset clients
βœ… RULES (3)
Accept both offset and cursor query params
Detect mode and resolve appropriately
Document cursor constraints clearly
❌ ANTI-PATTERNS (3)
Allowing ambiguous pagination mode
Inconsistent page size behavior
Failing silently on bad cursor values
πŸ’» CODE HINTS (1)
if (cursor) { ... } else if (offset) { ... }
LIMIT_PAGINATION_DEPTH_FOR_SCALE
When paginating over very large datasets
βœ… RULES (3)
Set max offset or page depth limit
Encourage filtering or date scoping
Block deep paging with warning
❌ ANTI-PATTERNS (3)
Allowing offset=1,000,000
Returning massive page payloads
Exposing exact dataset size unnecessarily
πŸ’» CODE HINTS (1)
if (offset > 10000) return error('Too deep')
πŸ§ͺ VALIDATION
Test paging behavior under offset and cursor modes. Simulate navigation, state restore, and edge scrolling. Confirm performance and API contract stability.
#221Matrix 221 β€” Filtering Matrix6 cells18 rules18 anti6 hints
Define how to design and apply filtering strategies on datasets across APIs, databases, and UI layers to ensure precision, performance, and consistency.
filter_expression_formatclient_vs_server_filteringfield_type_supportperformance_characteristicscomposability_and_nestinguser_customization_support
SERVER_SIDE_FILTERING_FOR_LARGE_SETS
When querying large datasets from backend
βœ… RULES (3)
Use parameterized query filters
Limit client-visible fields
Index commonly filtered fields
❌ ANTI-PATTERNS (3)
Sending full dataset to client for filtering
Hardcoding filter logic in app code
No control over filter complexity
πŸ’» CODE HINTS (1)
GET /products?category=books&price[lte]=20
CLIENT_SIDE_FILTERING_FOR_SMALL_SETS
When working with small cached lists in UI
βœ… RULES (3)
Perform filter in-memory on user input
Debounce filtering actions
Fallback to server when limit exceeded
❌ ANTI-PATTERNS (3)
Filtering on every keystroke without delay
Fetching entire dataset just to filter
Duplicating logic in multiple views
πŸ’» CODE HINTS (1)
const result = items.filter(x => x.name.includes(query))
ADVANCED_FILTER_BUILDER_SUPPORT
When allowing user to define multi-field, nested filters
βœ… RULES (3)
Support AND/OR nesting
Visualize filter logic as expression tree
Validate before applying
❌ ANTI-PATTERNS (3)
Storing filters as raw strings
Executing unparsed expressions
No UI feedback for malformed filters
πŸ’» CODE HINTS (1)
{ op: 'and', filters: [{ field: 'x', op: '>', val: 10 }, ...] }
TYPE_AWARE_FILTERING_SUPPORT
When filtering fields of varied data types
βœ… RULES (3)
Detect field type for operator selection
Support enums, dates, booleans appropriately
Validate filter format per type
❌ ANTI-PATTERNS (3)
Allowing text match on boolean field
Forgetting time zone logic in date filtering
Letting user choose invalid operator
πŸ’» CODE HINTS (1)
filter.field.type === 'date' β†’ show date-picker + comparator
PERFORMANCE_BOUND_FILTER_STRATEGY
When filtering over potentially slow backend systems
βœ… RULES (3)
Impose field-level filter limits
Require indexed filters for remote queries
Warn user of expensive combinations
❌ ANTI-PATTERNS (3)
Allowing filter on unindexed text field
Combining many ORs without bound
Assuming backend always optimizes
πŸ’» CODE HINTS (1)
if (!field.indexed) return error('Field not searchable')
USER_PREFERENCES_AND_SAVED_FILTERS
When supporting saved views or custom filtering
βœ… RULES (3)
Serialize filters to shareable format
Store in user profile or local storage
Respect defaults + allow overrides
❌ ANTI-PATTERNS (3)
Losing filters on reload
Only saving UI state without logic
Storing opaque blob with no parse model
πŸ’» CODE HINTS (1)
localStorage.setItem('filters', JSON.stringify(currentFilters))
πŸ§ͺ VALIDATION
Apply filters across datasets of various sizes and types. Validate client vs server logic split, type-specific operator behavior, and persistence of saved filters.
#222Matrix 222 β€” Sorting Matrix6 cells18 rules18 anti6 hints
Define how to apply sorting strategies to structured data across APIs, databases, and UIs while maintaining clarity, performance, and consistency.
sort_expression_formatdefault_sort_behaviormulti_field_sorting_supportfield_type_handlingperformance_considerationsuser_control_and_customization
DEFAULT_SORT_ON_PRIMARY_KEY
When no explicit sort is provided on a dataset
βœ… RULES (3)
Use primary key or created_at as fallback
Document default sort explicitly
Avoid random order returns
❌ ANTI-PATTERNS (3)
Leaving order undefined
Relying on database natural order
Inconsistent default sort across environments
πŸ’» CODE HINTS (1)
ORDER BY id ASC
MULTI_FIELD_SORTING_SUPPORT
When users want to sort by multiple columns
βœ… RULES (3)
Allow stable secondary sort fallback
Support client- or server-side expressions
Preserve tie-breaker logic
❌ ANTI-PATTERNS (3)
Overwriting previous sort on second field
Re-sorting full list client-side unnecessarily
Not aligning secondary sort with filter context
πŸ’» CODE HINTS (1)
ORDER BY status ASC, updated_at DESC
CLIENT_SIDE_SORT_FOR_SMALL_CACHES
When sorting small datasets already fetched in UI
βœ… RULES (3)
Use locale-aware string comparison
Respect numeric vs alpha types
Re-render only visible segment
❌ ANTI-PATTERNS (3)
Sorting blindly on stringified values
Triggering full UI reflow
Assuming sort works same across browsers
πŸ’» CODE HINTS (1)
items.sort((a,b) => a.name.localeCompare(b.name))
SERVER_SIDE_SORT_FOR_LARGE_LISTS
When working with large or paginated datasets
βœ… RULES (3)
Push sort expression to backend
Use indexed fields where possible
Align sort with pagination cursor field
❌ ANTI-PATTERNS (3)
Sorting large lists on frontend
Using unindexed sort keys
Changing sort order post-pagination
πŸ’» CODE HINTS (1)
GET /items?sort=price:desc
SORT_UI_CONTROL_PATTERNS
When exposing sorting to users in table or grid
βœ… RULES (3)
Support toggling asc/desc and reset
Show current sort indicators
Use accessible buttons and keyboard support
❌ ANTI-PATTERNS (3)
Hiding sort state from user
Toggling with every click without control
Non-interactive labels
πŸ’» CODE HINTS (1)
onClick: toggleSort(columnKey)
SORT_PERSISTENCE_AND_BOOKMARKING
When users navigate away and return to sorted views
βœ… RULES (3)
Store sort state in query string or route
Apply sort on re-render or mount
Allow shareable sorted URLs
❌ ANTI-PATTERNS (3)
Resetting sort on every view entry
Using internal-only state for sort
Breaking sort on reload
πŸ’» CODE HINTS (1)
router.push({ sort: 'name.asc' })
πŸ§ͺ VALIDATION
Sort real datasets across types and sizes. Validate user controls, sort expression handling, default fallbacks, and sort order persistence across navigation and refresh.
#223Caching Strategy Matrix6 cells12 rules6 anti6 hints
Determines how data is cached across layers β€” browser cache, in-memory cache, API cache headers, and cache invalidation strategies.
cache_layerinvalidation_strategyttl_policyconsistency_model
cache_001
When using HTTP caching at the browser or CDN level, leverage ETag headers to validate freshness without full content download.
βœ… RULES (2)
Set ETag header based on resource hash
Respond with 304 Not Modified if ETag matches
❌ ANTI-PATTERNS (1)
Always returning 200 OK with full body even if unchanged
πŸ’» CODE HINTS (1)
res.setHeader('ETag', calculateHash(body))
cache_002
When enabling browser or CDN cache, use Cache-Control headers to define TTL and revalidation behavior.
βœ… RULES (2)
Use max-age=X for static assets
Use stale-while-revalidate to serve old while revalidating
❌ ANTI-PATTERNS (1)
Leaving cache behavior to default or missing Cache-Control
πŸ’» CODE HINTS (1)
Cache-Control: max-age=86400, stale-while-revalidate=3600
cache_003
When storing transient data in memory (e.g. Map or LRU), apply TTL-based eviction to avoid stale data and memory bloat.
βœ… RULES (2)
Store timestamp alongside value
Purge expired entries on access or interval
❌ ANTI-PATTERNS (1)
Keeping all items in memory indefinitely
πŸ’» CODE HINTS (1)
if (Date.now() - entry.ts > ttl) delete cache[key]
cache_004
When enabling offline support in PWAs, use service worker cache with an offline-first strategy to serve cached content before network fallback.
βœ… RULES (2)
Check CacheStorage before fetching
Fallback to network only if not in cache
❌ ANTI-PATTERNS (1)
Always attempting network fetch first in offline scenario
πŸ’» CODE HINTS (1)
event.respondWith(caches.match(req) || fetch(req))
cache_005
When a mutation (e.g. POST, PUT) occurs, invalidate relevant caches to maintain consistency.
βœ… RULES (2)
On write, delete affected keys in memory or IndexedDB
Clear stale cache entries on mutation acknowledgment
❌ ANTI-PATTERNS (1)
Leaving stale cache after data update
πŸ’» CODE HINTS (1)
onPostSuccess(() => cache.delete('/api/items'))
cache_006
When caching responses, include both URL and normalized query params in cache key to avoid mismatches.
βœ… RULES (2)
Sort and hash query parameters
Use `${url}::${hash(params)}` as key format
❌ ANTI-PATTERNS (1)
Using raw URL string without params handling
πŸ’» CODE HINTS (1)
const key = url + '::' + hash(JSON.stringify(sortedParams))
πŸ§ͺ VALIDATION
Verify: ETag and Cache-Control headers used correctly, TTL works for memory caches, service worker serves offline reliably, mutations clear stale cache, and cache keys handle params correctly.
#224Matrix 224 β€” Cache Invalidation Matrix6 cells18 rules18 anti6 hints
Define strategies for invalidating cached data across layers and systems to ensure freshness, correctness, and performance balance.
cache_scopeinvalidation_triggerconsistency_guarantee_levelpropagation_timinguser_visibilitystaleness_tolerance
TIME_BASED_INVALIDATION_TTL
When cache can tolerate temporary staleness
βœ… RULES (3)
Define explicit TTL per resource
Expire entries asynchronously
Use background refresh if needed
❌ ANTI-PATTERNS (3)
Leaving items cached forever
No control over refresh interval
Over-reliance on default global TTL
πŸ’» CODE HINTS (1)
cache.set(key, value, { ttl: 600 })
MANUAL_INVALIDATION_ON_MUTATION
When data is changed by user or admin
βœ… RULES (3)
Trigger cache.clear(key) on mutation
Log invalidation reason
Invalidate affected related entries
❌ ANTI-PATTERNS (3)
Delaying invalidation until next read
Assuming update will auto-refresh
Only invalidating primary key but not related joins
πŸ’» CODE HINTS (1)
onUpdate: invalidate(['users', 'users:list'])
TAG_BASED_GROUP_INVALIDATION
When multiple cache entries belong to same domain
βœ… RULES (3)
Tag cache entries during write
Purge all tags on update or deploy
Use tag hierarchies if needed
❌ ANTI-PATTERNS (3)
Hardcoding related keys manually
Skipping tag cleanup
Allowing tag explosion without expiration
πŸ’» CODE HINTS (1)
cache.invalidateTags(['user'])
EVENT_DRIVEN_INVALIDATION
When updates happen across systems or users
βœ… RULES (3)
Emit invalidation events via pub/sub
Subscribe on cache layer or CDN edge
Include resource identity in message
❌ ANTI-PATTERNS (3)
Polling for changes unnecessarily
Allowing silent staleness
Lack of listener on subscriber side
πŸ’» CODE HINTS (1)
eventBus.publish('cache:invalidate', { resource: 'org:123' })
ON_NAVIGATION_REFETCH_POLICY
When user navigates back to a previously visited view
βœ… RULES (3)
Define cache revalidation policy on route
Clear or rehydrate cache after threshold
Use cache fingerprint or version tag
❌ ANTI-PATTERNS (3)
Blindly trusting navigation state
Reusing client cache without check
Missing cache key invalidation strategy
πŸ’» CODE HINTS (1)
useQuery({ staleTime: 0 })
USER_TRIGGERED_REFRESH_ACTIONS
When user explicitly wants to refresh stale or suspect data
βœ… RULES (3)
Expose refresh button on view
Bypass cache on user command
Show feedback that refresh is in progress
❌ ANTI-PATTERNS (3)
Forcing refresh without feedback
Hiding refresh controls in nested menus
Refreshing without cache bust mechanism
πŸ’» CODE HINTS (1)
onClick={() => queryClient.invalidateQueries('report')}
πŸ§ͺ VALIDATION
Trigger each invalidation mode in isolation. Confirm refresh occurs, stale data does not persist, and logging captures timing and scope.
#225Streaming Matrix6 cells14 rules6 anti6 hints
Determines how streaming data is handled β€” SSE, WebSocket, chunked transfer, backpressure, and reconnection strategies.
stream_protocoldirectionbackpressurereconnection
stream_001
When pushing real-time updates from server to client, use Server-Sent Events (SSE) for efficient unidirectional streaming.
βœ… RULES (3)
Use 'text/event-stream' Content-Type
Reconnect onEventSource close or error
Keep connection alive with comment heartbeats
❌ ANTI-PATTERNS (1)
Using WebSocket for simple one-way updates unnecessarily
πŸ’» CODE HINTS (1)
const es = new EventSource('/events'); es.onmessage = fn
stream_002
When enabling real-time two-way communication, use WebSockets to allow both client and server to send messages anytime.
βœ… RULES (3)
Upgrade HTTP connection with 'Upgrade: websocket'
Maintain open socket for both directions
Handle ping/pong to detect disconnects
❌ ANTI-PATTERNS (1)
Using polling or SSE when full duplex required
πŸ’» CODE HINTS (1)
ws.send(JSON.stringify({ type: 'ping' }))
stream_003
When streaming data over HTTP without buffering full response, use chunked transfer encoding to flush data as it's available.
βœ… RULES (2)
Set Transfer-Encoding: chunked
Flush response manually after each write
❌ ANTI-PATTERNS (1)
Buffering entire payload before sending
πŸ’» CODE HINTS (1)
res.write('chunk'); res.flush()
stream_004
When consuming streamed response in browser, use ReadableStream API for progressive parsing and UI updates.
βœ… RULES (2)
Read from response.body.getReader() loop
Process text chunks as they arrive
❌ ANTI-PATTERNS (1)
Waiting for full body before parsing
πŸ’» CODE HINTS (1)
reader.read().then(({done,value}) => decode(value))
stream_005
When producer emits faster than consumer can process, apply backpressure via pause/resume or buffer windowing.
βœ… RULES (2)
Check consumer readiness before pushing
Queue or drop excess messages
❌ ANTI-PATTERNS (1)
Unbounded buffering causing memory pressure
πŸ’» CODE HINTS (1)
if (!canProcess) stream.pause()
stream_006
When connection drops, use exponential backoff to retry with increasing delay and avoid overload.
βœ… RULES (2)
Double retry delay after each failure (max cap)
Reset timer on success
❌ ANTI-PATTERNS (1)
Retrying immediately in a tight loop
πŸ’» CODE HINTS (1)
setTimeout(connect, Math.min(2 ** attempts * 1000, 30000))
πŸ§ͺ VALIDATION
Verify: SSE used for push-only, WebSocket for full-duplex, chunked transfer avoids buffering, ReadableStream parsed progressively, backpressure avoids overflow, and reconnect uses backoff.
#226Matrix 226 β€” WebSocket Matrix6 cells18 rules18 anti6 hints
Define when and how to use WebSocket connections for real-time communication, ensuring scalability, reliability, and fallbacks.
connection_lifecyclemessage_routing_strategyauth_handling_methodfallback_and_reconnectscalability_architectureprotocol_standardization
BASIC_PUBSUB_CHANNEL_MODEL
When using WebSocket for simple topic-based updates
βœ… RULES (3)
Use named channels or topics
Support join/leave operations
Broadcast updates to subscribed clients only
❌ ANTI-PATTERNS (3)
Pushing all messages to all clients
Hardcoding topic names in frontend
Allowing anonymous wildcard subscriptions
πŸ’» CODE HINTS (1)
socket.emit('subscribe', 'news:weather')
CONNECTION_AUTHENTICATION_AND_REVOKE
When user identity is required for secure channels
βœ… RULES (3)
Authenticate on initial handshake
Refresh token before expiration
Disconnect or revoke on logout
❌ ANTI-PATTERNS (3)
Skipping auth in WebSocket layer
Letting expired tokens persist
Relying solely on cookie/session auth
πŸ’» CODE HINTS (1)
socket.emit('auth', { token })
RESILIENT_RECONNECT_WITH_BACKOFF
When connection may drop due to network issues
βœ… RULES (3)
Implement exponential backoff for reconnect
Cap retry count or interval
Inform user when offline for long
❌ ANTI-PATTERNS (3)
Reconnecting every 100ms indefinitely
Retrying without notifying user
Not distinguishing error types
πŸ’» CODE HINTS (1)
setTimeout(() => connect(), backoff[i++])
SERVER_SCALE_OUT_VIA_MESSAGE_BROKER
When many servers handle WebSocket clients
βœ… RULES (3)
Use Redis, NATS, or Kafka for cross-node pub/sub
Broadcast to other servers on internal publish
Avoid sticky session reliance if possible
❌ ANTI-PATTERNS (3)
Sending messages only to in-memory clients
Assuming single-node visibility
Not propagating disconnect events
πŸ’» CODE HINTS (1)
pubsub.publish('user:123', message)
PROTOCOL_VERSIONING_AND_ENVELOPE
When designing message format for WebSocket events
βœ… RULES (3)
Include type and version in each message
Wrap payload in a common envelope
Reject unsupported versions gracefully
❌ ANTI-PATTERNS (3)
Sending raw JSON without type metadata
Breaking changes without version bump
Omitting envelope structure
πŸ’» CODE HINTS (1)
{ type: 'chat.message', version: 1, payload: { ... } }
FALLBACK_TO_HTTP_POLLING_OR_SSE
When client or network blocks WebSocket use
βœ… RULES (3)
Detect WebSocket support at runtime
Fallback to HTTP polling or SSE
Unify message format across transports
❌ ANTI-PATTERNS (3)
Breaking app when WS not available
Using completely different format in fallback
No telemetry on fallback usage
πŸ’» CODE HINTS (1)
if (!supportsWebSocket()) useSSE()
πŸ§ͺ VALIDATION
Test WebSocket and fallback modes under real network conditions. Confirm authentication, reconnect, and message routing work cross-node and survive version changes.
#227Matrix 227 β€” Realtime Sync Matrix6 cells18 rules18 anti6 hints
Define how to synchronize state in real-time across clients, tabs, or systems using push-based protocols or polling with consistency and efficiency.
sync_initiation_triggertransport_mechanismconflict_resolution_strategylatency_tolerancedata_granularitysubscription_scope
SERVER_PUSH_ON_MUTATION
When backend updates data relevant to connected clients
βœ… RULES (3)
Emit mutation event with diff
Only notify subscribed clients
Log push latency
❌ ANTI-PATTERNS (3)
Broadcasting full object on every change
Not filtering recipients
Letting outdated values overwrite local state
πŸ’» CODE HINTS (1)
emit('user:updated', { id, patch })
CLIENT_POLL_INTERVAL_FOR_STATIC_DATA
When data changes slowly or cannot use push
βœ… RULES (3)
Set polling interval based on volatility
Use ETag or last-modified headers
Avoid polling when tab is unfocused
❌ ANTI-PATTERNS (3)
Polling every few seconds on static data
Refetching entire dataset
Ignoring backoff or suppression rules
πŸ’» CODE HINTS (1)
setInterval(() => fetch('/feed'), 60000)
TAB_SYNC_WITH_BROADCAST_CHANNEL
When multiple tabs need to sync shared state
βœ… RULES (3)
Use BroadcastChannel or storage event
Send delta rather than full copy
Avoid infinite sync loops
❌ ANTI-PATTERNS (3)
Syncing whole state blindly
Missing source of truth determination
Triggering loops via localStorage writes
πŸ’» CODE HINTS (1)
channel.postMessage({ type: 'update', patch })
CONFLICT_RESOLUTION_VIA_TIMESTAMP
When same record may be updated from multiple sources
βœ… RULES (3)
Compare timestamps or version numbers
Accept latest update or flag conflict
Store metadata about update origin
❌ ANTI-PATTERNS (3)
Last-write-wins without explanation
Overwriting remote changes blindly
No tracking of update history
πŸ’» CODE HINTS (1)
if (incoming.updatedAt > local.updatedAt) accept()
FRAGMENTED_ENTITY_LEVEL_UPDATES
When synchronizing large or structured documents
βœ… RULES (3)
Use patch-based or operational transforms
Track per-section version or checksum
Render minimal UI diff
❌ ANTI-PATTERNS (3)
Re-rendering entire document
Dropping user input during merge
Syncing raw blobs without granularity
πŸ’» CODE HINTS (1)
patch({ section: 'body', changes: [...] })
REALTIME_SYNC_SUBSCRIPTION_SCOPE
When users watch entities or feeds in real time
βœ… RULES (3)
Subscribe only to visible or followed items
Auto-unsubscribe when navigating away
Expose sync state per entity
❌ ANTI-PATTERNS (3)
Staying subscribed to all entities always
No sync feedback for disconnected views
Holding memory for unused topics
πŸ’» CODE HINTS (1)
subscribe(entityId); onUnmount(() => unsubscribe(entityId))
πŸ§ͺ VALIDATION
Simulate concurrent updates, tab interactions, and connection disruptions. Validate diff accuracy, conflict handling, and resource cleanup after unsubscription.
#228Matrix 228 β€” File Upload Matrix6 cells18 rules18 anti6 hints
Define how to architect and secure file uploads from client to server, ensuring scalability, validation, and user experience.
upload_methodfile_validation_strategystorage_destinationprogress_feedback_mechanismsecurity_controlsretry_and_resume_capability
DIRECT_UPLOAD_TO_CLOUD_STORAGE
When uploading large files directly from client
βœ… RULES (3)
Use pre-signed URLs or tokenized endpoints
Validate file metadata before signing
Secure expiration and access control
❌ ANTI-PATTERNS (3)
Allowing arbitrary files without limits
Hardcoding upload targets
Exposing credentials in client
πŸ’» CODE HINTS (1)
fetch('/sign-upload').then(res => uploadTo(res.url))
MULTIPART_FORM_UPLOAD_WITH_BACKEND_VALIDATION
When uploading small or structured files via form
βœ… RULES (3)
Use multipart/form-data encoding
Validate MIME type and schema server-side
Throttle request size and rate
❌ ANTI-PATTERNS (3)
Relying solely on frontend validation
Accepting file buffers blindly
Skipping MIME sniffing
πŸ’» CODE HINTS (1)
app.post('/upload', uploadMiddleware, validateFile, save)
CHUNKED_UPLOAD_FOR_LARGE_FILES
When uploading large files over unstable networks
βœ… RULES (3)
Split files into fixed-size chunks
Track upload status per chunk
Merge and verify on backend
❌ ANTI-PATTERNS (3)
Sending full file on retry
No way to resume after interruption
Merging chunks without hash check
πŸ’» CODE HINTS (1)
uploadChunk(chunk, index); finalizeUpload(fileId)
REALTIME_PROGRESS_FEEDBACK_UI
When users upload files through web UI
βœ… RULES (3)
Display percentage progress bar
Show estimated time remaining
Handle pause/cancel gracefully
❌ ANTI-PATTERNS (3)
No feedback until upload completes
Jumping progress or incorrect indicators
Blocking UI during upload
πŸ’» CODE HINTS (1)
xhr.upload.onprogress = (e) => updateBar(e.loaded / e.total)
SECURITY_AND_VIRUS_SCANNING
When accepting untrusted files from users
βœ… RULES (3)
Run antivirus or malware scan
Isolate uploads before processing
Reject based on denylist or scanning result
❌ ANTI-PATTERNS (3)
Processing file before scanning
Skipping scanning due to size
Failing open if scan errors
πŸ’» CODE HINTS (1)
clamd.scan(filePath).then(...)
RETRY_AND_RESUME_FAILED_UPLOADS
When network instability causes incomplete uploads
βœ… RULES (3)
Store partial upload state in client
Implement resume API with byte range
Provide retry UI on failure
❌ ANTI-PATTERNS (3)
Forcing full re-upload
Dropping uploads after timeout
Not informing user of partial progress
πŸ’» CODE HINTS (1)
headers: { 'Content-Range': 'bytes 1000-1999/4000' }
πŸ§ͺ VALIDATION
Upload files of different sizes and types. Interrupt uploads to test resumability. Verify scanning, backend merging, progress updates, and security logs.
#229Matrix 229 β€” File Download Matrix6 cells18 rules18 anti6 hints
Define how to handle file downloads from web or service endpoints, balancing user experience, security, and compatibility.
download_initiation_methodauthentication_and_authorizationfile_streaming_strategyprogress_and_status_feedbackcontent_disposition_controlcross_browser_and_device_support
DIRECT_DOWNLOAD_VIA_LINK
When file is public and static
βœ… RULES (3)
Use anchor tag with href
Set download attribute for filename
Avoid JS if unnecessary
❌ ANTI-PATTERNS (3)
Triggering downloads with complex JS unnecessarily
Forgetting content-type headers
No fallback for mobile
πŸ’» CODE HINTS (1)
<a href='/files/manual.pdf' download>Download</a>
AUTHENTICATED_DOWNLOAD_ENDPOINT
When file access is restricted to logged-in users
βœ… RULES (3)
Send token or session cookie
Use server redirect to blob URL if needed
Return 403 on unauthorized attempts
❌ ANTI-PATTERNS (3)
Embedding auth token in href
Serving files without auth headers
Allowing open file URLs to be indexed
πŸ’» CODE HINTS (1)
GET /secure/file.pdf with Authorization: Bearer...
STREAMING_LARGE_FILES
When downloading large or unbuffered files
βœ… RULES (3)
Use HTTP range headers or content streaming
Pipe file to response stream
Set appropriate caching and expiry headers
❌ ANTI-PATTERNS (3)
Buffering full file in memory
Not supporting resume on failure
Blocking event loop during read
πŸ’» CODE HINTS (1)
res.pipe(fs.createReadStream(path))
FEEDBACK_AND_CANCEL_IN_UI
When user downloads initiated file from web UI
βœ… RULES (3)
Show size and time estimates
Expose cancel button for async downloads
Handle retry logic on failure
❌ ANTI-PATTERNS (3)
No visual feedback for download
Blocking page UI while downloading
No cancel capability for long downloads
πŸ’» CODE HINTS (1)
xhr.onprogress = e => updateBar(e.loaded / e.total)
CONTENT_DISPOSITION_AND_FILENAME_CONTROL
When download file name or display behavior matters
βœ… RULES (3)
Set Content-Disposition header
Escape special characters in filename
Support inline display where applicable
❌ ANTI-PATTERNS (3)
Serving without filename header
Letting browser guess file type
Inconsistent file names across OS
πŸ’» CODE HINTS (1)
Content-Disposition: attachment; filename="report.csv"
MOBILE_DOWNLOAD_COMPATIBILITY
When supporting downloads on iOS/Android browsers
βœ… RULES (3)
Use blob URLs for JS-initiated files
Test on Safari and Chrome mobile
Avoid forcing download of unsupported formats
❌ ANTI-PATTERNS (3)
Using desktop-only download strategies
Blocking default behavior on anchor
Expecting file system access on mobile
πŸ’» CODE HINTS (1)
const link = URL.createObjectURL(blob); window.open(link)
πŸ§ͺ VALIDATION
Test downloads on various devices, with and without auth. Simulate large files, retry logic, filename variations, and stream/cancel behavior.
#230Matrix 230 β€” Chunking Matrix6 cells18 rules18 anti6 hints
Define strategies for splitting and reassembling data into manageable chunks to support large transfers, parallelism, and fault-tolerant processing.
chunking_strategychunk_size_determinationordering_and_indexingerror_handling_and_retriesreassembly_pointformat_standardization
FIXED_SIZE_CHUNKS_FOR_STREAMING
When transmitting large files over network
βœ… RULES (3)
Use fixed-size (e.g. 1MB) binary chunks
Align chunk boundaries with protocol limits
Track total size and number of parts
❌ ANTI-PATTERNS (3)
Sending entire file in one blob
Using inconsistent chunk sizes
Not signaling end-of-stream
πŸ’» CODE HINTS (1)
readStream().slice(i * size, (i+1) * size)
DYNAMIC_CHUNKING_FOR_VARIABLE_DATA
When input data size is unknown or highly variable
βœ… RULES (3)
Monitor stream pressure or latency
Adjust chunk size dynamically
Avoid over-fragmentation
❌ ANTI-PATTERNS (3)
Fixing chunk size without runtime feedback
Changing size mid-transmission without signaling
Letting metadata explode
πŸ’» CODE HINTS (1)
adjustChunkSize(latencyMetrics)
CHUNK_INDEXING_AND_SEQUENCE_IDS
When order of chunks must be preserved
βœ… RULES (3)
Include sequence ID in each chunk
Buffer out-of-order arrivals
Validate all parts before merge
❌ ANTI-PATTERNS (3)
Assuming in-order delivery
Merging on arrival without index
Lacking validation of completeness
πŸ’» CODE HINTS (1)
chunk = { seq: i, total: n, data: ... }
RETRYABLE_CHUNK_TRANSMISSION
When chunk delivery may fail in unreliable networks
βœ… RULES (3)
Track acknowledged chunks
Retry failed chunks only
Cap retry attempts and backoff
❌ ANTI-PATTERNS (3)
Retrying entire transfer on 1 chunk fail
Ignoring partial failure
Retry storms with no backoff
πŸ’» CODE HINTS (1)
if (!acked[chunk.id]) retry(chunk)
REASSEMBLY_AT_TARGET_LAYER
When chunks need to be joined into usable asset
βœ… RULES (3)
Select reassembly point: client, proxy, or server
Enforce strict schema for join
Checksum final result for integrity
❌ ANTI-PATTERNS (3)
Merging at unintended layer
Letting client send partial merge
Skipping verification step
πŸ’» CODE HINTS (1)
chunks.sort(bySeq).join(); verifyChecksum(fullFile)
CHUNK_FORMAT_AND_ENVELOPE
When transmitting chunks across diverse systems
βœ… RULES (3)
Wrap each chunk in standard envelope
Include metadata like ID, type, size
Support compression and encryption if needed
❌ ANTI-PATTERNS (3)
Sending raw binary with no framing
No versioning or content-type markers
Mixing multiple formats in stream
πŸ’» CODE HINTS (1)
{ header: { id, seq, type }, body: data }
πŸ§ͺ VALIDATION
Transmit files and records using chunked methods. Simulate network drops, reordering, and partial loss. Confirm retries, reassembly, and validation all succeed.
#231Matrix 231 β€” Background IO Matrix6 cells18 rules18 anti6 hints
Define how and when to perform background IO operations in client or server apps while minimizing disruption and ensuring consistency.
io_trigger_timingvisibility_scoperesource_priorityexecution_isolationcancellation_policyerror_tolerance_level
DEFERRED_PREFETCH_AFTER_IDLE
When preloading low-priority data during user inactivity
βœ… RULES (3)
Use requestIdleCallback or equivalent
Prefetch only when app is stable
Avoid contention with critical resources
❌ ANTI-PATTERNS (3)
Fetching aggressively during interaction
Blocking important UI updates
Prefetching without user need
πŸ’» CODE HINTS (1)
requestIdleCallback(() => fetch(...))
SILENT_BACKGROUND_SYNC_LOOP
When syncing data quietly in the background
βœ… RULES (3)
Throttle frequency to avoid load
Retry failed syncs with backoff
Pause on tab blur or low power mode
❌ ANTI-PATTERNS (3)
Constant polling without control
No error awareness or alerting
Updating state mid-user edit
πŸ’» CODE HINTS (1)
setInterval(syncData, 60000);
BACKGROUND_UPLOAD_WITH_QUEUEING
When uploading large or delayed content (e.g., images)
βœ… RULES (3)
Use job queue or indexedDB buffer
Provide offline persistence until success
Notify user on permanent failure
❌ ANTI-PATTERNS (3)
Uploading in main thread directly
Dropping uploads on tab close
Assuming success without confirmation
πŸ’» CODE HINTS (1)
enqueueUpload(blob); processQueue()
SERVER_SIDE_LOW_PRIORITY_JOBS
When processing IO-bound work that’s non-blocking (e.g., logging)
βœ… RULES (3)
Dispatch jobs to async worker or message queue
Ensure isolation from user-visible flow
Allow retries and monitoring
❌ ANTI-PATTERNS (3)
Running heavy IO inline with request
Blocking response on log flush
Failing silently on job failure
πŸ’» CODE HINTS (1)
queue.push('event_log', { ... })
PARALLEL_FETCH_WITH_PRIORITY_HINT
When loading multiple resources but some can be deprioritized
βœ… RULES (3)
Use fetch priority hints or custom scheduler
Abort or defer lower-priority on congestion
Track load order for observability
❌ ANTI-PATTERNS (3)
Loading everything with same priority
No backpressure management
Letting background fetch delay interactive UI
πŸ’» CODE HINTS (1)
fetch(url, { priority: 'low' })
CANCELABLE_BACKGROUND_IO_TASKS
When background IO may become irrelevant (e.g., user navigation)
βœ… RULES (3)
Use AbortController or worker termination
Listen for unmount/navigation events
Clean up pending requests on teardown
❌ ANTI-PATTERNS (3)
Letting background IO finish after user leaves
Leaking memory or open connections
Retrying canceled requests
πŸ’» CODE HINTS (1)
const ctrl = new AbortController(); ctrl.abort()
πŸ§ͺ VALIDATION
Test under load and network fluctuation. Confirm tasks defer, abort, and retry appropriately without blocking primary interaction paths.
#232Matrix 232 β€” Offline Mode Matrix6 cells18 rules18 anti6 hints
Define strategies for building reliable offline-first experiences in web or mobile apps, including caching, sync, and user feedback.
connectivity_detection_methoddata_persistence_strategyui_feedback_mechanismsync_defer_policyconflict_avoidancefallback_behavior
OFFLINE_DETECTION_AND_STATE_TRACKING
When user loses network connectivity mid-session
βœ… RULES (3)
Listen to navigator.onLine changes
Track last known online timestamp
Expose offline indicator in UI
❌ ANTI-PATTERNS (3)
Relying solely on failed requests
Assuming first failure = offline
Lack of visual state change
πŸ’» CODE HINTS (1)
window.addEventListener('offline', () => setAppOffline(true))
LOCAL_WRITE_CACHE_AND_BUFFER
When user performs write actions while offline
βœ… RULES (3)
Use IndexedDB or localStorage for persistence
Tag buffered writes with timestamp
Expose retry/resume API
❌ ANTI-PATTERNS (3)
Dropping writes on submit
Letting writes mutate state without commit
Blocking user input
πŸ’» CODE HINTS (1)
offlineQueue.push({ type: 'save', data })
UI_FEEDBACK_DURING_OFFLINE_MODE
When user interacts with app in offline state
βœ… RULES (3)
Show offline banner or badge
Disable or ghost blocked features
Display success state for locally buffered actions
❌ ANTI-PATTERNS (3)
Letting user think changes are live
Showing spinners that never resolve
Silent failures on input
πŸ’» CODE HINTS (1)
showBanner('You are offline. Changes will sync later.')
PRELOAD_AND_CACHE_FOR_OFFLINE_USE
When app should remain usable during connectivity loss
βœ… RULES (3)
Use service workers for asset caching
Prefetch user-specific data on login
Store recent records in local DB
❌ ANTI-PATTERNS (3)
Assuming CDNs are always reachable
No fallback for failed API calls
Caching UI without state
πŸ’» CODE HINTS (1)
caches.open('app').addAll(['/index.html', '/styles.css'])
RECONNECTION_AND_RECONCILIATION_POLICY
When app regains network connectivity
βœ… RULES (3)
Flush write queue in order
Refetch stale data
Detect and handle conflicts
❌ ANTI-PATTERNS (3)
Blind overwrite of server state
Ignoring locally changed records
Missing user-visible sync feedback
πŸ’» CODE HINTS (1)
processOfflineQueue(); refreshFromServer()
OFFLINE_MODE_FALLBACK_FLOW
When core features are unavailable due to offline state
βœ… RULES (3)
Redirect to offline-compatible views
Provide export/download option when sync fails
Explain limitations without blame
❌ ANTI-PATTERNS (3)
Crashing on unavailable API
Blank screen without explanation
Forcing logout during offline
πŸ’» CODE HINTS (1)
if (!online) navigate('/offline')
πŸ§ͺ VALIDATION
Simulate full offline state and interaction. Verify local buffering, visual cues, disabled flows, cache hit ratio, and recovery accuracy after reconnection.
#233Matrix 233 β€” Sync on Reconnect Matrix6 cells18 rules18 anti6 hints
Define strategies to safely synchronize state after reconnection, resolving conflicts and ensuring data integrity without user confusion.
reconnect_detectionsync_trigger_scopeconflict_resolution_methodsync_feedback_displaystaleness_detection_strategysync_retry_policy
RECONNECT_EVENT_HOOK
When app regains network connectivity
βœ… RULES (3)
Use navigator.onLine or socket.on('reconnect')
Debounce repeated reconnects
Verify backend state before applying queued actions
❌ ANTI-PATTERNS (3)
Firing sync before network stable
Flooding with retries on flapping connection
Letting offline data override newer remote state
πŸ’» CODE HINTS (1)
window.addEventListener('online', syncNow)
SCOPED_DATA_SYNC_STRATEGY
When only part of app data is affected
βœ… RULES (3)
Track dirty flags per entity type
Sync only recently changed views
Defer cold or unused views
❌ ANTI-PATTERNS (3)
Global revalidation on every reconnect
Syncing inactive modules unnecessarily
Failing to isolate active vs passive state
πŸ’» CODE HINTS (1)
sync({ scope: 'chat', changedOnly: true })
CONFLICT_RESOLUTION_WITH_VERSION_CHECK
When local data may be outdated or changed concurrently
βœ… RULES (3)
Compare updatedAt timestamps or content hashes
Show merge dialog or auto-resolve when safe
Log all conflicts for review
❌ ANTI-PATTERNS (3)
Last-write-wins on reconnect blindly
Applying both changes without detection
Ignoring silent divergence
πŸ’» CODE HINTS (1)
if (local.updatedAt < remote.updatedAt) overwrite()
USER_FEEDBACK_DURING_RECONNECT_SYNC
When data sync starts automatically on reconnect
βœ… RULES (3)
Show loading banner or sync status badge
Confirm when sync completes
Display count of updated or failed items
❌ ANTI-PATTERNS (3)
Running sync silently
Overwriting state without notice
Blocking UI with indefinite spinner
πŸ’» CODE HINTS (1)
setSyncStatus('Reconnecting...')
STALENESS_DETECTION_ON_RECONNECT
When resuming from long offline period
βœ… RULES (3)
Compare timestamps vs current server time
Mark stale items visually or reload silently
Purge cache if outside freshness threshold
❌ ANTI-PATTERNS (3)
Assuming cached data is still valid
No TTL or last-sync tracking
Reloading all data unnecessarily
πŸ’» CODE HINTS (1)
if (Date.now() - lastSync > threshold) refresh()
SYNC_RETRY_POLICY_ON_FAILURE
When reconnect sync fails due to server or conflict
βœ… RULES (3)
Backoff with increasing delay
Allow manual retry from user
Abort after max attempts and notify
❌ ANTI-PATTERNS (3)
Infinite retry loop
No logging of failure
Retrying same payload without correction
πŸ’» CODE HINTS (1)
retry(sync, { attempts: 3, backoff: true })
πŸ§ͺ VALIDATION
Simulate long disconnection and sync sequence. Introduce conflict, observe resolution, retry behavior, and user-facing feedback. Confirm data integrity and logging.
#234Matrix 234 β€” External Service Failure Matrix6 cells18 rules18 anti6 hints
Define how to handle partial or total failure of dependent services and APIs, including retries, user messaging, fallbacks, and incident logging.
failure_detection_methoduser_impact_scoperetry_and_backoff_strategyfallback_behaviorerror_reporting_and_loggingresilience_tuning
HTTP_5XX_RETRY_AND_BACKOFF
When upstream service returns 500-series errors
βœ… RULES (3)
Use capped exponential backoff
Log incident metadata
Surface degraded state to monitoring
❌ ANTI-PATTERNS (3)
Retrying instantly in loop
Assuming failure is always transient
Hiding error from ops dashboards
πŸ’» CODE HINTS (1)
retry(fetch, { backoff: true, max: 3 })
TIMEOUTS_AND_DEGRADATION_MODE
When external call times out after delay
βœ… RULES (3)
Set timeout ceiling (e.g., 3s)
Load degraded version or stub
Queue request retry in background
❌ ANTI-PATTERNS (3)
Waiting indefinitely
Freezing UI without feedback
Discarding response on timeout
πŸ’» CODE HINTS (1)
setTimeout(reject, 3000)
SERVICE_UNAVAILABLE_USER_MESSAGING
When external integration fails visibly to user
βœ… RULES (3)
Use plain language and suggest next steps
Offer retry or defer option
Track frequency of surfaced errors
❌ ANTI-PATTERNS (3)
Displaying raw exception message
Blaming third-party vendor
Showing generic failure without action
πŸ’» CODE HINTS (1)
showMessage('This feature is temporarily unavailable. Try later.')
FALLBACK_TO_CACHE_OR_STUB
When data cannot be loaded from API
βœ… RULES (3)
Use cache if valid
Show stub or loading skeleton with disclaimer
Mark view as stale or read-only
❌ ANTI-PATTERNS (3)
Showing blank view
Crashing app on missing data
Pretending data is current
πŸ’» CODE HINTS (1)
if (!liveData) render(cachedData)
DEGRADED_STATE_LOGGING_AND_ALERTING
When external failures affect UX or business flow
βœ… RULES (3)
Log error category and timestamp
Attach user/session metadata
Trigger alerts for SLA violation
❌ ANTI-PATTERNS (3)
Relying on silent failover
Logging only after retries exhausted
Missing traceability to UI impact
πŸ’» CODE HINTS (1)
log.error('partner_api_down', { user, route, severity: 'major' })
RESILIENCE_TUNING_PER_SERVICE_TIER
When integrating with multiple 3rd-party APIs
βœ… RULES (3)
Classify partners as critical vs optional
Use circuit breakers for flaky APIs
Cap retry intensity based on risk
❌ ANTI-PATTERNS (3)
Applying same logic to all services
Keeping broken integrations silently active
Failing open on sensitive endpoints
πŸ’» CODE HINTS (1)
if (partner.tier === 'low') disableTemporarily()
πŸ§ͺ VALIDATION
Simulate partner failure conditions (timeouts, 503s). Confirm retries, fallback display, logging behavior, and alert thresholds per service tier.
#235Matrix 235 β€” Fallback Integration Matrix6 cells18 rules18 anti6 hints
Define how and when to use fallback services or methods when primary integrations fail, including compatibility, switching logic, and risk management.
fallback_trigger_conditionswitching_strategycompatibility_alignmentuser_awareness_levellogging_and_traceabilitysecurity_and_data_consistency
MANUAL_USER_INITIATED_FALLBACK
When user sees failure and opts to retry with alternative
βœ… RULES (3)
Offer retry with fallback option in UI
Label alternate provider or method
Preserve user state across attempts
❌ ANTI-PATTERNS (3)
Switching silently
Forcing fallback without context
Resetting form on retry
πŸ’» CODE HINTS (1)
showFallbackCTA('Try alternate method')
AUTOMATIC_SWITCH_ON_STATUS_CODE
When primary API returns error and backup is available
βœ… RULES (3)
Detect 503, 504, or timeout
Switch to backup endpoint programmatically
Log failover reason and timing
❌ ANTI-PATTERNS (3)
Retrying primary too long before fallback
Missing logging of which provider served data
No alert on repeated fallback
πŸ’» CODE HINTS (1)
if (status === 503) use(fallbackProvider)
DATA_FORMAT_ALIGNMENT_LAYER
When fallback source has different payload format
βœ… RULES (3)
Map fields to internal schema
Handle missing or renamed fields
Log data source for auditing
❌ ANTI-PATTERNS (3)
Assuming identical structure
Propagating fallback-specific quirks
Skipping schema validation
πŸ’» CODE HINTS (1)
transform(fallbackResponse).toStandardModel()
FALLBACK_USAGE_FEEDBACK
When user interacts with fallback data
βœ… RULES (3)
Label fallback data in UI (when critical)
Log fallback path to client logs
Allow retry of primary if restored
❌ ANTI-PATTERNS (3)
Pretending fallback = original
Blocking user retry
Exposing fallback path unnecessarily
πŸ’» CODE HINTS (1)
tagContent('source:mirror-provider')
TEMPORARY_CACHE_FILL_FROM_FALLBACK
When fallback is slower or has quota limits
βœ… RULES (3)
Write-through to local cache
Set short TTL for fallback content
Log that cache origin is fallback
❌ ANTI-PATTERNS (3)
Always fetching fallback for same content
Caching stale or unverified data
Treating fallback as permanent source
πŸ’» CODE HINTS (1)
fallbackResult.cached = true; cache.set(key, fallbackResult)
DATA_ISOLATION_AND_INTEGRITY_CHECKS
When fallback source may be less trusted
βœ… RULES (3)
Run strict validation on fallback input
Flag entries with origin tag
Avoid merge into core dataset without review
❌ ANTI-PATTERNS (3)
Letting fallback data flow to persistent store directly
Failing to isolate riskier sources
Trusting fallback uptime blindly
πŸ’» CODE HINTS (1)
if (source === 'fallback') validateStrict(fallbackData)
πŸ§ͺ VALIDATION
Trigger failover to fallback in test scenarios. Check user awareness, data integrity, cache effect, and reversion behavior after primary restoration.
#236Matrix 236 β€” Contract Testing Matrix6 cells18 rules18 anti6 hints
Define how to ensure stability and trust in service contracts between producers and consumers, across build-time and run-time boundaries.
contract_definition_locationconsumer_validation_timingproducer_enforcement_strategyversioning_and_compatibilitytest_environment_alignmentfailure_handling_protocol
CONSUMER_DRIVEN_CONTRACTS
When frontend or API consumer defines expectations
βœ… RULES (3)
Define request/response shape in consumer repo
Use mocks or simulators for testing
Push contract to central registry
❌ ANTI-PATTERNS (3)
Relying on ad-hoc assumptions
Skipping edge case definition
No sharing back to producer
πŸ’» CODE HINTS (1)
pact.define('GET /user', { expectedResponse: ... })
PRODUCER_CONTRACT_VALIDATION_PIPELINE
When backend validates contracts against test data
βœ… RULES (3)
Pull consumer contracts in CI
Run contract verifier on endpoint mocks
Fail build if regression detected
❌ ANTI-PATTERNS (3)
Testing only during staging
Manual verification
Assuming contract coverage
πŸ’» CODE HINTS (1)
pactVerifier.verify({ provider: 'API' })
CONTRACT_VERSIONING_AND_COMPAT_LAYER
When multiple consumers rely on different contract shapes
βœ… RULES (3)
Tag contract versions
Deprecate with policy timeline
Gate incompatible changes behind version
❌ ANTI-PATTERNS (3)
Overwriting contract in place
Breaking consumers silently
No version rollback mechanism
πŸ’» CODE HINTS (1)
contract.setVersion('v2')
RUNTIME_SCHEMA_ENFORCEMENT
When runtime requests/responses must match contract
βœ… RULES (3)
Validate payloads against schema at runtime
Log and quarantine violations
Allow opt-in strict mode for critical flows
❌ ANTI-PATTERNS (3)
Allowing unexpected fields silently
Logging only without blocking
No alerting on schema mismatch
πŸ’» CODE HINTS (1)
ajv.validate(schema, response)
SHARED_SANDBOX_AND_FAKE_SERVICES
When consumer and producer test in isolated environments
βœ… RULES (3)
Deploy fake provider/consumer for test suite
Mount shared sandbox routes
Tag tests with contract version
❌ ANTI-PATTERNS (3)
Testing against real prod endpoints
No consistency between test data
Breaking contract during QA cycle
πŸ’» CODE HINTS (1)
mountFakeProvider('/sandbox/api')
FAILURE_POLICY_AND_RECOVERY
When contract test fails in CI or runtime
βœ… RULES (3)
Block builds on regressions
Alert relevant teams on runtime issues
Allow override with justification
❌ ANTI-PATTERNS (3)
Silently skipping failing tests
No link between failure and code owner
Allowing override without trace
πŸ’» CODE HINTS (1)
requireJustification('override_contract_violation')
πŸ§ͺ VALIDATION
Simulate breaking and non-breaking changes across versions. Run contract suite in CI and runtime. Observe failure behavior, rollback, and alert propagation.
#237Matrix 237 β€” API Versioning Matrix6 cells18 rules18 anti6 hints
Define strategies for maintaining, upgrading, and deprecating versions of APIs while preserving backward compatibility and clear communication.
version_locationchange_type_classificationcompatibility_policyconsumer_migration_supportdeprecation_communicationruntime_enforcement
URL_VERSIONING_CONVENTION
When versioning via API endpoint path
βœ… RULES (3)
Use /v1/, /v2/ in base path
Avoid mixing multiple versions in same path
Reflect contract differences in docs
❌ ANTI-PATTERNS (3)
Hiding version in query string only
Switching contract under same URL
Failing to version breaking changes
πŸ’» CODE HINTS (1)
GET /api/v2/users
SEMVER_FOR_CONTRACT_CHANGES
When tracking schema and behavior over time
βœ… RULES (3)
Follow MAJOR.MINOR.PATCH format
Increment MAJOR for breaking changes
Document changes per release
❌ ANTI-PATTERNS (3)
Skipping version bump on behavior shift
Letting PATCH change contract
Omitting version from changelog
πŸ’» CODE HINTS (1)
api.version = '2.1.0'
BACKWARD_COMPATIBILITY_ENFORCEMENT
When deploying updates to existing APIs
βœ… RULES (3)
Validate schema compatibility
Use feature flags for conditional behavior
Deprecate gradually with shadow mode
❌ ANTI-PATTERNS (3)
Changing required fields abruptly
Removing properties without notice
Breaking consumers during rollout
πŸ’» CODE HINTS (1)
if (version >= 2) useNewSchema()
CONSUMER_VERSION_NEGOTIATION
When different clients support different API versions
βœ… RULES (3)
Allow client to specify version via header or URL
Respond with compatible version or error
Log version usage statistics
❌ ANTI-PATTERNS (3)
Forcing latest version on all clients
Ignoring version in request
Failing silently on mismatch
πŸ’» CODE HINTS (1)
Accept: application/vnd.myapi.v2+json
DEPRECATION_ANNOUNCEMENT_CHANNELS
When sunsetting an older API version
βœ… RULES (3)
Announce deprecation in response headers
Email affected partners with timeline
Provide upgrade migration guide
❌ ANTI-PATTERNS (3)
Deprecating silently
Changing TTL without notice
Removing version without fallback
πŸ’» CODE HINTS (1)
Deprecation: true Sunset: 2024-12-31
VERSION_BLOCKING_AND ROUTING
When unsupported or risky version is requested
βœ… RULES (3)
Reject unknown versions with HTTP 400
Route traffic based on version
Log rejected version attempts
❌ ANTI-PATTERNS (3)
Defaulting silently to latest
Processing invalid versions without warning
Mismatched logic between routing and docs
πŸ’» CODE HINTS (1)
if (!supported(version)) return 400
πŸ§ͺ VALIDATION
Simulate versioned calls from multiple consumers. Validate correct fallback, migration notice, schema enforcement, and backward-compatible logic.
#238Matrix 238 β€” Integration Security Matrix6 cells18 rules18 anti6 hints
Define security best practices for integrating with third-party services and APIs, covering authentication, authorization, validation, and trust boundaries.
auth_methodscope_granularityinput_validation_layersecret_handlingtrust_boundary_isolationlogging_and_alerting_sensitivity
TOKEN_BASED_AUTH_WITH_SCOPES
When authenticating outbound API requests
βœ… RULES (3)
Use OAuth2 or JWT with defined scopes
Rotate tokens regularly
Avoid static API keys when possible
❌ ANTI-PATTERNS (3)
Embedding secrets in client-side code
Using root tokens for all access
Failing to expire credentials
πŸ’» CODE HINTS (1)
Authorization: Bearer <scoped_token>
ENDPOINT_WHITELISTING_AND_FIREWALL_RULES
When calling sensitive services
βœ… RULES (3)
Apply IP allowlists
Use VPC or private service access
Log all denied egress attempts
❌ ANTI-PATTERNS (3)
Allowing open outbound internet
Using DNS names without verification
No restriction on port or protocol
πŸ’» CODE HINTS (1)
egress.allow = ['api.trusted.com']
INPUT_VALIDATION_ON_ALL_INTEGRATION_PATHS
When accepting input from integrated systems
βœ… RULES (3)
Validate payloads against schema
Sanitize user-controlled inputs
Enforce max lengths and enum values
❌ ANTI-PATTERNS (3)
Assuming internal systems are trusted
Validating only at UI layer
Not checking optional nested fields
πŸ’» CODE HINTS (1)
validate(req.body, integrationSchema)
SECRET_STORAGE_AND_ROTATION_POLICY
When handling shared secrets with partners
βœ… RULES (3)
Store secrets in vault or secret manager
Use per-integration keys
Rotate on interval or upon suspicion
❌ ANTI-PATTERNS (3)
Hardcoding secrets in source
Sharing same secret across tenants
Lack of audit trail for access
πŸ’» CODE HINTS (1)
secrets.get('partner-api-key')
BOUNDARY_ISOLATION_AND_SANDBOXING
When invoking untrusted or variable services
βœ… RULES (3)
Use execution sandbox or proxy isolation
Run unknown code in jailed environment
Separate integration from core services
❌ ANTI-PATTERNS (3)
Calling external code from core threads
No resource limits or quotas
Combining trusted and untrusted data paths
πŸ’» CODE HINTS (1)
invokeInSandbox(fn, payload)
INTEGRATION_LOGGING_AND_ALERTING_HYGIENE
When auditing external calls and responses
βœ… RULES (3)
Scrub PII and credentials from logs
Sample logs based on risk
Trigger alerts on suspicious patterns
❌ ANTI-PATTERNS (3)
Logging full request/response by default
Storing long-lived tokens in logs
No alerting on repeated failures
πŸ’» CODE HINTS (1)
log.info('partner_response', sanitize(response))
πŸ§ͺ VALIDATION
Perform integration scans. Trigger failures and analyze logs, alerts, and token scope enforcement. Verify secrets are stored, rotated, and protected.
#239Matrix 239 β€” Secrets Handling Matrix6 cells18 rules18 anti6 hints
Define how to manage secrets (API keys, tokens, credentials) across environments and services securely, minimizing risk of leakage or misuse.
secret_sourcescope_and_lifetimestorage_locationruntime_access_controlrotation_policyleak_detection_mechanism
ENV_VAR_SECRETS_IN_BACKEND_ONLY
When accessing static secrets on server side
βœ… RULES (3)
Inject via environment variables
Exclude from build output
Log usage without value exposure
❌ ANTI-PATTERNS (3)
Putting secrets in config.js
Referencing env vars in client bundles
Logging full secret string
πŸ’» CODE HINTS (1)
process.env.STRIPE_SECRET_KEY
SECRET_MANAGER_WITH_ACCESS_POLICIES
When storing dynamic secrets across microservices
βœ… RULES (3)
Use HashiCorp Vault, AWS Secrets Manager, or similar
Define role-based access per service
Log access requests and denials
❌ ANTI-PATTERNS (3)
Using file-based secrets in production
Letting all services access all secrets
Skipping denial audits
πŸ’» CODE HINTS (1)
vault.read('service/db-creds')
TEMPORARY_SESSIONS_AND_EPHEMERAL_KEYS
When authenticating users or one-time flows
βœ… RULES (3)
Expire keys within minutes
Restrict usage to IP or session context
Store in memory or secure cookie
❌ ANTI-PATTERNS (3)
Long-lived session tokens
Tokens that work across browsers
Writing temp keys to disk
πŸ’» CODE HINTS (1)
setCookie('session', token, { maxAge: 300 })
ROLE_BASED_RUNTIME_ACCESS
When services or scripts request secret at runtime
βœ… RULES (3)
Use runtime identity or IAM roles
Tag secrets with consumer role
Block access outside policy context
❌ ANTI-PATTERNS (3)
Granting broad access via root creds
No enforcement of runtime identity
Caching secrets in global scope
πŸ’» CODE HINTS (1)
assumeRole('upload-worker')
SECRET_ROTATION_AND_REVOCATION_HOOKS
When secrets need to be changed periodically
βœ… RULES (3)
Define TTL and rotation window
Notify affected services
Revoke old version on use
❌ ANTI-PATTERNS (3)
Manually rotating in emergencies
Letting old secrets linger post-deploy
Skipping alert on use of expired key
πŸ’» CODE HINTS (1)
rotateSecret('db-token') β†’ notify(['app1','app2'])
LEAK_DETECTION_AND_SCAN_PIPELINES
When secrets may accidentally leak into code or logs
βœ… RULES (3)
Scan git commits for patterns
Alert on regex hits in logs
Invalidate exposed secrets immediately
❌ ANTI-PATTERNS (3)
Relying solely on reviews
Skipping post-commit scans
Keeping exposed secrets active
πŸ’» CODE HINTS (1)
gitleaks --repo ./src
πŸ§ͺ VALIDATION
Simulate secret usage across all flows. Rotate keys, scan for leaks, and verify access control and isolation. Audit log presence and security posture across environments.
#240Matrix 240 β€” IO Observability Matrix6 cells18 rules18 anti6 hints
Define strategies for tracking, measuring, and troubleshooting IO operations across internal and external systems, with visibility into flow, timing, and failures.
telemetry_capture_pointmetrics_collectedcorrelation_and_traceabilityaggregation_scopealerting_and_thresholdsdeveloper_accessibility
API_LATENCY_AND_THROUGHPUT_METRICS
When monitoring external API performance
βœ… RULES (3)
Collect avg, p95, max latency
Measure requests per minute
Tag by endpoint and status
❌ ANTI-PATTERNS (3)
Logging only failures
Skipping high-percentile latency
Ignoring burst traffic
πŸ’» CODE HINTS (1)
recordMetric('api.latency', { path, p95 })
DISTRIBUTED_TRACING_ACROSS_SERVICES
When debugging multi-service IO path
βœ… RULES (3)
Inject trace ID in all outbound requests
Use consistent headers like X-Request-ID
Log timing at each hop
❌ ANTI-PATTERNS (3)
Creating new ID per hop
No parent-child span relationships
Logging without ID linkage
πŸ’» CODE HINTS (1)
span = tracer.startSpan('db.query')
REALTIME_FAILURE_RATE_ALERTING
When error rate spikes suddenly
βœ… RULES (3)
Monitor 4xx/5xx rate per endpoint
Set dynamic thresholds with baseline
Include contextual metadata in alert
❌ ANTI-PATTERNS (3)
Alerting only on total downtime
No segmentation by service
Ignoring retry/fallback events
πŸ’» CODE HINTS (1)
if errorRate(path) > threshold then alertTeam(path)
AGGREGATED_IO_HEALTH_DASHBOARDS
When product managers and ops need global view
βœ… RULES (3)
Display latency, error, retry, fallback rates
Segment by integration domain
Update in near real-time
❌ ANTI-PATTERNS (3)
Only raw log access without graphs
Dashboards for developers only
No business-level abstraction
πŸ’» CODE HINTS (1)
Grafana.panel('IO Heatmap')
DEVELOPER_QUERY_AND TRACE_TOOLS
When investigating integration issues locally
βœ… RULES (3)
Expose searchable logs via dev portal
Provide CLI access with filters
Tag with team or feature owner
❌ ANTI-PATTERNS (3)
Only ops have observability tools
No link from error to trace
No access in staging/dev
πŸ’» CODE HINTS (1)
trace.lookup({ spanId }).open()
SYNTHETIC_PROBES_AND_HEALTH_CHECKS
When needing baseline monitoring of integrations
βœ… RULES (3)
Run synthetic checks hourly
Use real endpoints with test data
Track failures and performance over time
❌ ANTI-PATTERNS (3)
Only checking availability, not behavior
No test coverage of fallback path
Treating synthetic pass = user success
πŸ’» CODE HINTS (1)
probe('/search?q=test').expect(200)
πŸ§ͺ VALIDATION
Simulate load, latency, and failure. Confirm traces span hops, alerts trigger on spike, and dashboards reflect real IO state. Trace from user event to service response.
β–Ό πŸ” L9 β€” Security 30 matrices
#241Authentication Matrix6 cells12 rules10 anti6 hints
Determines how users are authenticated β€” identity verification methods, token management, session handling, and multi-factor strategies.
auth_methodtoken_typesession_strategymfa_level
auth_001
When using basic login via username and password, store session in a secure, HttpOnly cookie on the server.
βœ… RULES (2)
Validate credentials against hashed password store
Set cookie with HttpOnly, Secure, SameSite=strict
❌ ANTI-PATTERNS (2)
Storing password in plaintext
Using JavaScript-accessible cookies for session
πŸ’» CODE HINTS (1)
Set-Cookie: sessionId=abc; HttpOnly; Secure; SameSite=Strict
auth_002
When using JWT for stateless authentication, issue short-lived access tokens signed with private key.
βœ… RULES (2)
Sign JWTs with strong secret or asymmetric key
Set expiration (e.g. 15m) and validate on each request
❌ ANTI-PATTERNS (2)
Using long-lived JWTs with no expiration
Storing JWT in localStorage without refresh mechanism
πŸ’» CODE HINTS (1)
Authorization: Bearer eyJhbGciOi...
auth_003
When using OAuth2 or OIDC, use the ID token for identity and access token for resource access.
βœ… RULES (2)
Validate ID token signature and issuer
Check nonce, audience, expiration
❌ ANTI-PATTERNS (2)
Trusting ID token without validation
Mixing ID and access token usage
πŸ’» CODE HINTS (1)
id_token = decode(token); validateClaims(id_token);
auth_004
When using refresh tokens, implement rotation to prevent reuse and token theft.
βœ… RULES (2)
Store refresh token securely (e.g. HttpOnly cookie)
Invalidate old token on use
❌ ANTI-PATTERNS (2)
Allowing reuse of old refresh tokens
Not binding refresh token to client or session
πŸ’» CODE HINTS (1)
POST /refresh β†’ issue new refresh + access token
auth_005
When adding TOTP-based MFA, require second factor before issuing access token.
βœ… RULES (2)
Validate TOTP code before granting token
Allow backup codes or re-enrollment path
❌ ANTI-PATTERNS (1)
Allowing login with just password even when MFA is enabled
πŸ’» CODE HINTS (1)
verifyTOTP(user.secret, input.code)
auth_006
When using WebAuthn for passwordless or MFA login, bind ID token issuance to WebAuthn challenge response.
βœ… RULES (2)
Use WebAuthn API to verify user presence and credential
Issue ID token only on success
❌ ANTI-PATTERNS (1)
Issuing tokens before verifying WebAuthn assertion
πŸ’» CODE HINTS (1)
navigator.credentials.get({ publicKey: ... })
πŸ§ͺ VALIDATION
Verify: auth methods properly validate identity, tokens are scoped and rotated, sessions isolated per user, MFA enforced per policy, token claims verified at each step.
#242Authorization Matrix6 cells12 rules6 anti6 hints
Determines who can access what β€” role-based, permission-based, and attribute-based access control for sensitive data.
authz_modelgranularityenforcement_pointpolicy_storage
authz_001
When restricting access by user role (e.g. admin, editor), define role hierarchy and attach enforcement to route middleware.
βœ… RULES (2)
Map roles to groups of endpoints or actions
Use middleware to check req.user.role before access
❌ ANTI-PATTERNS (1)
Duplicating role checks in multiple controller methods
πŸ’» CODE HINTS (1)
if (user.role !== 'admin') return 403
authz_002
When needing per-action access control (e.g. create, edit, delete), assign permissions per action and validate in handler.
βœ… RULES (2)
Define permission matrix per role
Check specific action permission per user
❌ ANTI-PATTERNS (1)
Granting full access based only on role without per-action validation
πŸ’» CODE HINTS (1)
if (!user.permissions.includes('DELETE_DOCUMENT')) return 403
authz_003
When access depends on context (e.g. location, time, device), evaluate dynamic attributes before granting access.
βœ… RULES (2)
Fetch user attributes and runtime context
Use policy engine to evaluate access rule
❌ ANTI-PATTERNS (1)
Relying solely on static roles when context is critical
πŸ’» CODE HINTS (1)
if (ctx.location === 'HQ' && ctx.time < 18:00) allow
authz_004
When access to resources varies per user (e.g. document owner vs. viewer), enforce authorization at document-level.
βœ… RULES (2)
Store document.ownerId or ACL
Verify user.id matches or is in ACL before access
❌ ANTI-PATTERNS (1)
Allowing all authenticated users to read/write any document
πŸ’» CODE HINTS (1)
if (doc.ownerId !== user.id) return 403
authz_005
When rendering UI elements (e.g. buttons, menu items), control visibility based on role permissions on the client.
βœ… RULES (2)
Send role or permission data in auth payload
Conditionally render components by user.role
❌ ANTI-PATTERNS (1)
Showing admin UI actions to non-admins without disabling functionality
πŸ’» CODE HINTS (1)
{user.role === 'admin' && <DeleteButton />}
authz_006
When enforcing authorization server-side, apply middleware that loads policies from a centralized store (e.g. OPA, DB).
βœ… RULES (2)
Keep policies external to app logic
Middleware fetches and checks access policy per request
❌ ANTI-PATTERNS (1)
Hardcoding access rules in controller files
πŸ’» CODE HINTS (1)
middleware: checkAccess(user, route, method)
πŸ§ͺ VALIDATION
Verify: role checks are enforced consistently, permissions mapped per action, attributes used for contextual auth, per-resource rules respected, UI elements gated by role, and middleware applies central policy storage.
#243Identity Propagation Matrix6 cells18 rules18 anti6 hints
Define how to propagate authenticated user identity across distributed components securely and consistently.
identity_token_formattransport_methodscope_bindingexpiration_and_renewaltrust_chain_verificationtoken_forwarding_policy
SIGNED_JWT_WITH_EXPIRATION
When user identity must cross services over HTTP
βœ… RULES (3)
Use JWT signed with private key
Include 'exp' claim for short TTL
Validate signature and audience at each hop
❌ ANTI-PATTERNS (3)
Using unsigned tokens
Sharing long-lived tokens
Ignoring 'aud' mismatch
πŸ’» CODE HINTS (1)
jwt.sign(payload, key, { expiresIn: '15m' })
BEARER_TOKEN_OVER_MUTUAL_TLS
When services communicate inside zero-trust network
βœ… RULES (3)
Use HTTPS with client certs
Attach token in Authorization header
Reject if TLS not mutual or cert unverified
❌ ANTI-PATTERNS (3)
Sending tokens over plain HTTP
Skipping cert validation
Reusing access token across connections
πŸ’» CODE HINTS (1)
curl -H 'Authorization: Bearer ...' --cert client.pem
BOUND_SCOPED_TOKENS_FOR_RESOURCE_LIMITATION
When services should access only subset of user rights
βœ… RULES (3)
Include 'scope' claim in token
Restrict token generation to allowed scopes
Validate scope before action
❌ ANTI-PATTERNS (3)
Omitting scopes from access token
Allowing wildcard scopes
Not validating scope on backend
πŸ’» CODE HINTS (1)
token.scope = ['read:invoices']
PER_HOP_VERIFICATION_AND_AUDIENCE_CONTROL
When multiple intermediaries forward identity
βœ… RULES (3)
Set 'aud' claim for target service
Verify 'iss' and 'aud' at each boundary
Avoid broad trust of intermediate hops
❌ ANTI-PATTERNS (3)
Blindly forwarding tokens
Accepting tokens with mismatched audience
Allowing token use by unintended party
πŸ’» CODE HINTS (1)
verify(token, { audience: 'service-b' })
TOKEN_CHAIN_OBSERVABILITY
When troubleshooting distributed identity flow
βœ… RULES (3)
Log token IDs and trace context
Correlate identity headers with spans
Expose end-to-end identity in debug tools
❌ ANTI-PATTERNS (3)
Logging full tokens
No traceability across services
Unverifiable source of action
πŸ’» CODE HINTS (1)
logger.debug({ traceId, sub: token.sub })
FORWARDING_POLICY_AND_DELEGATION_CONSENT
When services delegate on behalf of users
βœ… RULES (3)
Mark delegation in token claims
Require consent or service-to-service policy
Audit delegation context
❌ ANTI-PATTERNS (3)
Forwarding tokens without disclosure
Assuming all services may act as user
Allowing lateral privilege escalation
πŸ’» CODE HINTS (1)
token.delegated_by = 'svc-a'
πŸ§ͺ VALIDATION
Pass identity across multiple service hops. Verify token validation, traceability, audience match, and delegation constraints. Simulate misrouting and token tampering.
#244Matrix 244 β€” Session Management Matrix6 cells18 rules18 anti6 hints
Define strategies for secure and consistent session management in web and distributed applications.
session_identifier_typestorage_locationexpiration_policyrevocation_strategydevice_and_context_bindingsecurity_attributes
HTTP_ONLY_COOKIE_SESSIONS
When managing sessions in browser-based clients
βœ… RULES (3)
Set HttpOnly and Secure flags
Use SameSite attribute
Rotate session ID on login
❌ ANTI-PATTERNS (3)
Storing tokens in localStorage
Allowing cross-site session reuse
No invalidation on logout
πŸ’» CODE HINTS (1)
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict
IN_MEMORY_TOKEN_SESSIONS
When building mobile or single-page apps
βœ… RULES (3)
Avoid persistence to disk
Wipe on tab close or logout
Use refresh tokens with short TTL
❌ ANTI-PATTERNS (3)
Saving tokens in indexedDB or persistent caches
Auto-login with stale credentials
No wipe on browser close
πŸ’» CODE HINTS (1)
sessionStorage.setItem('token', accessToken)
SESSION_EXPIRATION_AND_IDLE_TIMEOUT
When enforcing limits on session lifetime
βœ… RULES (3)
Expire session after fixed TTL
Use idle timeout to shorten window
Prompt user before auto-logout
❌ ANTI-PATTERNS (3)
Allowing infinite sessions
Resetting expiration on background traffic
No visible countdown or warning
πŸ’» CODE HINTS (1)
setTimeout(logout, 30 * 60 * 1000)
CENTRAL_SESSION_REVOCATION
When needing to terminate session remotely
βœ… RULES (3)
Store sessions server-side or as opaque tokens
Check revocation list on access
Log and notify on revocation
❌ ANTI-PATTERNS (3)
Using stateless JWTs without revocation
Only clearing cookies locally
Not reflecting logout across tabs
πŸ’» CODE HINTS (1)
session.revoke(sessionId)
DEVICE_AND_CONTEXT_BINDING
When strengthening session validation
βœ… RULES (3)
Bind session to IP/user-agent/device fingerprint
Revalidate on context change
Invalidate on suspicious geo movement
❌ ANTI-PATTERNS (3)
Allowing session reuse across IP jumps
Ignoring device fingerprint
Not reacting to login from distant location
πŸ’» CODE HINTS (1)
if (fingerprint !== stored) logout()
SESSION_SECURITY_ATTRIBUTES
When issuing session tokens
βœ… RULES (3)
Use Secure and HttpOnly flags
Set SameSite=Strict or Lax
Validate token on every request
❌ ANTI-PATTERNS (3)
Sending session tokens in URL
No protection against CSRF
Overly permissive cookie scope
πŸ’» CODE HINTS (1)
Set-Cookie: sid=xyz; Secure; HttpOnly; SameSite=Strict
πŸ§ͺ VALIDATION
Simulate login, inactivity, token theft, and remote logout. Verify cookie flags, session invalidation, and user-visible behaviors.
#245Token Lifecycle Matrix6 cells12 rules6 anti6 hints
Determines how security tokens (access, refresh, API keys) are created, stored, rotated, revoked, and expired across their full lifecycle.
token_typestorage_locationrotation_policyrevocation
token_001
When issuing access tokens for APIs, use short-lived JWTs (e.g. 15 minutes) to reduce attack window on compromise.
βœ… RULES (2)
Set token lifetime to 15 minutes or less
Include 'exp' claim and verify it on every request
❌ ANTI-PATTERNS (1)
Using long-lived access tokens without rotation
πŸ’» CODE HINTS (1)
const token = jwt.sign(payload, secret, { expiresIn: '15m' })
token_002
When storing refresh tokens, use HttpOnly cookies to avoid access from JavaScript and mitigate XSS risk.
βœ… RULES (2)
Set HttpOnly and Secure flags on cookie
Do not store in localStorage or sessionStorage
❌ ANTI-PATTERNS (1)
Storing refresh tokens in localStorage (vulnerable to XSS)
πŸ’» CODE HINTS (1)
Set-Cookie: refresh=...; HttpOnly; Secure
token_003
When exchanging a refresh token for new tokens, issue a new refresh token and invalidate the old one.
βœ… RULES (2)
Implement one-time use refresh tokens
Store token family ID and revoke all on suspicious reuse
❌ ANTI-PATTERNS (1)
Allowing same refresh token to be reused multiple times
πŸ’» CODE HINTS (1)
rotateRefreshToken(oldToken) β†’ issueNew(), revoke(oldToken)
token_004
When managing API keys, store a hashed version only β€” expose only a prefix to users for reference.
βœ… RULES (2)
Store API key hash using strong one-way hash (e.g. SHA-256)
Expose first 6–8 characters to user as identifier
❌ ANTI-PATTERNS (1)
Storing plaintext API keys in database
πŸ’» CODE HINTS (1)
storeHash = sha256(apiKey); shownPrefix = apiKey.slice(0, 8);
token_005
When revoking a token before expiry (e.g. user logout), add it to a blacklist or increase token version to invalidate.
βœ… RULES (2)
Track blacklisted token IDs or maintain user token version
Reject tokens with older version or in blacklist
❌ ANTI-PATTERNS (1)
Assuming JWT can't be revoked because it's stateless
πŸ’» CODE HINTS (1)
if (token.jti in blacklist || token.version < user.version) reject
token_006
When processing requests, enforce expiry by validating token timestamps at middleware level.
βœ… RULES (2)
Check 'exp' and 'nbf' claims in middleware
Reject requests with expired or future-use tokens
❌ ANTI-PATTERNS (1)
Letting expired tokens access resources due to missing checks
πŸ’» CODE HINTS (1)
if (now > token.exp || now < token.nbf) throw Unauthorized
πŸ§ͺ VALIDATION
Verify: tokens expire based on 'exp', refresh tokens rotate on use, revoked tokens blacklisted or version bumped, access tokens are short-lived, API keys stored as hash, and refresh tokens not accessible to JS.
#246Matrix 246 β€” Secrets Storage Matrix6 cells18 rules18 anti6 hints
Define secure storage practices for credentials, tokens, API keys, and other secrets used in software systems.
storage_mediumencryption_at_restaccess_control_policyrotation_mechanismauditabilityruntime_secret_loading
SECRETS_IN_MANAGED_SECRET_MANAGER
When storing secrets in cloud infrastructure
βœ… RULES (3)
Use AWS Secrets Manager, Vault, or equivalent
Enable automatic rotation
Control access via IAM or role-based permissions
❌ ANTI-PATTERNS (3)
Hardcoding secrets in source
Using plaintext files for prod credentials
No control over read access
πŸ’» CODE HINTS (1)
secrets.get('prod/db/password')
FILE_SYSTEM_STORAGE_WITH_OS_PERMISSIONS
When secrets must reside on disk temporarily
βœ… RULES (3)
Restrict file ownership and mode (e.g., 600)
Avoid shared folders or tempfs
Delete after use when possible
❌ ANTI-PATTERNS (3)
World-readable secret files
Secrets left in /tmp or shared mounts
Assuming container boundaries are sufficient
πŸ’» CODE HINTS (1)
chmod 600 .env && chown app:app .env
ENCRYPTION_WITH_KEY_MANAGEMENT
When encrypting secrets at rest
βœ… RULES (3)
Encrypt secrets with KMS or HSM
Store encryption metadata separately
Rotate data keys regularly
❌ ANTI-PATTERNS (3)
Encrypting with hardcoded password
Storing key with encrypted data
No rotation policy
πŸ’» CODE HINTS (1)
kms.encrypt(data, { keyId })
SECRETS_ROTATION_AND_EXPIRATION_POLICY
When secrets have limited validity
βœ… RULES (3)
Set TTLs for credentials
Use dynamic secrets where possible
Log secret issuance and expiry
❌ ANTI-PATTERNS (3)
Perpetual static secrets
No expiry enforcement
No alert on approaching expiration
πŸ’» CODE HINTS (1)
secret.ttl = '30d'; notifyBeforeExpiry()
AUDIT_AND_ACCESS_LOGGING
When tracking access to secrets
βœ… RULES (3)
Log every secret read with actor info
Alert on suspicious access
Retain logs per compliance rules
❌ ANTI-PATTERNS (3)
Reading secrets without audit trail
Silent access from CI pipelines
No retention policy for secret logs
πŸ’» CODE HINTS (1)
log.secretAccess({ who, what, why })
ON_DEMAND_RUNTIME_SECRET_FETCHING
When application needs secret during runtime only
βœ… RULES (3)
Fetch secrets via API or volume mount
Inject into memory space only
Avoid caching unless ephemeral
❌ ANTI-PATTERNS (3)
Injecting secrets at build-time
Leaving secrets in env post-shutdown
Persisting secrets in logs or heap dumps
πŸ’» CODE HINTS (1)
secret = await vault.fetch('api/key')
πŸ§ͺ VALIDATION
Simulate secret rotation, audit trail inspection, runtime access patterns. Verify encryption, file permissions, and alerts on misuse or overuse.
#247Matrix 247 β€” Encryption at Rest Matrix6 cells18 rules18 anti6 hints
Define encryption policies for sensitive data stored on disk, database, file systems, and backups.
encryption_scopekey_managementstorage_mediumperformance_impact_mitigationauditability_and_alertingcompliance_alignment
FULL_DISK_ENCRYPTION_FOR_SERVERS
When securing all data at rest on virtual machines
βœ… RULES (3)
Use FDE with automatic unlock
Enable encryption by cloud provider or OS
Audit encryption policy status at boot
❌ ANTI-PATTERNS (3)
Running production on unencrypted disks
Using non-boot-persistent keys
Missing boot-time audit enforcement
πŸ’» CODE HINTS (1)
gcloud compute disks create --image-encryption-key ...
FIELD_LEVEL_ENCRYPTION_IN_DB
When protecting specific columns like SSN or card numbers
βœ… RULES (3)
Encrypt sensitive fields client-side or in DB
Store encryption context or metadata separately
Restrict decryption access to app roles
❌ ANTI-PATTERNS (3)
Encrypting full record blindly
Storing keys in same table
Decrypting in client UI
πŸ’» CODE HINTS (1)
encryptField('ssn', keyRef)
DATABASE_TDE_WITH_KEY_ROTATION
When securing structured relational data
βœ… RULES (3)
Enable Transparent Data Encryption (TDE)
Rotate master keys periodically
Log key usage and access attempts
❌ ANTI-PATTERNS (3)
Disabling TDE in dev and prod
Never rotating TDE master key
Letting expired certs block reads
πŸ’» CODE HINTS (1)
ALTER DATABASE ... SET ENCRYPTION ON
ENCRYPTED_BACKUPS_AND_SNAPSHOTS
When storing backup files outside live system
βœ… RULES (3)
Encrypt backup archives
Use different keys per environment
Require auth to restore access
❌ ANTI-PATTERNS (3)
Exporting plaintext DB dumps
Sharing backup keys with prod keys
Leaving snapshot volumes open
πŸ’» CODE HINTS (1)
aws rds create-db-snapshot --kms-key-id ...
KEY_MANAGEMENT_VIA_KMS_OR_HSM
When managing encryption keys at scale
βœ… RULES (3)
Use hardware or cloud key managers
Separate data and key access roles
Log every decrypt operation
❌ ANTI-PATTERNS (3)
Using same static key for all data
Embedding keys in source code
No access audit on key reads
πŸ’» CODE HINTS (1)
kms.decrypt(ciphertext)
COMPLIANCE_ALERTING_AND_LABELING
When data must comply with GDPR, HIPAA, or PCI
βœ… RULES (3)
Tag encrypted assets by sensitivity
Raise alert on unencrypted writes
Generate compliance reports regularly
❌ ANTI-PATTERNS (3)
Letting unknown data bypass policy
Encrypting but not labeling
Auditing only once a year
πŸ’» CODE HINTS (1)
policy.check('encryption:gcs')
πŸ§ͺ VALIDATION
Scan data stores for encryption status. Trigger alerts on non-encrypted writes. Test backup restore with key isolation and field-level access separation.
#248Matrix 248 β€” Encryption in Transit Matrix6 cells18 rules18 anti6 hints
Define standards for protecting data in transit between services, clients, and networks, with modern encryption protocols.
transport_protocolcertificate_and_tls_pinninginternal_network_encryptionclient_handshake_behaviorlegacy_protocol_rejectionmonitoring_and_certs_rotation
TLS_1_2_PLUS_FOR_ALL_EXTERNAL_COMMUNICATION
When securing data between browser/mobile and servers
βœ… RULES (3)
Use TLS 1.2 or newer
Disable plaintext and downgrade fallbacks
Force HTTPS redirects
❌ ANTI-PATTERNS (3)
Allowing HTTP fallback
Supporting SSLv3 or TLS 1.0
Not redirecting port 80
πŸ’» CODE HINTS (1)
server.forceHttps = true
MUTUAL_TLS_FOR_SERVICE_TO_SERVICE
When securing internal microservice calls
βœ… RULES (3)
Use mTLS with per-service certificates
Rotate client certs regularly
Verify subject alternative name (SAN)
❌ ANTI-PATTERNS (3)
Using shared certs for all services
No identity verification
Skipping SAN validation
πŸ’» CODE HINTS (1)
envoy: tls_context { common_tls_context { tls_certificates { ... } } }
ENCRYPT_INTERNAL_NETWORK_SEGMENTS
When assuming VPC or VLAN is not sufficient
βœ… RULES (3)
Encrypt all non-public internal links
Use service mesh or VPN layer
Log attempted cleartext connections
❌ ANTI-PATTERNS (3)
Assuming internal = secure
Disabling encryption for performance
No alerting on unencrypted flows
πŸ’» CODE HINTS (1)
istio.mtls.enabled = true
CERTIFICATE_PINNING_IN_CLIENTS
When preventing man-in-the-middle attacks on mobile/web
βœ… RULES (3)
Pin public key or SPKI hash
Use fallback pin set with expiration
Update pins with app releases
❌ ANTI-PATTERNS (3)
Pinning certs that expire
No rotation mechanism
Breaking app on key rotation
πŸ’» CODE HINTS (1)
app.network.setPinSet({ hashes: [...] })
DISABLE_WEAK_CIPHERS_AND_PROTOCOLS
When configuring TLS endpoints
βœ… RULES (3)
Reject SSL, TLS 1.0, 1.1
Disable RC4, 3DES, and export-grade ciphers
Support forward secrecy
❌ ANTI-PATTERNS (3)
Supporting all cipher suites
Allowing legacy clients with weak handshake
No test coverage for cipher policy
πŸ’» CODE HINTS (1)
ssl_ciphers 'HIGH:!aNULL:!MD5';
TLS_CERT_MONITORING_AND_ROTATION
When maintaining long-running TLS endpoints
βœ… RULES (3)
Monitor cert expiration
Auto-renew via ACME or cron
Alert on mismatch or failure
❌ ANTI-PATTERNS (3)
Hardcoding certs into images
Manual rotation without alerting
Letting certs expire in prod
πŸ’» CODE HINTS (1)
certbot renew && nginx -s reload
πŸ§ͺ VALIDATION
Test connections with legacy protocols. Expire a cert in staging. Trigger mTLS failure. Validate encrypted flow visibility and rotation alerts.
#249Input Attack Surface Matrix6 cells12 rules6 anti6 hints
Determines how input attack vectors are identified and mitigated β€” form fields, query params, headers, file uploads, and API payloads.
input_vectorattack_typemitigationvalidation_layer
input_001
When accepting input from form fields, apply context-aware output encoding and sanitize HTML to prevent XSS attacks.
βœ… RULES (2)
Escape output using textContent or equivalent
Strip scripts via DOMPurify or server-side sanitizer
❌ ANTI-PATTERNS (1)
Writing raw input to innerHTML
πŸ’» CODE HINTS (1)
div.textContent = userInput
input_002
When reading query parameters for DB access, always use parameterized queries to prevent SQL injection.
βœ… RULES (2)
Bind query parameters instead of interpolating strings
Use ORM query builder or prepared statements
❌ ANTI-PATTERNS (1)
SELECT * FROM users WHERE name = concat(req.query.name)
πŸ’» CODE HINTS (1)
db.query('SELECT * FROM users WHERE name = ?', [name])
input_003
When processing HTTP headers, validate and escape newline characters to prevent header splitting or host header injection.
βœ… RULES (2)
Reject header values containing or
Normalize and validate Host header against whitelist
❌ ANTI-PATTERNS (1)
res.setHeader('Location', req.headers['x-custom'])
πŸ’» CODE HINTS (1)
if (/ | /.test(header)) reject()
input_004
When handling file uploads, verify MIME type and scan file headers to prevent spoofing and ensure expected content.
βœ… RULES (2)
Check MIME type with server-side library (e.g. magic bytes)
Whitelist allowed types
❌ ANTI-PATTERNS (1)
Relying solely on client-provided Content-Type
πŸ’» CODE HINTS (1)
mime = magic.detect(file.buffer); if (!allowed.includes(mime)) reject()
input_005
When receiving JSON payloads, enforce strict schemas to prevent unintended field injection (mass assignment).
βœ… RULES (2)
Use schema validators like Zod or Joi
Only bind explicitly listed fields
❌ ANTI-PATTERNS (1)
Object.assign(user, req.body)
πŸ’» CODE HINTS (1)
const user = pick(req.body, ['name','email'])
input_006
When reading cookies, sign and verify their integrity to prevent tampering.
βœ… RULES (2)
Use HMAC signing or JWT with secret
Reject if signature invalid or expired
❌ ANTI-PATTERNS (1)
Trusting cookie content without verification
πŸ’» CODE HINTS (1)
cookie = verifyHMAC(req.cookies.session)
πŸ§ͺ VALIDATION
Verify: input validated at boundary, parameterized queries used, headers and cookies sanitized, file uploads type-checked, and API payloads schema-validated.
#250Matrix 250 β€” Output Escaping Matrix6 cells18 rules18 anti6 hints
Define strategies for escaping untrusted content before rendering it in HTML, JavaScript, URLs, and other output contexts to prevent injection attacks.
output_contextescaping_methodtemplate_engine_supportautoescaping_defaultsdeveloper_override_policyencoding_library
HTML_BODY_ESCAPING
When injecting user input into page content
βœ… RULES (3)
Escape <, >, &, " and ' characters
Use encoding functions or template autoescaping
Reject or strip tags in rich text fields
❌ ANTI-PATTERNS (3)
String concat without escaping
Inserting HTML without sanitization
Allowing style/script tags in user content
πŸ’» CODE HINTS (1)
output = escapeHtml(userInput)
ATTRIBUTE_VALUE_ESCAPING
When inserting content into HTML attribute
βœ… RULES (3)
Escape quotes and special characters
Use context-aware escaping for href, src, alt
Enforce allowed protocols for links
❌ ANTI-PATTERNS (3)
Direct interpolation of href/src
Failing to escape ampersands
Allowing javascript: URLs
πŸ’» CODE HINTS (1)
<a href="{{ escapeAttr(url) }}">
JAVASCRIPT_CONTEXT_ESCAPING
When rendering content into JS inline blocks
βœ… RULES (3)
Escape " and \ in strings
Avoid direct object injection
Use JSON.stringify for values
❌ ANTI-PATTERNS (3)
String concat in <script> blocks
Embedding user objects directly
Assuming safe JSON structure
πŸ’» CODE HINTS (1)
<script>const data = {{ JSON.stringify(userData) }}</script>
URL_COMPONENT_ENCODING
When building dynamic links or query strings
βœ… RULES (3)
Use encodeURIComponent for query params
Validate domain or redirect targets
Reject URLs with disallowed schemas
❌ ANTI-PATTERNS (3)
Raw string concat for URL building
Trusting user-controlled redirect URLs
Mixing unescaped slashes or spaces
πŸ’» CODE HINTS (1)
const link = '/search?q=' + encodeURIComponent(query)
AUTOESCAPE_ON_BY_DEFAULT
When using templates or rendering libraries
βœ… RULES (3)
Use engines with autoescaping enabled
Require explicit opt-out
Escape all dynamic interpolations
❌ ANTI-PATTERNS (3)
Using string templates without escaping
Turning off autoescape globally
Allowing raw HTML by default
πŸ’» CODE HINTS (1)
{{ userInput }} β†’ autoescaped
ESCAPE_LIBRARY_USAGE_POLICY
When standardizing secure output across team
βœ… RULES (3)
Use vetted escaping libraries
Prohibit homegrown escaping logic
Run lint checks for unsafe patterns
❌ ANTI-PATTERNS (3)
Ad-hoc escaping per developer
Reinventing HTML escaping
Letting unsafe patterns through reviews
πŸ’» CODE HINTS (1)
const safe = DOMPurify.sanitize(input)
πŸ§ͺ VALIDATION
Render untrusted inputs in all output contexts. Confirm proper escaping by inspection and test harness. Attempt to inject and verify failures.
#251CSRF Protection Matrix6 cells13 rules6 anti6 hints
Determines how Cross-Site Request Forgery is prevented β€” token-based, SameSite cookies, origin validation, and double-submit patterns.
protection_methodtoken_placementcookie_policyverification
csrf_001
When rendering a server-side form, embed CSRF token as hidden field and validate it on POST to ensure token authenticity.
βœ… RULES (3)
Generate per-session CSRF token
Include hidden <input> in forms
Validate token server-side before processing
❌ ANTI-PATTERNS (1)
Accepting POST without verifying token
πŸ’» CODE HINTS (1)
<input type='hidden' name='csrf_token' value='{{token}}'>
csrf_002
When using AJAX requests, include CSRF token in X-CSRF-Token header and validate it on server.
βœ… RULES (2)
Set token in request header via JS
Reject if header missing or mismatched
❌ ANTI-PATTERNS (1)
Relying only on cookies with JS requests without header check
πŸ’» CODE HINTS (1)
fetch('/submit', { headers: { 'X-CSRF-Token': token } })
csrf_003
When setting session cookies, use SameSite=Strict to block all cross-site requests automatically.
βœ… RULES (2)
Set SameSite=Strict on all auth/session cookies
Use only for apps that don’t need cross-origin access
❌ ANTI-PATTERNS (1)
Using SameSite=None without Secure flag
πŸ’» CODE HINTS (1)
Set-Cookie: session=...; SameSite=Strict
csrf_004
When verifying cross-site requests, check Origin and Referer headers to confirm request source matches server domain.
βœ… RULES (2)
Validate Origin/Referer on sensitive methods (POST, PUT, DELETE)
Reject if header missing or mismatched
❌ ANTI-PATTERNS (1)
Not validating headers or trusting all origins
πŸ’» CODE HINTS (1)
if (!origin.endsWith(myDomain)) reject()
csrf_005
When using double-submit method, set CSRF token in cookie and require matching value in request body or header.
βœ… RULES (2)
Set token cookie on page load
Check match between cookie and form/header token
❌ ANTI-PATTERNS (1)
Verifying token only in cookie without match to payload
πŸ’» CODE HINTS (1)
cookie = document.cookie.csrf; fetch('/submit', { headers: { 'X-CSRF': cookie } })
csrf_006
When using stateless CSRF tokens, issue token as HMAC of session/nonce and validate signature on submission.
βœ… RULES (2)
Use server-secret + session-id to generate token
Verify HMAC on every request
❌ ANTI-PATTERNS (1)
Using random string without signing
πŸ’» CODE HINTS (1)
csrf = HMAC(secret, sessionId); validate(HMAC, received)
πŸ§ͺ VALIDATION
Verify: CSRF token present and validated, SameSite flags set properly, origin/referer checked, stateless HMAC verified, and double-submit patterns enforced.
#252XSS Protection Matrix6 cells12 rules6 anti6 hints
Determines how Cross-Site Scripting is prevented β€” output encoding, CSP headers, sanitization, and trusted types.
xss_typeprevention_methodcsp_policytrusted_types
xss_001
When reflecting untrusted input into HTML (e.g. query param into DOM), escape all special characters to prevent execution.
βœ… RULES (2)
Use context-aware output encoding (e.g. HTML, JS, URL)
Never insert raw user input into DOM
❌ ANTI-PATTERNS (1)
innerHTML = location.search
πŸ’» CODE HINTS (1)
element.textContent = userInput
xss_002
When storing user input (e.g. comments), sanitize dangerous tags on input and encode again on output.
βœ… RULES (2)
Apply sanitizer like DOMPurify on input
Use output encoding at render time
❌ ANTI-PATTERNS (1)
Sanitize only on input then trust it forever
πŸ’» CODE HINTS (1)
sanitized = DOMPurify.sanitize(input); div.textContent = sanitized
xss_003
When dynamically inserting user data into DOM, use safe APIs like textContent instead of innerHTML.
βœ… RULES (2)
Avoid innerHTML, outerHTML, insertAdjacentHTML for user content
Use DOM setters that don’t interpret HTML
❌ ANTI-PATTERNS (1)
el.innerHTML = userValue
πŸ’» CODE HINTS (1)
el.textContent = userValue
xss_004
When enforcing script safety, set strict Content-Security-Policy to allow only trusted script sources.
βœ… RULES (2)
Use CSP header: script-src 'self' https://cdn.example.com
Disallow inline scripts unless nonce-based
❌ ANTI-PATTERNS (1)
Using script-src * or unsafe-inline
πŸ’» CODE HINTS (1)
Content-Security-Policy: script-src 'self' https://cdn.example.com
xss_005
When using modern browsers, enforce Trusted Types to prevent DOM XSS through dangerous sinks.
βœ… RULES (2)
Enable Trusted Types via CSP
Define policy and create TrustedHTML wrapper
❌ ANTI-PATTERNS (1)
Assigning raw strings to innerHTML without policy
πŸ’» CODE HINTS (1)
window.trustedTypes.createPolicy('default', { createHTML: (s) => DOMPurify.sanitize(s) })
xss_006
When allowing dynamic scripts, use CSP nonces to allow only scripts generated with server-approved nonce value.
βœ… RULES (2)
Generate unique nonce per response
Apply nonce to <script> tag and match in CSP
❌ ANTI-PATTERNS (1)
Allowing inline scripts without nonce
πŸ’» CODE HINTS (1)
<script nonce='{{nonce}}'>...</script> CSP: script-src 'nonce-{{nonce}}'
πŸ§ͺ VALIDATION
Verify: XSS attack vectors blocked via encoding/sanitizing, CSP headers enforced, Trusted Types in place, and inline scripts restricted by nonce.
#253Injection Prevention Matrix6 cells18 rules18 anti6 hints
Define strategies to detect, block, and sanitize injection attempts across input channels and execution contexts.
input_source_typeexecution_contextsanitization_methodparameterization_supportpayload_detectionlogging_and_alerting
SQL_INJECTION_PROTECTION_VIA_PREPARED_STATEMENTS
When user input is used in database queries
βœ… RULES (3)
Always use prepared statements with bound parameters
Disallow string concatenation for query construction
Validate input types before DB call
❌ ANTI-PATTERNS (3)
Concatenating strings into SQL
Trusting client-side input validation only
Dynamic WHERE clauses without binding
πŸ’» CODE HINTS (1)
db.query('SELECT * FROM users WHERE id = ?', [userId])
COMMAND_INJECTION_SANITIZATION_AND_ESCAPE
When input is passed to system shell or exec
βœ… RULES (3)
Use child_process.execFile instead of exec
Validate allowed commands against whitelist
Escape shell metacharacters
❌ ANTI-PATTERNS (3)
Passing input directly to bash or sh
Using eval with untrusted input
Ignoring OS-specific escape needs
πŸ’» CODE HINTS (1)
execFile('ls', ['-l', userPath])
NOSQL_INJECTION_DETECTION_IN_FILTER_OBJECTS
When untrusted data builds MongoDB or NoSQL queries
βœ… RULES (3)
Disallow $-prefixed keys in user input
Filter only allowed query fields
Sanitize deeply nested objects
❌ ANTI-PATTERNS (3)
Passing req.body directly to find()
Trusting shallow key inspection
Allowing arbitrary query operators
πŸ’» CODE HINTS (1)
sanitizeQuery(req.body, allowedFields)
SERVER_SIDE_TEMPLATE_INJECTION_CONTROL
When rendering server-side templates with dynamic data
βœ… RULES (3)
Avoid user-controlled logic in templates
Use escaping by default
Restrict context variables
❌ ANTI-PATTERNS (3)
Embedding unescaped {{userInput}} in templates
Allowing user-defined template code
Using eval in template context
πŸ’» CODE HINTS (1)
res.render('profile', { username: escape(user.name) })
LDAP_QUERY_SANITIZATION_AND_FILTER_ENCODING
When constructing LDAP filters from input
βœ… RULES (3)
Escape special characters like * ( ) \
Use library encoding for filters
Reject unsupported query patterns
❌ ANTI-PATTERNS (3)
Concatenating input into LDAP strings
No length limit on user input
Blind bind queries without validation
πŸ’» CODE HINTS (1)
ldap.escapeFilter(username)
INJECTION_ALERT_LOGGING_AND_RESPONSE
When injection attempt is detected at runtime
βœ… RULES (3)
Log source IP and payload sample
Throttle or ban repeat offenders
Alert security team on threshold breach
❌ ANTI-PATTERNS (3)
Ignoring anomalous payloads
Logging full request without redaction
No alerts on high-frequency attempts
πŸ’» CODE HINTS (1)
log.warn('injection_attempt', { ip, path, snippet })
πŸ§ͺ VALIDATION
Run automated fuzzing and payload injection tests. Validate sanitization output. Review logs and verify alerts trigger under simulated attack load.
#254Matrix 254 β€” File Security Matrix6 cells18 rules18 anti6 hints
Define security practices for handling file uploads, downloads, processing, and storage to prevent injection, exfiltration, or abuse.
file_input_channelvalidation_and_mime_checkstorage_strategyaccess_control_and_scopingprocessing_sandboxinglogging_and_alerting
RESTRICT_FILE_TYPES_AND_EXTENSIONS
When accepting files from untrusted sources
βœ… RULES (3)
Whitelist MIME types and extensions
Use server-side MIME sniffing
Reject executable formats
❌ ANTI-PATTERNS (3)
Client-side only file validation
Allowing *.exe, *.js, *.sh
Relying on filename alone
πŸ’» CODE HINTS (1)
if (!allowedTypes.includes(mime)) reject()
VIRUS_SCAN_AND_QUARANTINE
When storing or sharing user-uploaded files
βœ… RULES (3)
Scan files on upload
Quarantine or reject malicious uploads
Tag files with scan status
❌ ANTI-PATTERNS (3)
Skipping AV scan in dev/staging
Trusting cloud provider implicitly
No user feedback on file rejection
πŸ’» CODE HINTS (1)
clamd.scan(upload.path)
STORAGE_ISOLATION_AND_INDIRECT_ACCESS
When serving files back to clients
βœ… RULES (3)
Store in segregated blob/object storage
Serve via signed URLs or proxy endpoints
Limit file lifetime and scope
❌ ANTI-PATTERNS (3)
Serving files directly from upload folder
Embedding file paths in HTML/JS
Static links to user files
πŸ’» CODE HINTS (1)
generateSignedUrl(fileId)
ACCESS_CONTROL_PER_FILE_SCOPE
When multiple users upload and access files
βœ… RULES (3)
Tag files with owner or access group
Enforce access at retrieval layer
Expire or revoke shared file links
❌ ANTI-PATTERNS (3)
All users share upload bucket
Checking only on client
No ACL enforcement in backend
πŸ’» CODE HINTS (1)
checkAccess(req.user, file.meta)
SANDBOX_FILE_PROCESSING
When processing uploaded files for parsing or extraction
βœ… RULES (3)
Use isolated container or thread pool
Set CPU/memory limits per job
Terminate on timeouts or failures
❌ ANTI-PATTERNS (3)
Parsing files in main thread
Unbounded memory allocation
Letting user control parser flags
πŸ’» CODE HINTS (1)
spawnWorkerThread(file)
AUDIT_LOGGING_AND_FILE_EVENT_MONITORING
When tracking sensitive file access or modification
βœ… RULES (3)
Log every upload, access, delete event
Include user, IP, timestamp, file ID
Alert on unexpected access patterns
❌ ANTI-PATTERNS (3)
No logging for read operations
Storing logs in same place as files
Silent overwrite of existing files
πŸ’» CODE HINTS (1)
log.fileEvent('read', { userId, fileId })
πŸ§ͺ VALIDATION
Upload test files with known payloads. Validate type checking, scan outcome, access scoping, and processing container isolation.
#255Rate Abuse Matrix6 cells12 rules6 anti6 hints
Determines how rate limiting and abuse prevention are implemented β€” per-user limits, sliding windows, and graduated responses.
rate_algorithmscoperesponse_actionbypass_protection
rateabuse_001
When limiting each user's request rate, apply a fixed window (e.g. 100 requests/min) reset on each interval.
βœ… RULES (2)
Track request count per user ID within 60s window
Reset count after window expires
❌ ANTI-PATTERNS (1)
Using same global counter for all users
πŸ’» CODE HINTS (1)
rate[userId] = rate[userId] + 1; if (rate[userId] > 100) block(userId)
rateabuse_002
When enforcing smoother limits, use sliding window algorithm per IP to avoid bursts within fixed boundaries.
βœ… RULES (2)
Track request timestamps in rolling 60s window
Reject if more than 60 requests in last 60s
❌ ANTI-PATTERNS (1)
Fixed reset time that enables burst at window edges
πŸ’» CODE HINTS (1)
if (requests[ip].filter(t => now - t < 60000).length > 60) throttle(ip)
rateabuse_003
When allowing controlled bursts, use token bucket per user β€” refill tokens over time, consume on request.
βœ… RULES (2)
Set bucket size and refill rate per user
Block if no tokens left
❌ ANTI-PATTERNS (1)
No refill logic implemented β†’ dry bucket
πŸ’» CODE HINTS (1)
bucket[user].tokens -= 1; if (tokens < 0) reject(user)
rateabuse_004
When users repeatedly exceed rate limits, escalate response: warn β†’ throttle β†’ block.
βœ… RULES (2)
Track infractions per user
Escalate based on infraction history
❌ ANTI-PATTERNS (1)
Blocking immediately without prior warning or context
πŸ’» CODE HINTS (1)
if (infractions[user] == 1) warn(), if == 2 then delay(), if >= 3 then block()
rateabuse_005
When issuing API keys, assign rate limits per key based on subscription tier (e.g. free vs premium).
βœ… RULES (2)
Tag each API key with tier label
Enforce limit based on key tier
❌ ANTI-PATTERNS (1)
Same rate limit for all users regardless of tier
πŸ’» CODE HINTS (1)
if (key.tier == 'free' && rate > 10/min) reject()
rateabuse_006
When enforcing rate limits, ensure protection cannot be bypassed by scripts (e.g. rotating IPs) via bot detection and CAPTCHA challenges.
βœ… RULES (2)
Use fingerprinting to track identity beyond IP
Trigger CAPTCHA after abuse detected
❌ ANTI-PATTERNS (1)
IP-only rate tracking susceptible to botnet evasion
πŸ’» CODE HINTS (1)
if (botScore > 0.9 || rotatingIPs) challengeWithCaptcha()
πŸ§ͺ VALIDATION
Verify: rate algorithms apply per-user/IP/key, sliding window avoids burst edge, token bucket refills, graduated escalation works, key tiers enforced, and bypass protected by bot detection.
#256Matrix 256 β€” Audit Logging Matrix6 cells18 rules18 anti6 hints
Define what, when, and how to log security-relevant events for compliance, forensics, and anomaly detection β€” covering log structure, retention, tamper-proofing, and alerting.
event_classificationlog_structure_formatretention_policytamper_protectionaccess_control_on_logsalerting_integration
AUTH_EVENT_LOGGING_JSONL
When logging authentication attempts or changes
βœ… RULES (3)
Log auth success/failure with timestamp
Use JSONL format with user/session context
Include IP, agent, and method type
❌ ANTI-PATTERNS (3)
Only logging errors
Mixing formats (text + json)
Omitting username/IP in logs
πŸ’» CODE HINTS (1)
logger.info({ event: 'auth_failure', user, ip })
CONFIG_CHANGE_LOG_CHAINED
When config or access policies are modified
βœ… RULES (3)
Log before/after state and actor
Timestamp and correlate with ticket
Hash entry and chain for immutability
❌ ANTI-PATTERNS (3)
No before/after diff
Overwriting logs on change
No link to authorizing request
πŸ’» CODE HINTS (1)
audit.logChange('role_policy', old, new)
DATA_ACCESS_LOG_WITH_MASKING
When recording read/write access to sensitive data
βœ… RULES (3)
Log actor, dataset, operation type
Mask sensitive content (PII, secrets)
Store separately from raw data path
❌ ANTI-PATTERNS (3)
Logging full raw PII
No record of read access
Mixing access logs with debug logs
πŸ’» CODE HINTS (1)
log.access({ user, resource: 'customer_email', action: 'read' })
LOG_RETENTION_AND_ROTATION_POLICY
When managing storage and lifecycle of logs
βœ… RULES (3)
Set log TTL by event type (e.g. 90 days)
Compress and rotate logs on schedule
Use lifecycle policies for archive
❌ ANTI-PATTERNS (3)
Infinite log retention
Stale logs mixed with hot data
No index or query support on archives
πŸ’» CODE HINTS (1)
s3.putLifecycleRule({ prefix: 'audit/', days: 90 })
APPEND_ONLY_STORAGE_WITH_PROOF
When requiring tamper-proof logging
βœ… RULES (3)
Use WORM (write-once-read-many) storage
Hash and chain log entries
Verify via Merkle proof or signature
❌ ANTI-PATTERNS (3)
Allowing log deletion
Editable log formats
Unverifiable log chain
πŸ’» CODE HINTS (1)
appendLog(entry); verifyMerkleChain()
ALERT_ON_CRITICAL_LOG_EVENTS
When sensitive events occur
βœ… RULES (3)
Define event types that require alert
Send to SIEM/Slack/on-call
Rate limit repeat alerts
❌ ANTI-PATTERNS (3)
Only storing logs without analysis
Alerts buried in email
Alert storms with no deduplication
πŸ’» CODE HINTS (1)
if (event.type in CRITICAL) alert.send(event)
πŸ§ͺ VALIDATION
Inject auth attempt, config change, and access events. Confirm structure, chaining, retention, masking, and alerts are active.
#257Matrix 257 β€” Tamper Detection Matrix6 cells18 rules18 anti6 hints
Define methods to detect unauthorized or unexpected modifications to code, configuration, or runtime environment.
monitored_asset_typedetection_mechanismtrigger_frequencyresponse_policylogging_detailtamper_scope_classification
STATIC_FILE_INTEGRITY_HASHING
When deploying frontend or CDN assets
βœ… RULES (3)
Generate checksum for each file
Use Subresource Integrity (SRI) in HTML
Fail load if hash mismatch
❌ ANTI-PATTERNS (3)
Loading JS from 3rd party without SRI
No checksums for key assets
Hash mismatch warning ignored
πŸ’» CODE HINTS (1)
<script src=... integrity='sha384-...' crossorigin='anonymous'>
CONFIG_FILE_CHECKSUM_VALIDATION
When verifying runtime config integrity
βœ… RULES (3)
Generate baseline checksums on deploy
Verify hashes at runtime or boot
Alert on change outside deploy window
❌ ANTI-PATTERNS (3)
Trusting config state blindly
Missing monitoring for mounted secrets
Assuming container immutability
πŸ’» CODE HINTS (1)
if hash(config) != stored_hash β†’ alert()
CODE_PACKAGE_SIGNATURE_VERIFICATION
When pulling code from external registry
βœ… RULES (3)
Use signed packages or hashes
Verify digital signature before install
Reject unsigned or mismatched packages
❌ ANTI-PATTERNS (3)
Installing directly from unverified URL
Trusting package.json blindly
Allowing mutable version tags
πŸ’» CODE HINTS (1)
npm audit sign --verify
MEMORY_AND_RUNTIME_PROTECTION_MONITORS
When guarding against in-memory tampering
βœ… RULES (3)
Use EDR or in-process memory scan
Trigger on syscall anomalies
Quarantine anomalous processes
❌ ANTI-PATTERNS (3)
Assuming sandbox = secure
Ignoring process injection vectors
No behavioral signature tracking
πŸ’» CODE HINTS (1)
monitorRuntime({ scanInterval: 5s })
SOURCE_REPO_TAMPER_AUDIT
When monitoring source code integrity
βœ… RULES (3)
Use signed commits (e.g. GPG)
Restrict force-push to admins
Alert on history rewrite or unexpected branch creation
❌ ANTI-PATTERNS (3)
Allowing force-push on main
No verification of committer identity
Ignoring external CI triggers
πŸ’» CODE HINTS (1)
git log --show-signature
TAMPER_CLASSIFICATION_AND_RESPONSE_POLICY
When detecting any anomaly indicating tamper
βœ… RULES (3)
Classify tamper by scope and severity
Alert team and suspend automation if needed
Log full chain of custody of change
❌ ANTI-PATTERNS (3)
Flat alert for all tamper cases
No escalation for production-impacting change
Missing audit trail for correction
πŸ’» CODE HINTS (1)
log.tamper({ level: 'critical', asset: 'config.env' })
πŸ§ͺ VALIDATION
Simulate modification of static asset, config, or code package. Confirm alert firing, hash mismatch logging, and incident classification triggers.
#258Matrix 258 β€” Integrity Checks Matrix6 cells18 rules18 anti6 hints
Define validation and integrity verification strategies for data at rest, in transit, and in processing to ensure trustworthiness.
asset_typevalidation_methodtrigger_timingdetection_scoperemediation_actionaudit_logging
STATIC_FILE_HASH_VALIDATION
When serving frontend or CDN assets
βœ… RULES (3)
Generate SHA-256 hashes at build
Store hashes in manifest file
Check on load or integrity attr
❌ ANTI-PATTERNS (3)
No hash-based loading mechanism
Allowing mismatch with fallback
Silent failure on mismatch
πŸ’» CODE HINTS (1)
<script src=... integrity='sha256-...'>
SIGNED_PAYLOAD_VERIFICATION
When receiving structured API or webhook payloads
βœ… RULES (3)
Include HMAC or digital signature with payload
Recompute and verify signature on receipt
Log failures with timestamp and source
❌ ANTI-PATTERNS (3)
Trusting unauthenticated inbound data
Using weak hashing (MD5)
No failure logging
πŸ’» CODE HINTS (1)
crypto.verify(signature, body, key)
CHECKSUM_VERIFICATION_FOR_DOWNLOADS
When client downloads large files from server
βœ… RULES (3)
Provide .sha256 files for assets
Auto-verify checksum on client
Retry or alert on mismatch
❌ ANTI-PATTERNS (3)
Downloading without integrity check
Mismatch silently ignored
No retry on corrupted downloads
πŸ’» CODE HINTS (1)
verifyChecksum(blob, expectedHash)
DATABASE_ROW_HASH_COLUMN
When storing sensitive or critical data rows
βœ… RULES (3)
Add hash column to data rows
Recompute and compare on read
Update hash only through trusted logic
❌ ANTI-PATTERNS (3)
No row-level validation
Updating hash blindly
Allowing direct DB writes bypassing hash
πŸ’» CODE HINTS (1)
row.hash = sha256(row.data)
BACKUP_INTEGRITY_TESTING
When validating data backups for disaster recovery
βœ… RULES (3)
Run periodic restore tests
Compare backup content hash to original
Alert on failure to mount or verify
❌ ANTI-PATTERNS (3)
Assuming backup = valid
No verification post-snapshot
Restoring silently despite errors
πŸ’» CODE HINTS (1)
compareHashes(backup, live)
INTEGRITY_FAILURE_ALERT_CHAIN
When any validation fails in runtime
βœ… RULES (3)
Classify failure severity
Notify relevant stakeholders
Log full trace with context
❌ ANTI-PATTERNS (3)
No alert on checksum mismatch
Silent fallback to last good version
Missing audit trail for validation outcome
πŸ’» CODE HINTS (1)
alert('integrity_failure', { id, scope, severity })
πŸ§ͺ VALIDATION
Test mismatched assets, webhook tamper, and invalid database rows. Confirm alerts, logs, and halted processing. Simulate backup restoration with hash verification.
#259Matrix 259 β€” Least Privilege Matrix6 cells18 rules18 anti6 hints
Define principles and enforcement mechanisms to restrict access rights for users, services, and systems to the minimum necessary.
principal_typescope_definitionpermission_grant_mechanismreview_frequencyrevocation_policyvisibility_and_alerting
HUMAN_USER_ROLE_SCOPING
When granting console or UI access to employees
βœ… RULES (3)
Use role-based access with tags
Assign only on ticketed request
Expire temporary access
❌ ANTI-PATTERNS (3)
Permanent admin access
Shared logins
Roles inherited via org group without scoping
πŸ’» CODE HINTS (1)
iam.attachRole(user, role, expiresAt)
SERVICE_IDENTITY_MINIMUM_SCOPE
When granting service accounts access to APIs or secrets
βœ… RULES (3)
Use unique identity per service
Allow only necessary APIs
Separate read/write identities
❌ ANTI-PATTERNS (3)
One service identity shared across apps
Access to * wildcard scopes
Same identity used in dev and prod
πŸ’» CODE HINTS (1)
gcp.serviceAccount({ name, scopes: ['read.bucket.x'] })
TIME_BOUND_ELEVATION_AND_ESCALATION
When temporary elevated access is required
βœ… RULES (3)
Use just-in-time (JIT) access workflows
Log elevation request, approval, and timeout
Auto-revoke after period
❌ ANTI-PATTERNS (3)
Manual grant with no expiry
No tracking of who elevated whom
Generic breakglass accounts
πŸ’» CODE HINTS (1)
elevateRole('db-admin', expiresIn=15min)
PERMISSION_REVIEW_AND_CLEANUP
When auditing permission sprawl
βœ… RULES (3)
Run periodic least privilege audit
Revoke unused permissions after threshold
Review high-privilege principals monthly
❌ ANTI-PATTERNS (3)
Set-and-forget access
Never expiring IAM grants
No insight into unused scopes
πŸ’» CODE HINTS (1)
audit.report('privilege-review')
ACCESS_POLICY_AS_CODE
When defining IAM or RBAC across systems
βœ… RULES (3)
Use declarative access policy (e.g. YAML, HCL)
Test policy before apply
Review via PR with audit log
❌ ANTI-PATTERNS (3)
ClickOps for policy changes
No review on access addition
Inline policy logic buried in code
πŸ’» CODE HINTS (1)
terraform apply iam.tf
EXCESSIVE_PRIVILEGE_ALERTING_AND_DASHBOARDING
When integrating least privilege into monitoring
βœ… RULES (3)
Alert on new admin grants
Visualize privilege trends over time
Flag outliers vs. baseline roles
❌ ANTI-PATTERNS (3)
No alert on privilege change
Privilege sprawl only caught in audit
No context for high-priv role holders
πŸ’» CODE HINTS (1)
monitor.roleChange(user, newRole) β†’ alertIf(admin)
πŸ§ͺ VALIDATION
Assign, elevate, and revoke roles. Run permission audits. Confirm alerting, expiry, JIT flow, and policy-as-code pipelines.
#260Failure Isolation Matrix6 cells12 rules6 anti6 hints
Determines how failures in one component are isolated from affecting others β€” bulkheads, process boundaries, and blast radius control.
isolation_methodboundary_typeblast_radiusrecovery
failiso_001
When isolating service classes (e.g. user-facing vs. batch jobs), use separate thread pools to prevent starvation during overload.
βœ… RULES (2)
Assign dedicated thread pool per task type
Enforce max concurrency per pool
❌ ANTI-PATTERNS (1)
Single shared thread pool β†’ one slow task delays all
πŸ’» CODE HINTS (1)
executorServiceA = Executors.newFixedThreadPool(20)
failiso_002
When isolating services at runtime, deploy each component in its own container or process to prevent memory leaks or crashes from spreading.
βœ… RULES (2)
Use Docker/K8s to isolate memory and CPU limits
Crash in one container must not affect others
❌ ANTI-PATTERNS (1)
Deploying all modules into a single monolithic process
πŸ’» CODE HINTS (1)
kubectl apply -f serviceA-deployment.yaml
failiso_003
When isolating rendering failures in React apps, wrap components in ErrorBoundary to catch exceptions and render fallback UI.
βœ… RULES (2)
Use <ErrorBoundary> around risky child trees
Provide user-friendly fallback component
❌ ANTI-PATTERNS (1)
Letting unhandled errors crash entire React tree
πŸ’» CODE HINTS (1)
<ErrorBoundary fallback={<CrashUI />}><Widget/></ErrorBoundary>
failiso_004
When isolating between producers and consumers, use message queues (e.g. Kafka, RabbitMQ) to prevent tight coupling and crash propagation.
βœ… RULES (2)
Queue buffers spikes from upstream
Enable retry/DLQ for failed consumer jobs
❌ ANTI-PATTERNS (1)
Direct HTTP calls between tightly coupled services
πŸ’» CODE HINTS (1)
producer.send(topic, payload)
failiso_005
When calling external services, set timeout + fallback per call site to prevent one bad dependency from blocking entire flow.
βœ… RULES (2)
Wrap each HTTP/gRPC call with timeout handler
Use fallback (cache, default) if call exceeds deadline
❌ ANTI-PATTERNS (1)
Letting remote calls hang indefinitely
πŸ’» CODE HINTS (1)
withTimeout(500ms).catch(useFallback)
failiso_006
When isolating experimental features, wrap in feature flag with kill switch capability to instantly disable on impact.
βœ… RULES (2)
Use LaunchDarkly or similar for flag control
Default to off in production rollout
❌ ANTI-PATTERNS (1)
Releasing risky logic without ability to disable live
πŸ’» CODE HINTS (1)
if (flags.featureX) runExperimental();
πŸ§ͺ VALIDATION
Verify: each service or function runs in isolated boundary (thread, process, container, flag), failure in one area doesn't affect others, fallbacks exist, and blast radius controlled via config or flags.
#261Graceful Degradation Matrix6 cells18 rules18 anti6 hints
Define fallback behaviors and UI/service patterns that maintain core functionality under partial system failure.
failure_scopefallback_typeuser_notification_strategycriticality_classificationdegradation_timinglogging_and_metrics
STATIC_ERROR_PAGE_ON_RENDER_FAILURE
When frontend component fails to render due to missing data
βœ… RULES (3)
Render fallback UI on data load error
Log missing resource with context
Avoid infinite retry loops
❌ ANTI-PATTERNS (3)
Blank screen on partial failure
Retry flooding
Leaking stack trace to user
πŸ’» CODE HINTS (1)
<ErrorBoundary fallback={<StaticError />}>...</ErrorBoundary>
READ_ONLY_MODE_ON_WRITE_FAILURE
When backend becomes read-only under stress
βœ… RULES (3)
Disable write buttons or forms
Notify user with reason
Log attempt to write in read-only mode
❌ ANTI-PATTERNS (3)
Returning 500 for all routes
Hiding functionality without explanation
Allowing form submission with silent drop
πŸ’» CODE HINTS (1)
if (isReadOnly) disableEditUI()
FALLBACK_CONTENT_WHEN_DEPENDENCY_DOWN
When 3rd party content provider (e.g. video, ads) fails
βœ… RULES (3)
Check 3rd-party availability via timeout
Use cached or mock content
Log degraded experience separately
❌ ANTI-PATTERNS (3)
Hard fail on embed error
Infinite spinners
Hiding failure without user cue
πŸ’» CODE HINTS (1)
useFallbackIfTimeout(videoLoader, 3s)
CLIENT_SIDE_CACHING_ON_NETWORK_LOSS
When offline or intermittent connectivity occurs
βœ… RULES (3)
Cache recent API responses
Use localStorage/indexedDB for durability
Fallback to cached mode with banner
❌ ANTI-PATTERNS (3)
Failing fetch with no retry
Clearing cache on load
Assuming online presence without check
πŸ’» CODE HINTS (1)
if (!navigator.onLine) useCachedContent()
SERVICE_SWITCHOVER_ON_INSTANCE_FAILURE
When one service instance goes down in a cluster
βœ… RULES (3)
Retry with another instance after health check
Mark failed instance temporarily
Update routing table dynamically
❌ ANTI-PATTERNS (3)
Retrying same bad instance
Letting outage affect user path
Global fail due to local issue
πŸ’» CODE HINTS (1)
retryWithFallback([svc1, svc2, svc3])
DEGRADATION_LOGGING_AND_ALERTING
When fallback or error boundary is activated
βœ… RULES (3)
Log every fallback trigger with source
Alert if fallback frequency exceeds threshold
Correlate with service health metrics
❌ ANTI-PATTERNS (3)
Swallowing degradation silently
No alerting despite degraded UX
Not correlating fallback with root cause
πŸ’» CODE HINTS (1)
log.warn('degraded_mode', { component, frequency })
πŸ§ͺ VALIDATION
Simulate each failure type and verify fallback UI, behavior, logs, and alerts. Use chaos experiments to trigger degradation pathways.
#262Circuit Breaker Matrix6 cells13 rules6 anti6 hints
Determines how circuit breaker patterns protect against cascading failures β€” open/closed/half-open states, thresholds, and recovery probing.
breaker_statethresholdrecovery_probefallback
cb_001
When in closed state, allow all requests but count failures to determine if threshold is breached.
βœ… RULES (3)
Increment failure counter on 5xx errors
Track window duration (e.g. 30 seconds)
Transition to open on threshold breach
❌ ANTI-PATTERNS (1)
Not resetting failure count after successful window
πŸ’» CODE HINTS (1)
if (res.status >= 500) failures++
cb_002
When in open state, reject all incoming requests immediately and serve fallback response.
βœ… RULES (2)
Log rejection with timestamp
Serve cached or default fallback
❌ ANTI-PATTERNS (1)
Forwarding requests while in open state
πŸ’» CODE HINTS (1)
if (state === 'open') return fallbackResponse
cb_003
When transitioning to half-open state, allow limited requests through as probes to check if backend has recovered.
βœ… RULES (2)
Allow N test requests in half-open
Success resets breaker to closed, failure returns to open
❌ ANTI-PATTERNS (1)
Flooding backend with full traffic in half-open
πŸ’» CODE HINTS (1)
if (state === 'half_open' && probeQuota > 0) sendProbe()
cb_004
When configuring breaker, define failure threshold as X failures in Y seconds (e.g. 5 in 30s).
βœ… RULES (2)
Use rolling window for counting
Tune X and Y based on service SLO
❌ ANTI-PATTERNS (1)
Hardcoded threshold not tuned per endpoint
πŸ’» CODE HINTS (1)
threshold = { count: 5, window: 30s }
cb_005
When in half-open state, close breaker only after N consecutive successful responses (e.g. 3 OKs).
βœ… RULES (2)
Track consecutive 200 OK responses
Reset failure counter on successful recovery
❌ ANTI-PATTERNS (1)
Closing breaker after single success only
πŸ’» CODE HINTS (1)
if (consecutiveOKs >= 3) state = 'closed'
cb_006
When in open state, return fallback logic such as cached data, static message, or alternative path.
βœ… RULES (2)
Design fallback per endpoint category
Include alert or metric for fallback usage
❌ ANTI-PATTERNS (1)
Returning 500 without meaningful fallback
πŸ’» CODE HINTS (1)
return cachedResponse || staticPage
πŸ§ͺ VALIDATION
Verify: breaker counts failures in closed, rejects in open, probes in half-open, respects thresholds, closes on consecutive success, and fallback returns meaningful response.
#263Matrix 263 β€” Bulkhead Matrix6 cells18 rules18 anti6 hints
Define architectural patterns and safeguards to prevent cascading failure by isolating failures to specific subsystems or components.
isolation_unitresource_allocation_modelfailure_detectionoverflow_policyobservability_integrationrestart_recovery_policy
THREAD_POOL_ISOLATION
When service processes multiple kinds of workloads
βœ… RULES (3)
Allocate separate thread pools per operation type
Limit pool size with queue
Drop or timeout on overflow
❌ ANTI-PATTERNS (3)
Single thread pool for all requests
Unbounded queues
Blocking on IO in shared threads
πŸ’» CODE HINTS (1)
ExecutorService invoicesPool = newFixedThreadPool(5)
SERVICE_INSTANCE_SHARDING
When running replicated services across a fleet
βœ… RULES (3)
Partition load by tenant or shard
Use routing layer for isolation
Scale shards independently
❌ ANTI-PATTERNS (3)
All tenants on same shared instance
No boundaries between test and prod
One noisy client affects all
πŸ’» CODE HINTS (1)
route(userId % numShards) β†’ serviceInstance
ASYNC_WORKER_PARTITIONING
When running jobs in queue-based system
βœ… RULES (3)
Use topic or tag-based isolation
Create bounded queues per topic
Route failures to DLQ per stream
❌ ANTI-PATTERNS (3)
All jobs in same unbounded queue
Retry flood affecting healthy jobs
Mixing critical and non-critical job types
πŸ’» CODE HINTS (1)
consumer.subscribe(['billing-jobs'])
BULKHEAD_POLICY_OVERFLOW_STRATEGY
When bulkhead hits resource max (threads, memory, etc.)
βœ… RULES (3)
Return 429 or custom fallback
Apply circuit breaker if repeated
Log rejection reason with metrics
❌ ANTI-PATTERNS (3)
Crashing under overload
Failing silently
Retry storm without backoff
πŸ’» CODE HINTS (1)
bulkhead.reject(reason: 'maxConcurrency')
BULKHEAD_METRICS_AND_ALERTING
When monitoring isolation behavior
βœ… RULES (3)
Track queue fill, drop %, max concurrency
Alert on sustained overflow
Break down metrics by isolation zone
❌ ANTI-PATTERNS (3)
Aggregated metrics only
No alert until crash
No separation by context
πŸ’» CODE HINTS (1)
prometheus.bulkhead_rejections_total{zone='billing'}
RESTART_STRATEGY_PER_ISOLATED_UNIT
When component within bulkhead fails irrecoverably
βœ… RULES (3)
Supervise and restart failed module
Use failure domain boundaries
Preserve healthy peers
❌ ANTI-PATTERNS (3)
Full system reboot on single failure
No per-component error handling
State leak across isolation boundary
πŸ’» CODE HINTS (1)
supervisor.restart(failedWorker)
πŸ§ͺ VALIDATION
Simulate overload in isolated threads. Confirm rejection, alerting, restart, and no cascade.
#264Matrix 264 β€” Redundancy Matrix6 cells18 rules18 anti6 hints
Define redundancy strategies to improve service availability, data durability, and failover reliability across infrastructure and software layers.
redundancy_targetredundancy_typefailover_triggersync_modellatency_tolerancetesting_frequency
LOAD_BALANCED_SERVICE_INSTANCES
When running stateless microservices
βœ… RULES (3)
Deploy β‰₯2 replicas behind load balancer
Health check and remove failing node
Distribute traffic evenly
❌ ANTI-PATTERNS (3)
Single instance in prod
No health probe in load balancer
Sticky sessions without fallback
πŸ’» CODE HINTS (1)
nginx upstream { server app1; server app2; }
DATABASE_REPLICATION_PRIMARY_SECONDARY
When storing transactional data
βœ… RULES (3)
Use streaming replication or binlog shipping
Promote secondary on primary failure
Keep replica lag monitored
❌ ANTI-PATTERNS (3)
Single write node with no failover
No monitoring of replication lag
Allowing split brain
πŸ’» CODE HINTS (1)
replica.setReadOnly(true)
CROSS_ZONE_OBJECT_STORAGE
When storing large files or backups
βœ… RULES (3)
Use S3, GCS with cross-zone replication
Enable auto-repair of object copies
Monitor consistency across replicas
❌ ANTI-PATTERNS (3)
Keeping all data in single region
Relying on eventual consistency blindly
No verification of backup integrity
πŸ’» CODE HINTS (1)
aws s3api put-bucket-replication ...
ACTIVE_PASSIVE_SERVICE_FAILOVER
When active instance must hand off control
βœ… RULES (3)
Monitor heartbeat between peers
Trigger failover via script or orchestrator
Delay restore to prevent flip-flop
❌ ANTI-PATTERNS (3)
Both instances active simultaneously
No fencing after failover
Silent failover without alert
πŸ’» CODE HINTS (1)
keepalived + VRRP or Kubernetes readinessProbe
REDUNDANT_DNS_RESOLVERS
When resolving domain names for system traffic
βœ… RULES (3)
Configure β‰₯2 resolvers per host
Prefer geo-distributed DNS providers
Test resolution on both paths
❌ ANTI-PATTERNS (3)
Single /etc/resolv.conf entry
Depending on internal DNS only
No retries or failover logic
πŸ’» CODE HINTS (1)
resolv.conf: nameserver 8.8.8.8 nameserver 1.1.1.1
FAILOVER_TESTING_AND_SIMULATION
When validating that redundancy mechanisms work
βœ… RULES (3)
Run periodic failover drills
Simulate zone loss or crash
Record time to recovery (TTR)
❌ ANTI-PATTERNS (3)
Assuming failover will work
No test in production-like setting
No rollback path after failover
πŸ’» CODE HINTS (1)
chaos.run('zone-failure')
πŸ§ͺ VALIDATION
Simulate failure of service, DB, zone, or DNS. Measure time to failover. Confirm alerts and restored service without data loss.
#265Recovery Time Matrix6 cells12 rules6 anti6 hints
Determines recovery time objectives and strategies β€” RTO/RPO targets, automated recovery, and degraded mode duration limits.
recovery_metricautomation_leveldegraded_durationdata_loss_tolerance
recovery_001
When planning for disaster recovery, define RTO (Recovery Time Objective) β€” maximum acceptable downtime before services must be restored.
βœ… RULES (2)
Set RTO target per service class (e.g. 15 min for Tier 1)
Document recovery steps to meet RTO
❌ ANTI-PATTERNS (1)
No RTO target defined, relying on best effort
πŸ’» CODE HINTS (1)
recoveryPolicy: { service: 'checkout', RTO: '15m' }
recovery_002
When defining backup strategies, establish RPO (Recovery Point Objective) β€” maximum tolerable data loss in time units.
βœ… RULES (2)
Backups must occur at intervals ≀ RPO
Design database replication to meet RPO target
❌ ANTI-PATTERNS (1)
RPO exceeds backup frequency β†’ risk of unacceptable loss
πŸ’» CODE HINTS (1)
backup.schedule = 'every 5 min' // supports 5-min RPO
recovery_003
When critical service fails health check, trigger automatic failover to standby node to minimize downtime.
βœ… RULES (2)
Monitor heartbeat every 10s
Switch traffic to standby after 2 failures
❌ ANTI-PATTERNS (1)
Waiting for manual approval after failure
πŸ’» CODE HINTS (1)
if (!heartbeat.ok) β†’ switchTo('standby')
recovery_004
When automation is not available, follow manual recovery runbook to restore minimal service or reroute traffic.
βœ… RULES (2)
Document fallback DNS switch or redeploy steps
Keep runbook in version-controlled, accessible location
❌ ANTI-PATTERNS (1)
Undocumented procedures or tribal knowledge only
πŸ’» CODE HINTS (1)
runbook.md β†’ section: 'manual fallback to CDN cache'
recovery_005
When operating in degraded mode, auto-escalate incident if service not fully restored within defined window (e.g. 20 mins).
βœ… RULES (2)
Set degraded mode timeout per SLA
Page human operator if timeout exceeded
❌ ANTI-PATTERNS (1)
Staying in degraded mode indefinitely without escalation
πŸ’» CODE HINTS (1)
if (degraded && duration > 20m) escalateTo('SRE')
recovery_006
After service recovery, run smoke tests to verify core functionality is restored and validate no data corruption.
βœ… RULES (2)
Automate post-recovery tests for login, DB access, API ping
Block deploy if tests fail
❌ ANTI-PATTERNS (1)
Assuming system is healthy without verification
πŸ’» CODE HINTS (1)
ci/test/smoke.sh β†’ run after recovery hook
πŸ§ͺ VALIDATION
Verify: RTO/RPO are defined per service, failover triggers work on healthchecks, manual fallback documented, degraded mode escalates after threshold, and post-restore tests validate recovery.
#266Matrix 266 β€” Disaster Recovery Matrix6 cells18 rules18 anti6 hints
Define planning, execution, and validation practices for recovering services, infrastructure, and data after a catastrophic failure.
disaster_type_categoryrecovery_objective_typefailover_mechanismdata_restore_processteam_coordination_protocoldr_test_frequency
RPO_RTO_CLASSIFICATION
When determining acceptable loss and downtime
βœ… RULES (3)
Define Recovery Time Objective (RTO)
Define Recovery Point Objective (RPO)
Classify tiers of services
❌ ANTI-PATTERNS (3)
No defined SLAs for recovery
Same RTO for all systems
Missing stakeholder approval
πŸ’» CODE HINTS (1)
rtoMap = { 'payments': 5min, 'logs': 24h }
HOT_COLD_BACKUP_REGION_FAILOVER
When regional outage affects availability
βœ… RULES (3)
Maintain warm or cold standby infra
Replicate critical data with minimal lag
Automate DNS and orchestration failover
❌ ANTI-PATTERNS (3)
No alternate region configured
Manual failover without runbook
Live+DR serving mixed traffic
πŸ’» CODE HINTS (1)
aws route53 failover policy + warmRegion.activate()
OFFLINE_BACKUP_RESTORE_AND_VERIFICATION
When data loss requires recovery from backup
βœ… RULES (3)
Encrypt and store backups offsite
Verify backup integrity on rotation
Use sandbox to test restore before prod
❌ ANTI-PATTERNS (3)
Restoring from untested backups
No restore time estimation
Mutating backup copy before use
πŸ’» CODE HINTS (1)
restoreFrom(backup.snapshot).verifyIntegrity()
DISASTER_ROLES_AND_ESCALATION_LADDER
When coordinating DR response among teams
βœ… RULES (3)
Pre-assign roles (commander, comms, ops, auditor)
Use runbook escalation levels
Train DR leads on tools and context
❌ ANTI-PATTERNS (3)
No DR-specific org chart
Unclear who owns decision
Ping-all escalation
πŸ’» CODE HINTS (1)
incidentCommander.assign('DR-lead')
CROSS_TEAM_SIMULATION_AND TRAINING
When preparing for coordinated DR events
βœ… RULES (3)
Run multi-team chaos games
Time full DR run from detection to recovery
Debrief and patch gaps discovered
❌ ANTI-PATTERNS (3)
Testing only technical steps
No end-to-end drills
Ignoring human coordination
πŸ’» CODE HINTS (1)
chaosSim.run('region-loss-drill')
DOCUMENTED_AND_VERSIONED_DR_RUNBOOKS
When executing real or simulated DR
βœ… RULES (3)
Keep runbooks in version control
Update after every DR exercise
Link runbook to observability triggers
❌ ANTI-PATTERNS (3)
Stale or inaccessible DR docs
Tribal knowledge only
No postmortem feedback loop
πŸ’» CODE HINTS (1)
drDocs.get('restore-log-db-v2')
πŸ§ͺ VALIDATION
Run DR drill and record full timeline. Validate backup usability, regional switchover, runbook clarity, and team coordination effectiveness.
#267Matrix 267 β€” Reliability Testing Matrix6 cells18 rules18 anti6 hints
Define testing strategies that measure system resilience, correctness, and uptime guarantees under real-world and edge-case conditions.
test_typetrigger_conditionstarget_componentexpected_result_behaviormetrics_to_captureautomated_alerting
FAILURE_SIMULATION_TESTS
When validating component reaction to fault
βœ… RULES (3)
Inject network or DB fault
Verify error boundaries and fallbacks
Capture recovery time
❌ ANTI-PATTERNS (3)
Assuming try/catch is enough
No chaos validation in CI
Ignoring partial service failures
πŸ’» CODE HINTS (1)
simulate('db-down') β†’ expect fallback()
LATENCY_AND_THROUGHPUT_BENCHMARKS
When measuring system under load
βœ… RULES (3)
Run load test with ramp-up
Track p95/p99 latency
Test with real API and data paths
❌ ANTI-PATTERNS (3)
Testing only hello world
Ignoring tail latency
Same concurrency for all endpoints
πŸ’» CODE HINTS (1)
k6 run loadtest.js
CAPACITY_LIMIT_TESTING
When reaching upper bounds of known capacity
βœ… RULES (3)
Exceed memory, connection, queue limits
Trigger rejection handlers
Measure error rate and recovery
❌ ANTI-PATTERNS (3)
Guessing capacity in production
Crashing on overflow
No circuit breakers triggered
πŸ’» CODE HINTS (1)
simulateLoad({ users: 100k })
AVAILABILITY_TESTING_ON_DEPLOY
When releasing new code to live environment
βœ… RULES (3)
Run smoke tests post-deploy
Validate status and health checks
Block promotion on critical error
❌ ANTI-PATTERNS (3)
Assuming success without test
No metrics on post-deploy stability
Silent failure in background jobs
πŸ’» CODE HINTS (1)
canary.test('smoke-basic')
REAL_WORLD_TRAFFIC_REPLAY
When validating edge cases or legacy compatibility
βœ… RULES (3)
Record and replay past traffic
Compare output vs golden results
Detect unintended changes
❌ ANTI-PATTERNS (3)
Testing only happy path
No control group to compare
Replaying outdated versions only
πŸ’» CODE HINTS (1)
replayTraffic('2023-12-10')
SLA_METRIC_ALERTING_FROM_TESTS
When monitoring test-derived metrics
βœ… RULES (3)
Integrate test suite with metrics pipeline
Emit alert if SLA breached
Correlate test failures with incidents
❌ ANTI-PATTERNS (3)
Test metrics not reaching Grafana
No alerting from test failure
Monitoring only prod traffic
πŸ’» CODE HINTS (1)
prometheus.push({ name: 'p95_latency', value: 120 })
πŸ§ͺ VALIDATION
Run suite simulating real traffic, fault injection, deploy and rollback. Confirm metrics, alerts, logs, and system response match expectations.
#268Matrix 268 β€” Chaos Engineering Matrix6 cells18 rules18 anti6 hints
Define controlled fault injection strategies that uncover hidden failure modes and increase system resilience.
fault_typeinjection_methodtarget_scopeblast_radius_controlrollback_strategyobservability_hooks
NETWORK_LATENCY_AND_DROP
When testing network instability
βœ… RULES (3)
Inject latency or drop at network layer
Scope to specific IPs or services
Monitor retry logic and fallback
❌ ANTI-PATTERNS (3)
Global packet loss
No rollback once fault injected
Silent failure on timeout
πŸ’» CODE HINTS (1)
tc qdisc add dev eth0 netem delay 250ms loss 5%
CPU_MEMORY_EXHAUSTION
When validating resource limits
βœ… RULES (3)
Run background job that fills memory or burns CPU
Apply only in sandboxed container
Measure health, latency, GC behavior
❌ ANTI-PATTERNS (3)
Running on host with no isolation
Impacting unrelated services
Letting job run unbounded
πŸ’» CODE HINTS (1)
chaos.inject('memory-hog', scope='service-A')
SERVICE_TERMINATION_AND_RESTART
When simulating crash or forced kill
βœ… RULES (3)
Send SIGKILL or delete pod
Observe system recovery and traffic impact
Check readiness probes and requeue logic
❌ ANTI-PATTERNS (3)
Disabling health probes
Not monitoring restart time
Failing jobs post-restart
πŸ’» CODE HINTS (1)
kubectl delete pod service-a-xyz
DEPENDENCY_BLACKHOLE
When testing third-party unavailability
βœ… RULES (3)
DNS override to blackhole target
Use dummy TCP dropper
Validate timeout and circuit breaker activation
❌ ANTI-PATTERNS (3)
Waiting forever on dependency
No SLA threshold
Breaking core user flow
πŸ’» CODE HINTS (1)
/etc/hosts β†’ 127.0.0.1 api.partner.com
BLAST_RADIUS_AND_AUDIT_TRAIL
When running any chaos experiment
βœ… RULES (3)
Tag and scope chaos to test env or shard
Log affected resources and outcomes
Gate chaos on approval or trigger
❌ ANTI-PATTERNS (3)
Running chaos in prod without scope
Lack of logs or rollback
Lack of observability hooks
πŸ’» CODE HINTS (1)
chaos.log({ scope: 'staging', fault: 'svc-unavail' })
RECOVERY_AND_FALLBACK_VERIFICATION
When observing chaos aftermath
βœ… RULES (3)
Check dashboards for auto-recovery
Verify SLA and latency graphs
Validate logs and fallback code paths
❌ ANTI-PATTERNS (3)
No verification after chaos run
Silent success
False recovery without end-user test
πŸ’» CODE HINTS (1)
assert(metrics['latency'] < threshold)
πŸ§ͺ VALIDATION
Inject faults across network, CPU, service, and dependency. Confirm recovery, observability, blast radius control, and rollback.
#269Matrix 269 β€” Security Monitoring Matrix6 cells18 rules18 anti6 hints
Define monitoring strategies for detecting threats, misconfigurations, and suspicious activity across systems, networks, and applications.
monitoring_targetsignal_typetooling_integrationalert_thresholdsfalse_positive_handlingaudit_and_response_hooks
APPLICATION_LOG_MONITORING
When capturing auth and error events from apps
βœ… RULES (3)
Log login attempts, errors, auth failures
Stream logs to SIEM or aggregator
Alert on pattern match or frequency spike
❌ ANTI-PATTERNS (3)
Only storing logs locally
Ignoring 401/403 trends
Logging PII without masking
πŸ’» CODE HINTS (1)
logger.warn('unauthorized', { user, ip })
FIREWALL_AND_NETWORK_TRAFFIC_ALERTING
When guarding infrastructure ingress/egress
βœ… RULES (3)
Monitor connection spikes, blocked ports
Alert on outbound anomalies
Correlate with flow logs
❌ ANTI-PATTERNS (3)
Unmonitored VPCs or security groups
No egress controls
Accepting connections on all interfaces
πŸ’» CODE HINTS (1)
cloudwatch.metric('ConnectionsOut')
CLOUD_CONFIG_DRIFT_DETECTION
When managing cloud infra via IaC
βœ… RULES (3)
Run drift detection regularly
Compare live state to IaC plan
Alert on manual edits outside CI/CD
❌ ANTI-PATTERNS (3)
Manual console edits in prod
No check between deploys
Letting misconfig linger silently
πŸ’» CODE HINTS (1)
terraform plan --detailed-exitcode
ENDPOINT_BEHAVIORAL_MONITORING
When defending user devices or servers
βœ… RULES (3)
Monitor process trees, syscalls, file access
Use EDR with alerting
Correlate with identity and time
❌ ANTI-PATTERNS (3)
Relying on signature AV only
No visibility into behavioral traces
Ignoring suspicious child process patterns
πŸ’» CODE HINTS (1)
edr.track('suspicious_exec', context)
USER_PRIVILEGE_ESCALATION_WATCH
When monitoring identity and access controls
βœ… RULES (3)
Log role changes, sudo grants, policy edits
Set alerts on admin grants outside deploy window
Notify user and security team on escalation
❌ ANTI-PATTERNS (3)
Silent role or ACL changes
Bundling access logs without analysis
No alert when IAM policy changes
πŸ’» CODE HINTS (1)
cloudtrail.filter(eventType='PolicyChange')
SECURITY_MONITORING_ALERT_CLASSIFICATION
When reviewing alerts from various security tools
βœ… RULES (3)
Tag alerts by severity, source, asset
Deduplicate noisy alerts
Route actionable items to correct team
❌ ANTI-PATTERNS (3)
All alerts treated equal
Email-only alerting
No closed-loop on alert resolution
πŸ’» CODE HINTS (1)
alert.route({ severity: 'high', team: 'secops' })
πŸ§ͺ VALIDATION
Trigger alerts through simulated events. Confirm logging, alert delivery, triage, classification, and correlation across layers.
#270Matrix 270 β€” Incident Response Matrix6 cells18 rules18 anti6 hints
Define structured, time-bound, and role-specific protocols for responding to security or availability incidents.
incident_type_categoryinitial_detection_methodtriage_and_severity_policyresponse_team_rolescommunication_protocolpostmortem_and_learning
AUTOMATED_ALERT_TO_ONCALL_ESCALATION
When incident is detected by monitoring system
βœ… RULES (3)
Route to on-call immediately via paging
Escalate if no response in N minutes
Log acknowledgement and start time
❌ ANTI-PATTERNS (3)
Email-only notification
No alert routing metadata
No fallback if pager fails
πŸ’» CODE HINTS (1)
alertmanager.route({ severity: 'critical' })
INCIDENT_COMMANDER_ROLE_ASSIGNMENT
When active incident is confirmed
βœ… RULES (3)
Assign IC within 5 minutes
Define clear handoff procedure
IC owns comms, response, closure
❌ ANTI-PATTERNS (3)
No designated IC
Ping-all response swarm
No authority to take action
πŸ’» CODE HINTS (1)
incident.assignCommander('oncall-lead')
SEVERITY_TRIAGE_GUIDELINES
When assessing impact and urgency
βœ… RULES (3)
Use criteria: users affected, systems, duration
Update severity if conditions change
Track severity for postmortem analysis
❌ ANTI-PATTERNS (3)
One severity for all alerts
No downgrade/upgrade allowed
No link between severity and process
πŸ’» CODE HINTS (1)
incident.severity = assessSeverity(metrics)
LIVE_STATUS_PAGE_AND_UPDATES
When incident impacts users or external systems
βœ… RULES (3)
Publish status within X minutes of impact
Update every 30 min or on milestone
Clarify known scope and actions
❌ ANTI-PATTERNS (3)
No user comms during downtime
Infrequent updates
Using vague or blameful language
πŸ’» CODE HINTS (1)
statusPage.update({ state: 'investigating' })
POSTMORTEM_TEMPLATE_AND_RITUAL
When incident is resolved and closed
βœ… RULES (3)
Use template: timeline, root cause, impact, fix
Hold review with stakeholders
Track action items and owners
❌ ANTI-PATTERNS (3)
No postmortem for sev3+
No documented root cause
No follow-up on action items
πŸ’» CODE HINTS (1)
postmortem.create('incident-270-template')
INCIDENT_METRICS_AND_TTR_TRACKING
When managing SLOs for incident handling
βœ… RULES (3)
Track MTTA, MTTR, and resolution duration
Correlate metrics with team load
Include in quarterly review
❌ ANTI-PATTERNS (3)
No measurement of response
Only count # of incidents
No visibility into regressions
πŸ’» CODE HINTS (1)
metrics.push({ mtta: 4min, mttr: 42min })
πŸ§ͺ VALIDATION
Simulate alert, triage, user impact, and postmortem. Confirm paging, role assignment, severity handling, status page update, and metric tracking.
β–Ό πŸ› οΈ L10 β€” Build/Ops 30 matrices
#271Build Pipeline Matrix6 cells12 rules8 anti8 hints
Determines how code is built, bundled, tested, and deployed β€” pipeline stages, artifact management, and CI/CD automation.
pipeline_stageautomation_levelartifact_typeenvironment_target
build_001
When validating code on each push, run lint and type-check as a mandatory automated stage in the CI pipeline.
βœ… RULES (2)
Run ESLint and TypeScript in parallel
Fail pipeline on any type or lint error
❌ ANTI-PATTERNS (1)
Skipping lint/type-check in CI and relying only on local dev tools
πŸ’» CODE HINTS (1)
npm run lint && tsc --noEmit
build_002
When code is pushed to feature branches, run unit tests automatically with coverage check.
βœ… RULES (2)
Set coverage threshold (e.g. 80%)
Fail build if test suite fails or coverage too low
❌ ANTI-PATTERNS (2)
Allowing unit test failures to pass CI
No coverage enforcement
πŸ’» CODE HINTS (2)
jest --coverage
nyc --check-coverage
build_003
When bundling application for production, use a bundler (e.g. Webpack or Vite) with optimized config and output artifact.
βœ… RULES (2)
Use mode=production for minification
Emit static assets to dist/ with hash in filenames
❌ ANTI-PATTERNS (1)
Building without minification or versioned assets
πŸ’» CODE HINTS (2)
vite build --mode production
webpack --config webpack.prod.js
build_004
When CI runs in staging env, run integration tests automatically with real services or mocks.
βœ… RULES (2)
Run tests against deployed staging env or docker-compose
Use environment flag to differentiate staging logic
❌ ANTI-PATTERNS (2)
Running integration tests only locally
Testing with mocked backend in staging
πŸ’» CODE HINTS (1)
npm run test:integration -- --env=staging
build_005
When storing build artifacts, tag versions using SemVer and upload to artifact store (e.g. S3, Nexus).
βœ… RULES (2)
Use git tag or commit hash in artifact version
Store immutable builds per version
❌ ANTI-PATTERNS (1)
Overwriting same artifact for different code versions
πŸ’» CODE HINTS (1)
aws s3 cp dist/ s3://my-artifacts/v1.2.3/
build_006
When promoting to production, require manual approval after passing staging deployment and smoke tests.
βœ… RULES (2)
Deploy to staging automatically
Gate production deployment behind manual approval step
❌ ANTI-PATTERNS (1)
Auto-deploying to production without human review
πŸ’» CODE HINTS (1)
deploy --env staging β†’ approval β†’ deploy --env production
πŸ§ͺ VALIDATION
Verify: all stages run on push/merge, lint/test/build fail fast, artifacts versioned immutably, deploys require approval before production.
#272Dependency Resolution Matrix6 cells12 rules6 anti7 hints
Determines how project dependencies are resolved, locked, and audited β€” version pinning, lock files, and vulnerability scanning.
resolution_strategylock_mechanismaudit_policyupdate_cadence
depres_001
When targeting build stability, pin exact dependency versions (no ^/~) and commit lockfile for reproducibility.
βœ… RULES (2)
Use exact versions in package.json
Disallow semver ranges (e.g. ^1.2.3)
❌ ANTI-PATTERNS (1)
Using ^ or ~ which allow implicit upgrades
πŸ’» CODE HINTS (1)
npm install lodash@1.2.3 --save-exact
depres_002
When running CI pipelines, verify that lockfile is committed and unchanged to ensure dependency integrity.
βœ… RULES (2)
Run npm ci to install strictly from lockfile
Fail build if package-lock.json or yarn.lock modified
❌ ANTI-PATTERNS (1)
Running npm install in CI, which may alter lockfile
πŸ’» CODE HINTS (2)
npm ci
git diff --exit-code package-lock.json
depres_003
When scanning dependencies for security, block builds on high or critical severity CVEs.
βœ… RULES (2)
Run 'npm audit --json' in CI
Set severity threshold for failure
❌ ANTI-PATTERNS (1)
Ignoring audit output in production pipelines
πŸ’» CODE HINTS (1)
npm audit --audit-level=critical
depres_004
When using packages that declare peer dependencies, resolve and install them explicitly to avoid runtime warnings.
βœ… RULES (2)
Read peerDependencies field in package.json
Install required peer manually at compatible version
❌ ANTI-PATTERNS (1)
Ignoring peer dependency warnings during install
πŸ’» CODE HINTS (1)
npm install react@17 react-dom@17
depres_005
When maintaining dependency freshness, use Dependabot/Renovate to open scheduled PRs with version bumps.
βœ… RULES (2)
Set schedule to weekly or biweekly
Enable auto-merge for patch updates if tests pass
❌ ANTI-PATTERNS (1)
Manual update tracking or ignoring outdated deps
πŸ’» CODE HINTS (1)
.github/dependabot.yml β†’ schedule.interval: 'weekly'
depres_006
When securing builds, add explicit audit check steps to CI and fail on policy violations.
βœ… RULES (2)
Add audit step in CI config file (e.g. GitHub Actions, GitLab CI)
Fail build if audit step fails
❌ ANTI-PATTERNS (1)
Omitting audit from CI jobs
πŸ’» CODE HINTS (1)
jobs: audit: steps: - run: npm audit --audit-level=high
πŸ§ͺ VALIDATION
Verify: versions pinned without ^, lockfile enforced in CI, audits block critical CVEs, peer deps resolved, updates flow via PRs, and CI enforces audit step.
#273Matrix 273 β€” Version Pinning Matrix6 cells18 rules18 anti6 hints
Define rules and strategies for pinning dependency versions across environments, tools, containers, and services.
artifact_typepinning_methodupdate_policyverification_strategyrollback_preparednessautomated_enforcement
LIBRARY_DEPENDENCY_LOCKFILE
When managing package.json or requirements.txt
βœ… RULES (3)
Use lockfiles (package-lock.json, Pipfile.lock)
Commit lockfile to repo
Regenerate only via CI or PR
❌ ANTI-PATTERNS (3)
Using ^ or ~ for core packages
No lockfile checked in
Manual edits to lockfile
πŸ’» CODE HINTS (1)
npm ci; pipenv install --ignore-pipfile
CONTAINER_IMAGE_DIGEST_PINNING
When deploying services via Docker or K8s
βœ… RULES (3)
Pin to image SHA256 digest
Tag only in CI/CD process
Rebuild on base image update
❌ ANTI-PATTERNS (3)
Using :latest in production
Reusing mutable tags across versions
Not verifying image digest
πŸ’» CODE HINTS (1)
image: myservice@sha256:abc123...
INFRASTRUCTURE_MODULE_VERSIONING
When using Terraform or similar IaC tools
βœ… RULES (3)
Pin module to exact version
Update via PR with test plan
Use version constraints consciously
❌ ANTI-PATTERNS (3)
Unversioned git refs
Modules on main branch
Auto-pull without review
πŸ’» CODE HINTS (1)
source = "github.com/org/module?ref=v1.2.3"
TOOLCHAIN_AND_CLI_VERSION_LOCK
When building or deploying via local/dev CI
βœ… RULES (3)
Specify versions in toolchain config (e.g. .nvmrc, .python-version)
Pin CI base images or tools
Validate CLI version during run
❌ ANTI-PATTERNS (3)
No version enforcement in local env
Mixing multiple tool versions
Drift between local and CI env
πŸ’» CODE HINTS (1)
asdf install nodejs 18.14.1
ROLLBACK_TESTING_AND_CACHING
When updating pinned version via PR or deploy
βœ… RULES (3)
Cache previous version artifact
Tag rollback point in version control
Document rollback command
❌ ANTI-PATTERNS (3)
No test of rollback flow
No record of prior state
Rollback requires rebuild
πŸ’» CODE HINTS (1)
git revert -m 1 HEAD; helm rollback service 42
VERSION_PINNING_ENFORCEMENT_PIPELINE
When reviewing PRs or deploying to staging
βœ… RULES (3)
Lint for unpinned or floating versions
Gate deploy on SHA or lockfile diff
Alert on indirect upgrade in lockfile
❌ ANTI-PATTERNS (3)
Deploying without reviewing lockfile diff
Floating tool versions in CI
Auto-merge without version check
πŸ’» CODE HINTS (1)
diff-lockfiles.sh; helm diff upgrade
πŸ§ͺ VALIDATION
Force drift in test branch and validate enforcement. Revert pinned versions and ensure system recovers correctly.
#274Build Reproducibility Matrix6 cells12 rules6 anti7 hints
Determines how builds are made reproducible β€” deterministic outputs, pinned tools, cached artifacts, and environment parity.
determinism_methodcache_strategyenvironment_parityverification
buildrepro_001
When installing dependencies, enforce deterministic installs using lockfiles (e.g. package-lock.json or pnpm-lock.yaml).
βœ… RULES (2)
Commit lockfile to version control
CI must fail if lockfile drift detected
❌ ANTI-PATTERNS (1)
Reinstalling with different versions without lockfile
πŸ’» CODE HINTS (2)
npm ci
pnpm install --frozen-lockfile
buildrepro_002
When building across environments, use Docker multi-stage builds to ensure identical tooling across local, CI, and prod.
βœ… RULES (2)
Pin base image and tool versions
Keep Dockerfile stages clean and minimal
❌ ANTI-PATTERNS (1)
Running builds outside container in CI
πŸ’» CODE HINTS (1)
FROM node:18-alpine as builder
buildrepro_003
When optimizing large mono-repos, use build system cache (e.g. Turborepo/Nx) to skip unchanged steps and maintain consistency.
βœ… RULES (2)
Enable remote cache with access token
Cache build outputs per task graph
❌ ANTI-PATTERNS (1)
Re-running all steps even if inputs unchanged
πŸ’» CODE HINTS (1)
npx turbo run build --cache
buildrepro_004
When verifying build outputs, use content-addressable hashes (e.g. SHA-256) to fingerprint artifacts and detect drift.
βœ… RULES (2)
Hash file content before publishing
Fail if hash differs from baseline
❌ ANTI-PATTERNS (1)
Trusting timestamps or file size alone for diffs
πŸ’» CODE HINTS (1)
shasum -a 256 dist/*.js
buildrepro_005
When targeting reproducibility, pin Node.js and npm versions using .nvmrc or engines field to ensure matching runtime behavior.
βœ… RULES (2)
Check Node version in CI
Document expected versions for contributors
❌ ANTI-PATTERNS (1)
Using whatever Node version happens to be installed
πŸ’» CODE HINTS (1)
.nvmrc 18.17.1
buildrepro_006
When validating reproducibility, hash and compare output directories across repeated builds to detect non-determinism.
βœ… RULES (2)
Run builds twice in CI and compare artifact hashes
Diff output content byte-by-byte
❌ ANTI-PATTERNS (1)
Assuming output is the same without verification
πŸ’» CODE HINTS (1)
diff <(tar -cf - dist1) <(tar -cf - dist2)
πŸ§ͺ VALIDATION
Verify: builds run with lockfiles, hashes match across runs, Docker used for parity, remote cache effective, Node versions fixed, and diff tools confirm deterministic output.
#275Environment Parity Matrix6 cells18 rules18 anti6 hints
Define strategies to ensure dev, staging, and production environments remain consistent β€” covering infrastructure, configuration, data, tooling, and behavioral alignment to prevent "works on my machine" issues.
infrastructure_alignmentconfiguration_consistencydata_parity_strategytoolchain_matchingbehavioral_drift_detectionenvironment_promotion_policy
INFRASTRUCTURE_AS_CODE_ENFORCEMENT
When provisioning dev, staging, and prod environments
βœ… RULES (3)
Use shared IaC templates across all stages
Parameterize for environment-specific values only
Validate infra drift regularly
❌ ANTI-PATTERNS (3)
Manual setup of environments
Unversioned infra changes
Multiple diverging IaC templates
πŸ’» CODE HINTS (1)
terraform.workspace('staging')
CONFIGURATION_SOURCE_OF_TRUTH
When managing app config across environments
βœ… RULES (3)
Use a central config service
Define shared base + env override layers
Audit config changes for all environments
❌ ANTI-PATTERNS (3)
Inline config in source code
Untracked config changes in staging
Mismatch between local and deployed config
πŸ’» CODE HINTS (1)
config.load('base.yaml').merge('staging.yaml')
DATA_PARITY_SEEDING_AND_MASKING
When replicating prod-like data in lower environments
βœ… RULES (3)
Use masked snapshots of prod for staging
Seed development DBs with realistic synthetic data
Automate periodic refresh and validation
❌ ANTI-PATTERNS (3)
Empty dev DBs
Old staging data that drifts
PII copied directly to staging
πŸ’» CODE HINTS (1)
data.clone('prod').mask().load('staging')
TOOLCHAIN_AND_RUNTIME_MATCHING
When using different local tools than prod
βœ… RULES (3)
Match language/runtime versions
Pin CLI and build tool versions
Use dockerized toolchain if needed
❌ ANTI-PATTERNS (3)
Dev uses Node 18, prod uses Node 16
Floating version tags in CI
Tool install steps differ between dev and CI
πŸ’» CODE HINTS (1)
nodeenv -p 16.20.0
BEHAVIORAL_DIFF_MONITORING
When app behaves differently across environments
βœ… RULES (3)
Mirror test suites in staging and prod
Monitor logs/metrics for behavior anomalies
Compare API schema responses across envs
❌ ANTI-PATTERNS (3)
Prod-only bugs not reproducible
No synthetic traffic in staging
Tests skipped in CI but required in prod
πŸ’» CODE HINTS (1)
diff.apiResponse('staging', 'prod')
PROMOTION_PIPELINE_AND_TAGGING
When releasing code from dev β†’ staging β†’ prod
βœ… RULES (3)
Promote builds via verified CI pipeline
Tag artifacts per environment stage
Block manual deploys to prod
❌ ANTI-PATTERNS (3)
Direct prod deploy from laptop
No artifact provenance
No gating between environments
πŸ’» CODE HINTS (1)
ci.promote('build-123', from='staging', to='prod')
πŸ§ͺ VALIDATION
Deploy identical artifact to dev/staging/prod. Confirm config parity, data masking, toolchain match, and behavioral consistency across environments.
#276Configuration Injection Matrix6 cells13 rules7 anti6 hints
Determines how configuration is injected at build and runtime β€” env vars, config files, secrets management, and per-environment overrides.
injection_methodsecret_handlingenvironment_scopevalidation
configinj_001
When using .env files during local development, keep sensitive values out of source control and ensure plaintext vars are filtered from logs.
βœ… RULES (3)
Use dotenv or env-cmd to load env files
Add .env to .gitignore
Do not log full config dumps in production
❌ ANTI-PATTERNS (2)
Checking .env files into git
Printing process.env to console
πŸ’» CODE HINTS (1)
require('dotenv').config()
configinj_002
When deploying to Kubernetes, inject configuration via ConfigMap volume mounts or env vars scoped to deployment namespace.
βœ… RULES (2)
Mount ConfigMap into /etc/config or inject via env
Separate per-namespace config objects
❌ ANTI-PATTERNS (1)
Hardcoding config into container images
πŸ’» CODE HINTS (1)
envFrom: configMapRef: name: app-config
configinj_003
When managing secrets, use a system like Vault or AWS Secrets Manager to store encrypted secrets outside app codebase.
βœ… RULES (2)
Do not store secrets in config files or env directly
Fetch at runtime using secure SDK/client
❌ ANTI-PATTERNS (1)
Storing DB_PASSWORD in plaintext in config.js
πŸ’» CODE HINTS (1)
aws-sdk β†’ getSecretValue({ SecretId })
configinj_004
When deploying across multiple environments, allow per-env overrides (e.g. .env.development, .env.production).
βœ… RULES (2)
Load base config first, then override with env-specific file
Use NODE_ENV or APP_ENV to drive logic
❌ ANTI-PATTERNS (1)
Single flat config file across all environments
πŸ’» CODE HINTS (1)
dotenv-flow or dotenv-expand
configinj_005
When application starts, validate loaded config against a schema to fail fast on missing/invalid values.
βœ… RULES (2)
Use Zod, Joi, or Yup to define config shape
Abort startup if required vars missing
❌ ANTI-PATTERNS (1)
Silent fallback to defaults without validation
πŸ’» CODE HINTS (1)
configSchema.parse(process.env)
configinj_006
When enabling/disabling features at runtime, inject config via feature flag service that supports remote toggles.
βœ… RULES (2)
Use LaunchDarkly, Unleash, or custom toggle client
Flags must default safely if remote fetch fails
❌ ANTI-PATTERNS (1)
Hardcoded feature branching in code without toggles
πŸ’» CODE HINTS (1)
if (flags.isEnabled('betaMode')) { ... }
πŸ§ͺ VALIDATION
Verify: .env excluded from SCM, K8s config injected via ConfigMap, secrets stored in manager, per-env overrides load, config schema validated on boot, feature flags toggle remotely.
#277Matrix 277 β€” Runtime Configuration Matrix6 cells18 rules18 anti6 hints
Define safe, flexible, and observable practices for handling runtime configuration across environments and deployment stages.
config_typesource_backendoverride_mechanismvalidation_and_schemachange_propagationaudit_and_rollbacks
ENV_VARS_FOR_STATIC_BOOT_CONFIG
When setting fixed values used on service start
βœ… RULES (3)
Use environment variables via injection
Set via deployment YAML or .env files
Avoid secrets or dynamic flags here
❌ ANTI-PATTERNS (3)
Overloading env vars with live flags
Reading env vars dynamically during runtime
Spreading config across scripts
πŸ’» CODE HINTS (1)
ENV PORT=3000 node app.js
CENTRALIZED_RUNTIME_CONFIG_SERVICE
When needing to update config without redeploy
βœ… RULES (3)
Use Consul, etcd, Firebase, or internal config server
Load config on boot and poll or subscribe
Tag configs by env, stage, or region
❌ ANTI-PATTERNS (3)
Hardcoded config in app logic
Manual JSON file editing in containers
No source of truth across instances
πŸ’» CODE HINTS (1)
configClient.get('feature.split.payments')
SCHEMA_VALIDATION_FOR_CONFIG_INPUTS
When loading external configuration at runtime
βœ… RULES (3)
Define config schemas via JSON Schema or Zod
Validate config before use
Log and reject on schema failure
❌ ANTI-PATTERNS (3)
Blindly trusting config shape
No test coverage for config edge cases
Fixing config bugs in code logic
πŸ’» CODE HINTS (1)
z.object({ maxItems: z.number() })
CONFIG_OVERRIDES_VIA_ENV_OR_FLAGS
When needing temporary override without rebuild
βœ… RULES (3)
Support local overrides via ENV, CLI flags, or shell
Precedence order: CLI > ENV > config
Expire overrides after N time or deploy
❌ ANTI-PATTERNS (3)
Overrides without expiry
Unknown override sources in prod
Overrides changing app semantics
πŸ’» CODE HINTS (1)
DEBUG=true MAX_RETRY=0 node service.js
CONFIG_REFRESH_AND_PROPAGATION_POLICY
When config is mutable or remotely controlled
βœ… RULES (3)
Use pub/sub or polling for config change
Notify and revalidate live instances
Track version ID of active config
❌ ANTI-PATTERNS (3)
Stale config across cluster
Out-of-band config writes
Restart required for trivial changes
πŸ’» CODE HINTS (1)
configClient.watch(key, onUpdate)
CONFIG_CHANGE_AUDIT_AND_ROLLBACKS
When config change might cause downtime
βœ… RULES (3)
Record change history with author and time
Allow restore of prior config versions
Correlate config with incidents
❌ ANTI-PATTERNS (3)
Config changes without logging
No link between deploy and config
One-way config mutations
πŸ’» CODE HINTS (1)
audit.logChange('config', diff, user)
πŸ§ͺ VALIDATION
Simulate bad config, drift, and rollback. Observe refresh timing, override correctness, audit trail, and resilience to malformed input.
#278Matrix 278 β€” Feature Flags Matrix6 cells18 rules18 anti6 hints
Define patterns for safely managing, deploying, and observing feature flags and toggles.
flag_typescoping_modelevaluation_methodpersistence_and_sourcevisibility_and_metricssunset_and_cleanup
BOOLEAN_RELEASE_TOGGLE
When gradually rolling out a feature
βœ… RULES (3)
Use simple true/false flag
Evaluate at runtime per user/session
Default to false in staging
❌ ANTI-PATTERNS (3)
Hardcoded flag checks
Flip flag without user targeting
No rollback on error spike
πŸ’» CODE HINTS (1)
if (flags.get('checkout_v2')) { ... }
SEGMENTED_AUDIENCE_FLAGGING
When flag behavior depends on user or account
βœ… RULES (3)
Target by user attributes (plan, region, ID hash)
Assign buckets using consistent hash
Evaluate flag in SDK or server middleware
❌ ANTI-PATTERNS (3)
All users treated equally
No attribution on user exposure
Manual targeting per feature
πŸ’» CODE HINTS (1)
getFlag('beta_ui', user)
REMOTE_FLAG_EVALUATION
When flag state is controlled from config backend
βœ… RULES (3)
Use hosted config/flag service (e.g. LaunchDarkly, Unleash)
Sync periodically or via push
Tag flags with version and environment
❌ ANTI-PATTERNS (3)
Hardcoded booleans in code
Flags toggled via app redeploy
No monitoring of flag health
πŸ’» CODE HINTS (1)
flagsClient.evaluate('dark_mode')
FLAG_USAGE_LOGGING_AND_METRICS
When flag state may impact behavior or stability
βœ… RULES (3)
Log flag state with each event
Expose flag exposure in dashboards
Alert on correlation with regressions
❌ ANTI-PATTERNS (3)
No correlation between flags and metrics
Flags changed with no visibility
Missing logs for flag evaluation path
πŸ’» CODE HINTS (1)
log.event('signup', { ff_signup_v3: true })
SHORT_LIVED_EXPERIMENT_TOGGLES
When using flags for A/B or experimentation
βœ… RULES (3)
Expire flags with analysis window
Use structured exposure logging
Clean up after test ends
❌ ANTI-PATTERNS (3)
Abandoned flags post-test
Experiment logic left in prod
Mixed targeting logic across tests
πŸ’» CODE HINTS (1)
flags.cleanup('exp_checkout_variant_4')
FLAG_RETIREMENT_AND_DELETION_POLICY
When long-lived flags accumulate in code
βœ… RULES (3)
Track flag ownership and lifetime
Review flags quarterly
Remove stale toggles with audit
❌ ANTI-PATTERNS (3)
Flags used as permanent config
No owner or documentation
Unused flags never deleted
πŸ’» CODE HINTS (1)
flagRegistry.prune({ unusedForDays: 90 })
πŸ§ͺ VALIDATION
Flip flags in staging and prod, observe logging, metric shifts, and rollback behavior. Confirm cleanup after flag deprecation.
#279Matrix 279 β€” Startup Sequence Matrix6 cells18 rules18 anti6 hints
Define the order, gating, and fallback of service boot processes and critical init routines.
init_stepblocking_vs_nonblockinghealthcheck_integrationfallback_on_failureparallelization_safetylogging_and_metrics
CONFIG_LOAD_AND_VALIDATE
When initializing from environment or config store
βœ… RULES (3)
Fail fast on missing or invalid config
Use schema validation and defaults
Log config version and source
❌ ANTI-PATTERNS (3)
Silent fallback to hardcoded values
Boot continues with broken config
No metrics on config freshness
πŸ’» CODE HINTS (1)
config.load(); config.validate()
DEPENDENCY_CONNECT_AND_TIMEOUT
When connecting to DB, cache, queue, etc.
βœ… RULES (3)
Apply timeout and retry budget
Log connection attempts and latency
Defer non-critical dependencies to post-start
❌ ANTI-PATTERNS (3)
Waiting forever on unavailable service
Failing silently on bad credentials
No differentiation between optional and critical
πŸ’» CODE HINTS (1)
await connectWithTimeout(db, 5s)
PRE_WARM_CACHE_AND_INDEX
When populating local memory for fast response
βœ… RULES (3)
Load recent or hot items
Run async and gate traffic until ready
Track warmup duration
❌ ANTI-PATTERNS (3)
Traffic before cache warm
Blocking forever on external pre-warm
No retry budget for pre-warm task
πŸ’» CODE HINTS (1)
await cache.warm('last24hr')
HEALTHCHECK_REGISTRATION_AND SIGNALING
When app signals readiness to orchestrator
βœ… RULES (3)
Delay ready signal until core init completes
Expose /healthz and /readyz endpoints
Remove from load balancer on init failure
❌ ANTI-PATTERNS (3)
Readiness check returns before init
No way to block traffic from LB
No liveness probes during boot
πŸ’» CODE HINTS (1)
k8s.readinessGate('cacheReady')
BACKGROUND_TASK_SCHEDULING_POST_BOOT
When starting non-critical jobs or pollers
βœ… RULES (3)
Defer until core boot passes
Tag background jobs for monitoring
Allow optional failure or retry logic
❌ ANTI-PATTERNS (3)
Running background jobs before init
Boot blocked by metrics emitter startup
No tagging or logging for async threads
πŸ’» CODE HINTS (1)
startBackground('reportScheduler')
BOOT_METRICS_AND_LOG_SEQUENCING
When needing insight into boot time behavior
βœ… RULES (3)
Emit structured boot stage logs
Track duration per init phase
Correlate logs with health status
❌ ANTI-PATTERNS (3)
All boot logs in one big blob
No timing data on boot
No clear transition to ready state
πŸ’» CODE HINTS (1)
log.stage('init.db', { ms: 142 })
πŸ§ͺ VALIDATION
Simulate slow or failing dependencies. Confirm correct blocking, logging, health signaling, and warmup behavior.
#280Shutdown Sequence Matrix6 cells18 rules18 anti6 hints
Define reliable teardown patterns for services to release resources, flush buffers, and exit predictably during shutdown.
shutdown_triggergraceful_teardown_logicsignal_handlingresource_cleanup_ordererror_reportingobservability_hooks
SIGTERM_CATCH_AND_GRACE_PERIOD
When a container or process receives a termination signal
βœ… RULES (3)
Trap SIGTERM and begin timer
Log shutdown intent and deadline
Initiate async teardown without blocking signal thread
❌ ANTI-PATTERNS (3)
No signal handler present
Immediate exit on signal
Cleanup logic in global finally block only
πŸ’» CODE HINTS (1)
process.on('SIGTERM', shutdownHandler)
ORDERED_RESOURCE_DISPOSAL
When a service uses multiple connected resources (db, cache, workers)
βœ… RULES (3)
Disconnect outward-facing interfaces first
Flush in-flight buffers (logs, metrics)
Close DB/connections last
❌ ANTI-PATTERNS (3)
Close DB before draining workers
Leaving open connections on exit
Killing worker pool without coordination
πŸ’» CODE HINTS (1)
await server.close(); await flushMetrics(); await db.disconnect()
INFLIGHT_REQUEST_TIMEOUT_AND_DRAIN
When handling incoming HTTP/gRPC requests
βœ… RULES (3)
Stop accepting new requests
Drain keep-alive connections
Set shutdown deadline for slow handlers
❌ ANTI-PATTERNS (3)
Force-closing sockets immediately
No deadline awareness in handlers
Restarting service mid-request
πŸ’» CODE HINTS (1)
server.stopAccepting(); await activeRequests.drain()
METRICS_AND_LOG_FLUSH_ON_EXIT
When observability pipelines are async
βœ… RULES (3)
Flush structured logs before exit
Wait for metrics exporter to send final payload
Use bounded timeout to avoid stall
❌ ANTI-PATTERNS (3)
exit() before flushing
Ignoring export promises
No final health status written
πŸ’» CODE HINTS (1)
await logger.flush(); await metricsExporter.flush()
TIMEOUT_AND_FORCEFUL_EXIT_POLICY
When shutdown exceeds max grace duration
βœ… RULES (3)
Set max shutdown duration (e.g. 30s)
Track elapsed teardown time
Force exit with error code after timeout
❌ ANTI-PATTERNS (3)
Waiting forever for exit
Partial shutdown with no fail signal
Zombie pods post-preStop hook timeout
πŸ’» CODE HINTS (1)
setTimeout(() => process.exit(1), 30000)
SHUTDOWN_TELEMETRY_AND_AUDIT_LOGGING
When analyzing shutdown causes and success
βœ… RULES (3)
Log shutdown initiator (signal, admin, error)
Write structured event to audit log
Capture uptime and failure classification
❌ ANTI-PATTERNS (3)
exit() with no logging
Overwriting last error trace
No telemetry on shutdown reason
πŸ’» CODE HINTS (1)
log.shutdown({ signal: 'SIGTERM', uptime })
πŸ§ͺ VALIDATION
Trigger shutdown in test environment. Confirm resource disposal order, deadline handling, log flush, telemetry, and non-zero exit codes on error.
#281Resource Monitoring Matrix6 cells12 rules6 anti6 hints
Determines how system resources are monitored β€” CPU, memory, network, main thread blocking, and performance budgets.
resource_typemonitoring_methodalert_thresholdreporting
resmon_001
When detecting UI jank due to main thread blocking, use Long Tasks API to log and surface long tasks exceeding 50ms.
βœ… RULES (2)
Use PerformanceObserver on 'longtask' entryType
Record tasks > 50ms and include source attribution if available
❌ ANTI-PATTERNS (1)
Ignoring long tasks below 100ms and causing UX stutter
πŸ’» CODE HINTS (1)
new PerformanceObserver(list => list.getEntries().forEach(entry => log(entry.duration))).observe({ entryTypes: ['longtask'] })
resmon_002
When tracking browser memory usage, use performance.measureUserAgentSpecificMemory (when supported) to monitor heap growth.
βœ… RULES (2)
Poll memory snapshot periodically
Use baseline + delta tracking to catch leaks
❌ ANTI-PATTERNS (1)
Polling memory randomly or ignoring platform-specific availability
πŸ’» CODE HINTS (1)
const snapshot = await performance.measureUserAgentSpecificMemory();
resmon_003
When analyzing slow network requests, build a waterfall view using Navigation Timing and Resource Timing APIs.
βœ… RULES (2)
Capture DNS, TCP, request, response durations
Visualize per-resource timeline
❌ ANTI-PATTERNS (1)
Only measuring total load time without component breakdown
πŸ’» CODE HINTS (1)
performance.getEntriesByType('resource')
resmon_004
When ensuring performance budgets, monitor LCP, FID, and bundle size during build or runtime and block on threshold exceed.
βœ… RULES (2)
Track bundle size < 250KB
LCP < 2.5s, FID < 100ms
❌ ANTI-PATTERNS (1)
Letting regressions through without budget enforcement
πŸ’» CODE HINTS (1)
if (bundleSize > MAX_SIZE) failBuild()
resmon_005
When needing live observability, stream resource metrics (CPU, memory, latency) to real-time dashboards for ops visibility.
βœ… RULES (2)
Use WebSocket or push-based metrics exporter
Visualize time-series in Grafana or similar
❌ ANTI-PATTERNS (1)
Batching all logs to backend with delay
πŸ’» CODE HINTS (1)
sendMetric({ type: 'cpu', value })
resmon_006
When a monitored resource crosses threshold (e.g. 90% CPU), trigger automated alert via webhook, SMS, or incident system.
βœ… RULES (2)
Define upper/lower bounds per resource type
Connect alert policy to Opsgenie, PagerDuty, or custom webhook
❌ ANTI-PATTERNS (1)
Only logging issues without alert mechanism
πŸ’» CODE HINTS (1)
if (cpu > 0.9) sendAlert('High CPU')
πŸ§ͺ VALIDATION
Verify: Long Tasks > 50ms are logged, memory usage tracked per snapshot, network timing includes full waterfall, budgets enforce fail conditions, live metrics reach dashboard, and alerts fire on breach.
#282Logging Levels Matrix6 cells12 rules6 anti6 hints
Determines appropriate logging levels per context β€” debug in dev, info in prod, error for failures, and dynamic level switching.
log_levelenvironmentdynamic_controlperformance_impact
loglevel_001
When running in a development environment, enable verbose DEBUG logging to trace internal state and help with debugging.
βœ… RULES (2)
Log variable values, API payloads, and control flow paths
Keep DEBUG logs disabled in production by default
❌ ANTI-PATTERNS (1)
Leaving DEBUG logging enabled in production environments
πŸ’» CODE HINTS (1)
logger.debug('input payload', payload)
loglevel_002
When tracking business operations in production (e.g. user signup, checkout), use INFO logs to capture significant events.
βœ… RULES (2)
Use INFO to describe expected flows
Include contextual metadata for analytics
❌ ANTI-PATTERNS (1)
Logging technical internals (e.g. retries, cache hits) as INFO
πŸ’» CODE HINTS (1)
logger.info('user_registered', { userId })
loglevel_003
When an issue occurs that doesn’t block execution but could indicate deeper problems (e.g. degraded service), log it as WARN.
βœ… RULES (2)
Include fallback path taken or retry count
Monitor WARN logs for patterns over time
❌ ANTI-PATTERNS (1)
Logging WARN on successful fallback or noise scenarios
πŸ’» CODE HINTS (1)
logger.warn('cache_miss_fallback', { key })
loglevel_004
When a runtime exception or unrecoverable failure occurs (e.g. failed DB write), log it as ERROR to ensure visibility and alerting.
βœ… RULES (2)
Include stack trace and user impact details
Route ERROR logs to alerting systems
❌ ANTI-PATTERNS (1)
Logging handled edge cases as ERROR
πŸ’» CODE HINTS (1)
logger.error('db_write_failed', { orderId, error })
loglevel_005
When investigating live systems, enable dynamic logging level switches via environment variable or remote config.
βœ… RULES (2)
Expose log level config endpoint or env var
Revert to default level after investigation
❌ ANTI-PATTERNS (1)
Leaving DEBUG level enabled permanently via dynamic toggle
πŸ’» CODE HINTS (1)
process.env.LOG_LEVEL = 'DEBUG'
loglevel_006
When optimizing production performance, strip or disable verbose logs (DEBUG/TRACE) to reduce overhead.
βœ… RULES (2)
Use log-level filters in logger config
Avoid formatting expensive log strings unless level is active
❌ ANTI-PATTERNS (1)
Logging large payloads or heavy computations in production paths
πŸ’» CODE HINTS (1)
if (logger.isLevelEnabled('debug')) { logger.debug(expensiveFn()) }
πŸ§ͺ VALIDATION
Verify: log levels match context, DEBUG restricted to dev, INFO used for biz events, WARN/ERROR distinguish recoverable vs critical, dynamic toggles are temporary, and prod logs avoid performance hits.
#283Structured Logging Matrix6 cells13 rules6 anti6 hints
Determines how application events are logged in structured format β€” JSON logs with correlation IDs, severity levels, and searchable fields for debugging and audit trails.
log_formatseverity_levelcorrelationretention
log_001
When logging application events, emit logs in structured JSON format with timestamp, level, message, and context fields.
βœ… RULES (2)
Include fields: timestamp, level, message, context
Ensure logs are machine-parseable and consistent across services
❌ ANTI-PATTERNS (1)
Using plain string logs without structured fields
πŸ’» CODE HINTS (1)
{ "timestamp": "2026-02-08T12:00:00Z", "level": "INFO", "message": "User login", "context": { "userId": 123 } }
log_002
When emitting logs, use standardized severity levels (DEBUG, INFO, WARN, ERROR, FATAL) to categorize event criticality.
βœ… RULES (3)
DEBUG for development-only details
INFO for business events
ERROR/FATAL for exceptions or service failures
❌ ANTI-PATTERNS (1)
Logging all events as INFO regardless of impact
πŸ’» CODE HINTS (1)
logger.error('Failed to process payment', { orderId })
log_003
When handling requests across services, propagate a correlation ID to trace full request chain across logs.
βœ… RULES (2)
Generate or extract correlation ID at request entry point
Inject into all outbound requests and log context
❌ ANTI-PATTERNS (1)
Omitting correlation ID on downstream service logs
πŸ’» CODE HINTS (1)
logger.info('Handling checkout', { correlationId })
log_004
When logging sensitive or business-critical actions, include structured fields like userId, action, duration, and result for auditability.
βœ… RULES (2)
Log userId, action, and outcome for every sensitive operation
Emit logs in searchable key:value format
❌ ANTI-PATTERNS (1)
Logging freeform messages without structured fields
πŸ’» CODE HINTS (1)
{ action: 'transfer', userId: 42, result: 'success', durationMs: 134 }
log_005
When centralizing logs, forward structured logs from stdout to a collector (e.g. Fluentd), then index in a search platform (e.g. ELK).
βœ… RULES (2)
Configure apps to write logs to stdout in JSON format
Forward logs to collector with retry/backoff
❌ ANTI-PATTERNS (1)
Writing logs directly to file without aggregation
πŸ’» CODE HINTS (1)
stdout β†’ FluentBit β†’ Elasticsearch
log_006
When managing log retention, keep recent logs in hot storage (e.g. 30d), and archive older logs in cold storage (e.g. 1y) for compliance.
βœ… RULES (2)
Use lifecycle policies to move logs from hot to cold tier
Hot storage for search, cold for compliance/legal access
❌ ANTI-PATTERNS (1)
Retaining all logs in primary index indefinitely
πŸ’» CODE HINTS (1)
hot: 30d, cold: 1y via index lifecycle policy
πŸ§ͺ VALIDATION
Verify: logs are JSON structured, severity levels used correctly, correlation IDs propagated, audit fields included, aggregation pipeline configured, retention policy enforced.
#284Metrics Collection Matrix6 cells12 rules6 anti9 hints
Determines what metrics are collected and how β€” counters, histograms, gauges, and export to monitoring systems.
metric_typecollection_methodexport_targetalerting_integration
metrics_001
When tracking number of total requests and failures, use counter metrics that increment on each occurrence.
βœ… RULES (2)
Use one counter for requests, another for errors
Reset only on process restart
❌ ANTI-PATTERNS (1)
Using gauges to track cumulative counts
πŸ’» CODE HINTS (2)
http_requests_total{method='GET'}++
http_errors_total{status='500'}++
metrics_002
When measuring response latency, use histograms to bucket request durations and export percentiles.
βœ… RULES (2)
Configure buckets appropriate to SLA (e.g. 0.1s, 0.5s, 1s, 5s)
Use histogram_quantile for p95, p99
❌ ANTI-PATTERNS (1)
Logging average response time only
πŸ’» CODE HINTS (1)
http_request_duration_seconds_bucket{le='1.0'}
metrics_003
When tracking current values like active sessions or queue depth, use gauge metrics that can go up/down.
βœ… RULES (2)
Set gauge on each event, do not increment/decrement blindly
Track max queue size separately
❌ ANTI-PATTERNS (1)
Using counters for values that fluctuate over time
πŸ’» CODE HINTS (1)
connections_active.set(count)
metrics_004
When integrating with Prometheus, expose metrics in text exposition format via /metrics endpoint.
βœ… RULES (2)
Follow Prometheus exposition format strictly
Expose metrics at consistent /metrics path
❌ ANTI-PATTERNS (1)
Serving metrics in custom JSON format for Prometheus
πŸ’» CODE HINTS (1)
GET /metrics β†’ text/plain; version=0.0.4
metrics_005
When tracking business-specific KPIs (e.g. orders/min, conversions), define custom metrics with stable cardinality.
βœ… RULES (2)
Prefix custom metrics with app/business domain
Avoid high-cardinality labels (e.g. userId)
❌ ANTI-PATTERNS (1)
Defining metrics per-user or per-session
πŸ’» CODE HINTS (2)
app_orders_total
app_conversion_rate
metrics_006
When using labels on metrics, constrain cardinality to avoid resource exhaustion or degraded query performance.
βœ… RULES (2)
Limit number of unique label values per metric
Use static enums for labels when possible
❌ ANTI-PATTERNS (1)
Labels with dynamic UUIDs, timestamps, or paths
πŸ’» CODE HINTS (2)
job="api", status="200" β€” OK
user_id="..." β€” BAD
πŸ§ͺ VALIDATION
Verify: counters accumulate, histograms bucket correctly, gauges reflect current state, /metrics exposes text format, business metrics avoid high-cardinality, and label usage is controlled.
#285Matrix 285 β€” Tracing Matrix6 cells18 rules18 anti6 hints
Define distributed tracing patterns across services, including context propagation, span design, sampling, and trace analysis.
trace_initiationcontext_propagationspan_designsampling_policyerror_annotationtrace_visualization
TRACE_ID_AND_ROOT_SPAN_ON_ENTRY
When request enters edge or gateway service
βœ… RULES (3)
Generate trace ID at ingress if missing
Create root span with request metadata
Propagate to downstream services
❌ ANTI-PATTERNS (3)
Missing root span in traces
Multiple traces for single request
No correlation ID in logs
πŸ’» CODE HINTS (1)
trace.start('GET /api/init')
CONTEXT_PROPAGATION_VIA_HEADERS
When passing request between services
βœ… RULES (3)
Use W3C TraceContext headers (traceparent, tracestate)
Preserve parent span ID
Support both HTTP and messaging protocols
❌ ANTI-PATTERNS (3)
No propagation in async jobs
Custom header names without standard
Rewriting trace IDs in mid-chain
πŸ’» CODE HINTS (1)
injectTraceHeaders(req.headers)
SPAN_NAMING_AND_EVENT_TAGGING
When breaking logic into traceable operations
βœ… RULES (3)
Name spans with operation and object (e.g. SQL SELECT user)
Tag errors, retries, cache hits
Use duration, size, and status codes as attributes
❌ ANTI-PATTERNS (3)
Generic span names (start/end)
No tags for error/debug events
Mixing unrelated logic into one span
πŸ’» CODE HINTS (1)
span.setAttribute('db.statement', query)
SAMPLING_AND_TRACE_VOLUME_CONTROL
When managing observability at scale
βœ… RULES (3)
Sample at head (ingress) or dynamically
Use priority sampling for errors, slow traces
Tag dropped traces at span root
❌ ANTI-PATTERNS (3)
Trace every request in prod
Sampling based only on user ID
Silent drop of traces without signal
πŸ’» CODE HINTS (1)
tracer.sampleIfSlow(thresholdMs=250)
ERROR_AND_EXCEPTION_TRACING
When errors occur during a traced request
βœ… RULES (3)
Capture stack trace or exception message
Set span.status = ERROR
Log error event in structured form
❌ ANTI-PATTERNS (3)
Silent errors with no trace
Status=OK on failing span
Errors outside tracing boundary
πŸ’» CODE HINTS (1)
span.recordException(e); span.setStatus(ERROR)
TRACE_VISUALIZATION_AND_CORRELATION
When reviewing traces in observability dashboard
βœ… RULES (3)
Display spans hierarchically with timing
Link logs and metrics to trace ID
Support trace search by status, service, latency
❌ ANTI-PATTERNS (3)
Flat span views without hierarchy
No links to related logs
No filters for trace search
πŸ’» CODE HINTS (1)
ui.traceView(traceId).withLogs().withMetrics()
πŸ§ͺ VALIDATION
Trace request through multi-service flow. Verify context is passed, spans are structured, errors are tagged, and visualization links traces to logs and metrics.
#286Health Checks Matrix6 cells12 rules6 anti6 hints
Determines how system health is monitored via health check endpoints β€” liveness, readiness, dependency checks, and automated recovery triggers.
check_typefrequencydependency_scopefailure_action
health_001
When determining if a process is alive, run a liveness probe every minute to detect crash or freeze.
βœ… RULES (2)
Use a lightweight endpoint (e.g. /live)
Probe should not include external dependencies
❌ ANTI-PATTERNS (1)
Including DB calls in liveness check β€” slows detection
πŸ’» CODE HINTS (1)
GET /live β†’ 200 OK
health_002
When checking if an app can receive traffic, run readiness probes every 15s and wait for successful signal before routing.
βœ… RULES (2)
Include dependency checks (DB, cache) in readiness
Use /ready endpoint that reflects full availability
❌ ANTI-PATTERNS (1)
Assuming process boot implies readiness
πŸ’» CODE HINTS (1)
GET /ready β†’ 200 OK
health_003
When validating system dependencies, run internal health checks every 30s on DB, Redis, external APIs.
βœ… RULES (2)
Check connectivity and latency for each service
Expose result in aggregated /health JSON
❌ ANTI-PATTERNS (1)
Ignoring transient errors or caching old statuses
πŸ’» CODE HINTS (1)
{ db: 'ok', redis: 'fail', api: 'ok' }
health_004
When validating full app functionality, run deep health check on-demand (via CLI or admin UI) to simulate full request-response path.
βœ… RULES (2)
Include DB read/write + downstream API call
Simulate real user transaction
❌ ANTI-PATTERNS (1)
Running deep check on every probe β€” too heavy
πŸ’» CODE HINTS (1)
POST /admin/check/deep
health_005
When exposing health checks externally, use unified /health endpoint with structured JSON output.
βœ… RULES (2)
Include status per component
Respond with overall status + timestamp
❌ ANTI-PATTERNS (1)
Plaintext responses without structure or detail
πŸ’» CODE HINTS (1)
{ status: 'ok', components: { db: 'ok', cache: 'ok' }, timestamp: 1707421500 }
health_006
When liveness check fails repeatedly, trigger automated restart via orchestrator (e.g. Kubernetes).
βœ… RULES (2)
Set failureThreshold and restartPolicy in probe config
Use restart: always in Docker or Kubernetes
❌ ANTI-PATTERNS (1)
Letting crashed process hang without recovery action
πŸ’» CODE HINTS (1)
livenessProbe: { httpGet: /live, failureThreshold: 3, periodSeconds: 60 }
πŸ§ͺ VALIDATION
Verify: liveness probes detect failure fast, readiness blocks routing until ready, dependencies exposed in /health, deep check simulates transaction, JSON format standard across services, and orchestrator restarts on repeated failure.
#287Matrix 287 β€” Readiness Checks Matrix6 cells18 rules18 anti6 hints
Define runtime health, readiness, and dependency checks to control service traffic routing and lifecycle.
check_typeevaluation_timingdependency_scopesignal_formatorchestration_hookfallback_and_bypass
HTTP_READINESS_ENDPOINT
When service is being deployed or restarted
βœ… RULES (3)
Expose /readyz or /health/ready endpoint
Return 200 only after full init
Fail fast with 503 on issues
❌ ANTI-PATTERNS (3)
Always returning 200
Missing endpoint altogether
No readiness state management
πŸ’» CODE HINTS (1)
app.get('/readyz', readinessHandler)
DEPENDENCY_PROBE_AND TIMEOUT
When startup depends on external systems (db, queue)
βœ… RULES (3)
Ping critical services with timeout
Fail readiness if probe fails
Retry with exponential backoff
❌ ANTI-PATTERNS (3)
Assuming all deps are healthy
Blocking indefinitely
Not differentiating optional vs required
πŸ’» CODE HINTS (1)
await db.ping(); await redis.ping()
READINESS_GATE_IN_ORCHESTRATOR
When integrated into container or service mesh
βœ… RULES (3)
Use readinessProbe in K8s
Remove pod from LB if not ready
Restart pod if probe fails repeatedly
❌ ANTI-PATTERNS (3)
Using livenessProbe instead
No probe in config
Forcing ready without validation
πŸ’» CODE HINTS (1)
readinessProbe: httpGet: path: /readyz
DYNAMIC_FLAG_BASED_GATING
When readiness depends on config, migration, or batch job
βœ… RULES (3)
Check feature flags or migration state
Allow signal once init condition met
Expose state via /status or trace
❌ ANTI-PATTERNS (3)
Static readiness only
Manual toggling in prod
No visibility into gating reason
πŸ’» CODE HINTS (1)
if (flags.get('init_ready')) β†’ return 200
GRACEFUL_EXIT_ON_READINESS_FAILURE
When service loses ability to serve
βœ… RULES (3)
Fail /readyz on core health drop
Trigger deregistration from routing
Log and alert on readiness loss
❌ ANTI-PATTERNS (3)
Always returning ready
Traffic routed despite internal failures
Missing alerts on drop
πŸ’» CODE HINTS (1)
if (!canServe()) return 503
READINESS_METRICS_AND_BURN_IN_PERIOD
When measuring readiness across multiple deploys
βœ… RULES (3)
Emit readiness state as metric
Delay ready for burn-in or warmup
Correlate readiness with success rate
❌ ANTI-PATTERNS (3)
No metrics on readiness gate
Immediate ready after pod start
Readiness vs health metrics mismatch
πŸ’» CODE HINTS (1)
metrics.emit('ready', 1)
πŸ§ͺ VALIDATION
Force dependency failure, config gate, or health drop. Confirm readiness blocks traffic, removes from mesh, emits metrics, and alerts.
#288Health Checks Matrix6 cells18 rules18 anti6 hints
Define structured approaches to expose, validate, and act upon service health β€” covering readiness, liveness, startup, and dependency indicators.
check_typeexposure_methodevaluation_logicfailure_responsevisibility_and_alertingtesting_and_validation
LIVENESS_PROBE_KILL_ON_HANG
When process becomes unresponsive
βœ… RULES (3)
Use /live or /healthz endpoint
Fail on timeout or blocked thread
Let orchestrator restart the pod
❌ ANTI-PATTERNS (3)
Liveness never fails
Restart only on manual signal
Same logic as readiness
πŸ’» CODE HINTS (1)
livenessProbe.httpGet('/live').timeout(3s)
READINESS_PROBE_AND_TRAFFIC_GATE
When service isn't ready to accept traffic
βœ… RULES (3)
Use /ready endpoint
Fail probe if DB or deps not connected
Deregister from mesh or LB on failure
❌ ANTI-PATTERNS (3)
Always returning 200
LB routes traffic despite failures
No distinction from liveness
πŸ’» CODE HINTS (1)
readinessProbe.httpGet('/ready')
STARTUP_PROBE_FOR_COLD_BOOT
When service takes long to start
βœ… RULES (3)
Use separate startup probe
Allow longer timeout
Transition to liveness after success
❌ ANTI-PATTERNS (3)
Killed during cold init
Startup logic in liveness
No differentiation in probes
πŸ’» CODE HINTS (1)
startupProbe.httpGet('/boot').timeout(30s)
DEPENDENCY_HEALTH_CHAIN
When service depends on DBs, APIs, cache
βœ… RULES (3)
Ping critical dependencies
Report degraded state if any fail
Expose summary tree for ops view
❌ ANTI-PATTERNS (3)
Only app logic monitored
No visibility into DB/API/cache
Health returns OK if deps fail
πŸ’» CODE HINTS (1)
healthCheck.chain(['db', 'redis', 'auth'])
HEALTH_CHECK_ALERTS_AND_DASHBOARDS
When surfacing health status to operators
βœ… RULES (3)
Emit metrics for probe pass/fail
Alert on sustained failure
Visualize per instance and region
❌ ANTI-PATTERNS (3)
No metrics tied to health
Silent failure without alert
Global OK despite local failures
πŸ’» CODE HINTS (1)
metrics.emit('ready_fail', 1)
PROBE_TESTING_AND_FAULT_INJECTION
When validating correctness of probe logic
βœ… RULES (3)
Inject failures into startup/deps
Test probe behavior in CI
Document probe logic and thresholds
❌ ANTI-PATTERNS (3)
Probes always return healthy
CI skips probe validation
Unclear thresholds for failure
πŸ’» CODE HINTS (1)
simulate.dbDown().expectReadiness(503)
πŸ§ͺ VALIDATION
Inject faults, observe probe results, confirm alerting, and dashboard sync. Compare behavior across liveness, readiness, and startup.
#289Alerting Matrix6 cells12 rules6 anti6 hints
Determines when and how alerts are triggered β€” thresholds, severity routing, escalation, and alert fatigue prevention.
alert_triggerseverity_routingescalationfatigue_prevention
alert_001
When CPU exceeds 90% or error rate exceeds 5%, trigger severity-based alerts mapped directly to alerting channels.
βœ… RULES (2)
Set static thresholds for CPU, memory, error %
Map CRITICAL alerts to PagerDuty, WARN to Slack
❌ ANTI-PATTERNS (1)
Using same route/channel for all severities
πŸ’» CODE HINTS (1)
alert: if cpu > 90% β†’ send('PagerDuty')
alert_002
When metric deviates from normal baseline (e.g. anomaly detection), route alert based on confidence level.
βœ… RULES (2)
Train baseline using past 7d data
Trigger alert if 3Οƒ deviation persists >5min
❌ ANTI-PATTERNS (1)
Alerting on single-point spikes without baseline context
πŸ’» CODE HINTS (1)
if (zscore > 3 for 5min) route(confidence > 0.9 ? 'PagerDuty' : 'Slack')
alert_003
When alert is unacknowledged for 15 minutes, auto-escalate to higher severity channel or tier.
βœ… RULES (2)
Start with tier-1 oncall
Escalate to tier-2 or manager if no ack in SLA
❌ ANTI-PATTERNS (1)
Alert stays stuck on primary with no response
πŸ’» CODE HINTS (1)
if (!ack && age > 15min) escalate('Manager')
alert_004
When multiple alerts fire from same system/component, group them and deduplicate to reduce noise.
βœ… RULES (2)
Correlate alerts with same root cause
Suppress duplicates within 10min window
❌ ANTI-PATTERNS (1)
Sending 10+ identical alerts for same issue
πŸ’» CODE HINTS (1)
groupBy(service + alert_type) window=10m
alert_005
When in maintenance mode, suppress alerts from non-critical systems to avoid alert fatigue.
βœ… RULES (2)
Define maintenance schedules in alert manager
Allow critical infra alerts only
❌ ANTI-PATTERNS (1)
Disabling all alerts including critical ones during maintenance
πŸ’» CODE HINTS (1)
if (in_maintenance && severity != 'CRITICAL') suppress()
alert_006
When a system generates repeated alerts, apply rate-limiting or backoff to avoid fatigue and reduce noise.
βœ… RULES (2)
Track alert frequency per service/component
Suppress or silence source if threshold exceeded
❌ ANTI-PATTERNS (1)
Letting noisy systems spam alert channels indefinitely
πŸ’» CODE HINTS (1)
if (alertCount > 5/hour) rateLimit(alert_source)
πŸ§ͺ VALIDATION
Verify: alerts fire correctly on threshold or anomaly, severity routed properly, unacked alerts escalate, grouping reduces duplicates, maintenance suppression works, and volume limits avoid fatigue.
#290SLO / SLA Matrix6 cells18 rules18 anti6 hints
Define how to specify, enforce, and track service-level objectives and agreements across internal and external consumers.
metric_typeconsumer_visibilityenforcement_scopebreach_handlingmeasurement_intervalremediation_path
INTERNAL_ERROR_RATE_SLO
When defining internal quality targets for services
βœ… RULES (3)
Set error rate SLO (e.g. <0.1%)
Track over rolling 30d window
Trigger internal alert on breach
❌ ANTI-PATTERNS (3)
Only uptime SLOs
SLO defined but not measured
No alert on violation
πŸ’» CODE HINTS (1)
slo.define('error_rate', threshold=0.001)
EXTERNAL_UPTIME_SLA
When providing uptime guarantees to clients
βœ… RULES (3)
Define 99.9%+ uptime in terms of 5xx and unavailability
Disclose window and measurement agent
Include compensation clause on breach
❌ ANTI-PATTERNS (3)
No SLA enforcement mechanism
Ambiguous definition of downtime
No data source declared
πŸ’» CODE HINTS (1)
sla.publish('uptime', threshold=0.999)
LATENCY_OBJECTIVE_BY_ENDPOINT
When managing multiple APIs with different SLIs
βœ… RULES (3)
Define 95th percentile latency target
Customize per endpoint class (e.g. read vs write)
Visualize trends per API
❌ ANTI-PATTERNS (3)
Global latency SLO only
No segmentation per call type
Using average instead of percentile
πŸ’» CODE HINTS (1)
latency.p95('/search') < 350ms
CONSUMER_VISIBLE_SLO_DASHBOARDS
When publishing status to external consumers
βœ… RULES (3)
Publish SLO status on dashboard
Update weekly or on incident
Include breakdown and annotation
❌ ANTI-PATTERNS (3)
No external view of SLOs
Static page without trend
Manual data entry
πŸ’» CODE HINTS (1)
statusPage.show('slo_uptime', value)
ALERTING_AND_PAGING_ON_SLO_BREACH
When SLOs fall below threshold
βœ… RULES (3)
Integrate SLO into alerting system
Set multi-window, multi-burn-rate alerts
Escalate on sustained breach
❌ ANTI-PATTERNS (3)
One-shot alert on threshold
No severity tiering
Paging only on infra metrics
πŸ’» CODE HINTS (1)
burnRate.alert(slo='latency', window=6h)
RETROSPECTIVE_AND_REMEDIATION_PLAN
When an SLO breach has occurred
βœ… RULES (3)
Run blameless postmortem
Document why SLO was missed
Track and publish remediation tasks
❌ ANTI-PATTERNS (3)
No follow-up on breach
No root cause identified
Repeat breach with no adaptation
πŸ’» CODE HINTS (1)
incident.linkTo('slo_violation')
πŸ§ͺ VALIDATION
Track breach, fire alert, trigger postmortem, check consumer dashboard. Compare observed vs defined metrics and contractual terms.
#291Performance Budget Matrix6 cells18 rules18 anti6 hints
Define quantitative boundaries for system latency, resource usage, and throughput to prevent degradation under changing load or code evolution.
budget_typemeasurement_methodenforcement_scopetracking_intervalviolation_responsedegradation_mitigation
FRONTEND_LOAD_TIME_BUDGET
When loading client-side JS/CSS/assets
βœ… RULES (3)
Set max FCP/LCP budget (e.g. <2.5s)
Track with RUM or Lighthouse
Fail build if budget regresses
❌ ANTI-PATTERNS (3)
No budget per route
Only lab tests, no real-world
Budget defined but unenforced
πŸ’» CODE HINTS (1)
lighthouse-ci assert --budgets budgets.json
BACKEND_API_LATENCY_TARGET
When exposing server endpoints to consumers
βœ… RULES (3)
Define latency per endpoint class
Track with APM + metrics
Alert on burn-rate and SLO impact
❌ ANTI-PATTERNS (3)
Using average instead of percentile
Global latency only, no breakdown
Alert only on hard error
πŸ’» CODE HINTS (1)
prometheus.query('latency_p95{endpoint=...}')
RESOURCE_FOOTPRINT_BUDGET
When optimizing memory, CPU, or network
βœ… RULES (3)
Set RAM and CPU budget per service
Benchmark under load
Use alerts and dashboards
❌ ANTI-PATTERNS (3)
No resource limits on containers
Budget defined but not measured
Relying only on cloud billing for signal
πŸ’» CODE HINTS (1)
kubectl set resources deployment/...
THROUGHPUT_EXPECTATION_VS_REALITY
When load varies across time or customers
βœ… RULES (3)
Compare actual TPS/QPS to target
Include seasonal or client segment factors
Track regressions in volume or latency
❌ ANTI-PATTERNS (3)
Fixed assumptions on traffic
No baseline from past months
Ignoring error rate in throughput
πŸ’» CODE HINTS (1)
apm.compare('throughput', period='30d')
PERF_BUDGET_GATING_IN_CI_PIPELINE
When pushing new code or infra
βœ… RULES (3)
Run perf test and compare vs baseline
Block merge if P95 or LCP worsens
Log reason for override when gating bypassed
❌ ANTI-PATTERNS (3)
No perf check in CI
Allowing perf drift silently
Gating only on errors, not perf
πŸ’» CODE HINTS (1)
ci.check('perf-budget')
GRADUAL_DEGRADATION_HANDLING
When degradation accumulates over time
βœ… RULES (3)
Emit warning when budget gets close
Visualize deltas per deploy
Trigger cleanup or rollback plan
❌ ANTI-PATTERNS (3)
Hard fail only at breach
No tracking of delta vs previous
Slowness caught only via user complaint
πŸ’» CODE HINTS (1)
dashboard.show('perf-trend', delta=true)
πŸ§ͺ VALIDATION
Push code with perf delta, observe block/alert. Compare perf budget across deploys. Confirm rollback path on regression.
#292Capacity Planning Matrix6 cells18 rules18 anti6 hints
Define methods for projecting, testing, and reviewing system capacity across compute, storage, and throughput dimensions.
capacity_typeforecast_horizonmeasurement_toolrisk_thresholdscale_triggerreview_interval
STORAGE_UTILIZATION_FORECAST
When monitoring growing data storage use
βœ… RULES (3)
Track usage with daily granularity
Forecast 90d+ horizon
Alert at 75/85/95% checkpoints
❌ ANTI-PATTERNS (3)
Alerts only at 100%
No projection model
No SLA on scale-up time
πŸ’» CODE HINTS (1)
forecast.disk('s3').horizon(120d)
CPU_AND_MEMORY_HEADROOM
When running compute-intensive workloads
βœ… RULES (3)
Reserve buffer above max observed usage
Track headroom over time
Alert when trending downward
❌ ANTI-PATTERNS (3)
No capacity margin configured
Static CPU requests
Ignoring vertical scaling trends
πŸ’» CODE HINTS (1)
monitor.cpu().reserve(25%)
QPS_LOADTEST_AND_THRESHOLDS
When validating throughput under simulated load
βœ… RULES (3)
Run synthetic load tests monthly
Plot error vs QPS curve
Track peak capacity by region
❌ ANTI-PATTERNS (3)
Loadtest only before launch
No failover test
No circuit breaker test at limits
πŸ’» CODE HINTS (1)
k6 run test-load-qps.js
CAPACITY_SAFETY_MARGIN_TAGGING
When labeling workloads and tiers
βœ… RULES (3)
Tag critical workloads with extra reserve
Deprioritize low-importance background jobs
Separate burst and batch budgets
❌ ANTI-PATTERNS (3)
Same budget for all jobs
No distinction between prod/dev
Critical jobs squeezed by noisy neighbors
πŸ’» CODE HINTS (1)
workload.tag('tier1').reserve(40%)
HISTORICAL_CAPACITY_TRENDS
When reviewing past data to inform future scale
βœ… RULES (3)
Visualize weekly/monthly trends
Correlate with code deploys
Identify patterns across clusters
❌ ANTI-PATTERNS (3)
Short term view only
No correlation with releases
Blind scaling without insight
πŸ’» CODE HINTS (1)
grafana.panel('capacity-trend')
CAPACITY_PLAN_REVIEW_CYCLE
When planning infra and spend
βœ… RULES (3)
Review plan quarterly
Include cost/performance tradeoffs
Update based on usage deviations
❌ ANTI-PATTERNS (3)
One-time plan for the year
No cross-team input
No rollback if overprovisioned
πŸ’» CODE HINTS (1)
plan.review('infra_q2')
πŸ§ͺ VALIDATION
Review forecast, alerts, and recent usage. Simulate high load. Validate scale-up behavior, reserve capacity, and team review trail.
#293Auto-Scaling Matrix6 cells18 rules18 anti6 hints
Define adaptive policies and safeguards for automatic horizontal/vertical scaling of compute, storage, and other resources.
scaling_trigger_typescaling_policycooldown_and_hysteresisvisibility_and_alertingcost_controlfallback_behavior
CPU_UTILIZATION_SCALE_POLICY
When autoscaling based on CPU load
βœ… RULES (3)
Trigger at 75% avg CPU
Define min/max instance bounds
Throttle scale frequency
❌ ANTI-PATTERNS (3)
Reactive scaling only on error
Too frequent scale in/out
CPU spike triggers premature scale
πŸ’» CODE HINTS (1)
autoscale.cpu(threshold=0.75, min=2, max=20)
QUEUE_LENGTH_OR_BACKLOG_SCALING
When workers process message or job queues
βœ… RULES (3)
Monitor queue length or age
Scale workers to meet SLA
Drain gracefully before scale in
❌ ANTI-PATTERNS (3)
No scale on burst
Blindly adding workers
Killing jobs mid-queue on scale in
πŸ’» CODE HINTS (1)
autoscale.queue(name='jobs', maxLatency=30s)
SCHEDULED_SCALE_WINDOWS
When load varies predictably (e.g. day/night)
βœ… RULES (3)
Define scale-up/down windows
Combine with reactive policy
Override on anomaly detection
❌ ANTI-PATTERNS (3)
Always reactive only
Schedules with no overrides
Scaling ignores cost windows
πŸ’» CODE HINTS (1)
schedule.scale('weekday_peak', start='08:00', end='18:00')
SCALING_METRICS_DASHBOARDS_AND_ALERTS
When tuning or debugging autoscale behavior
βœ… RULES (3)
Log scale events with cause
Expose active instance count and trigger history
Alert on stuck scaling or flapping
❌ ANTI-PATTERNS (3)
No trace of scale decisions
No alerts on maxed-out group
Only billing alert on scale
πŸ’» CODE HINTS (1)
dashboard.show('autoscale_events')
SCALING_COST_GUARDS
When avoiding runaway spend during incident
βœ… RULES (3)
Set per-hour cost caps
Pause scaling after limit
Alert on spend threshold
❌ ANTI-PATTERNS (3)
No budget tie-in to scaling
Unbounded burst during outage
Scaling leads to zero throttling
πŸ’» CODE HINTS (1)
autoscale.guard(costPerHour < $100)
SCALE_FAILURE_FALLBACK
When scaling API or infra fails
βœ… RULES (3)
Use queue or rate-limit fallback
Notify teams with degraded mode
Throttle traffic or offload work
❌ ANTI-PATTERNS (3)
Scaling failure causes outage
No graceful degradation
Untracked fallback activation
πŸ’» CODE HINTS (1)
if (scalingFail) β†’ enterDegradedMode()
πŸ§ͺ VALIDATION
Simulate spike or backlog. Validate trigger, policy enforcement, dashboard events, cost capping, and fallback mode.
#294Deployment Strategy Matrix6 cells18 rules18 anti6 hints
Define structured patterns for rolling out application changes with safety, observability, and rollback paths.
strategy_typetraffic_shift_modelrollback_pathmonitoring_scopeblast_radius_limitautomation_level
ROLLING_UPDATE_WITH_HEALTH_CHECK
When updating stateless services gradually
βœ… RULES (3)
Replace N% of pods at a time
Wait for health check between batches
Abort if errors exceed threshold
❌ ANTI-PATTERNS (3)
All-at-once deploys
No health gate
No rollback marker
πŸ’» CODE HINTS (1)
kubernetes.strategy('rolling', maxUnavailable=1)
BLUE_GREEN_WITH_TRAFFIC_SWITCH
When deploying entirely new version alongside
βœ… RULES (3)
Provision full copy in parallel
Verify health before switch
Enable instant rollback via DNS or LB switch
❌ ANTI-PATTERNS (3)
Blue/Green with shared DB schema
Switch without warm validation
No state migration plan
πŸ’» CODE HINTS (1)
deploy.blueGreen(stagingEnv='v2')
CANARY_BASED_ON_ERROR_BUDGET
When limiting risk via gradual exposure
βœ… RULES (3)
Send X% traffic to new version
Monitor burn rate or error budget
Roll forward or abort based on data
❌ ANTI-PATTERNS (3)
No budget check before rollout
All traffic shifted instantly
Canary expands without metrics
πŸ’» CODE HINTS (1)
canary.deploy(traffic=0.1).watch(slo='p95_latency')
SHADOW_TRAFFIC_VALIDATION
When validating backend behavior pre-launch
βœ… RULES (3)
Mirror real traffic to new version
Capture responses and compare
Block prod deploy on mismatch
❌ ANTI-PATTERNS (3)
Shadow with no diffing
Traffic mirrored but ignored
Mismatch ignored at deploy gate
πŸ’» CODE HINTS (1)
shadow.traffic(mirrorTo='new-backend')
DEPLOYMENT_DASHBOARDS_AND_ALERTS
When running live deployment
βœ… RULES (3)
Show version, region, % traffic
Surface health and latency
Alert on rollout deviation
❌ ANTI-PATTERNS (3)
Deploy with no dashboards
No version visibility
Rollout errors only in logs
πŸ’» CODE HINTS (1)
dashboard.deployments().showActive()
AUTOMATED_ROLLBACK_AND LOCKOUT
When deploy causes instability
βœ… RULES (3)
Monitor SLO and rollback on breach
Disable re-deploy until cause fixed
Alert deployer and team
❌ ANTI-PATTERNS (3)
Manual rollback only
Deploy retried automatically
No link between error and deploy
πŸ’» CODE HINTS (1)
if (burnRate > threshold) rollback(); lockout()
πŸ§ͺ VALIDATION
Trigger rollout, observe traffic flow, validate alerts, simulate error, confirm rollback.
#295Rollback Strategy Matrix6 cells16 rules12 anti12 hints
Determines how deployments are rolled back safely β€” blue-green, canary rollback, database migration reversal, and automated triggers.
rollback_methodtriggerdata_migrationverification
rollback_001
When needing instant rollback, switch traffic from green (new) to blue (previous) version using load balancer or router toggle.
βœ… RULES (3)
Keep both environments live during rollout
Monitor new (green) before DNS/cutover
Switch back to blue instantly if issues detected
❌ ANTI-PATTERNS (2)
Tearing down previous version before validating the new
Not automating switch mechanism
πŸ’» CODE HINTS (2)
kubectl rollout undo deployment/web
nginx.conf: proxy_pass http://blue_backend;
rollback_002
When progressive rollout fails health checks (latency, errors), automatically halt and revert canary deployment.
βœ… RULES (3)
Monitor SLO metrics during canary
Set thresholds to trigger rollback logic
Route traffic back to stable version
❌ ANTI-PATTERNS (2)
No rollback logic on canary failure
Canary traffic percentage too high to begin with
πŸ’» CODE HINTS (2)
if (error_rate > 5%) rollback()
Argo Rollouts with canary analysis + abortOnFailure
rollback_003
When a DB migration breaks functionality, run a reversible down-migration script to restore schema/data state.
βœ… RULES (3)
All migrations must include backward-compatible down script
Capture snapshot or export before applying
Test rollback scripts in staging
❌ ANTI-PATTERNS (2)
Irreversible schema changes (e.g. DROP COLUMN without backup)
Skipping data migration validations
πŸ’» CODE HINTS (2)
sequelize db:migrate:undo
rails db:rollback STEP=1
rollback_004
When a new feature causes UX issues, instantly disable it via feature flag without needing redeployment.
βœ… RULES (2)
Gate risky features with remote-controlled flags
Use default fallback paths when flag is off
❌ ANTI-PATTERNS (2)
Hardcoding feature paths without flag control
Tying rollback to redeploys instead of toggles
πŸ’» CODE HINTS (2)
if (flags.newUI) renderNew(); else renderOld();
LaunchDarkly.toggle('betaEditor', false)
rollback_005
When health probes fail post-deploy, trigger automatic rollback via orchestrator (e.g. Kubernetes, Argo).
βœ… RULES (2)
Use liveness/readiness probes to detect degraded state
Define rollback policies in deployment controller
❌ ANTI-PATTERNS (2)
No probes configured or probes too lax
Manual detection of health issues
πŸ’» CODE HINTS (2)
livenessProbe + failureThreshold
Argo Rollouts: autoAbort: true
rollback_006
After rollback is complete, run smoke tests to confirm core functionality is restored.
βœ… RULES (3)
Run post-rollback validation suite
Monitor errors/logs immediately after switch
Verify rollback didn’t corrupt shared state
❌ ANTI-PATTERNS (2)
No verification after rollback (false sense of success)
Assuming rollback always safe without test
πŸ’» CODE HINTS (2)
npm run test:smoke
smoke.yaml in CI/CD rollback stage
πŸ§ͺ VALIDATION
Verify: rollback mechanism triggers on health failure, migrations reversible, feature flags toggle instantly, post-rollback tests confirm system stability, and orchestration tools enforce policy reliably.
#296Canary Releases Matrix6 cells18 rules18 anti6 hints
Define safe, observable, and incremental release patterns using canary deployments and metrics-based expansion logic.
canary_triggertraffic_allocation_strategymetrics_monitoringrollback_policycontrol_vs_experiment_comparisonexpansion_schedule
PERCENTAGE_BASED_TRAFFIC_SHIFT
When routing small % of users to new version
βœ… RULES (3)
Start with <5% of traffic
Monitor error and latency metrics
Expand only after success window
❌ ANTI-PATTERNS (3)
No gating before expansion
Hard jump from 5% to 100%
Metrics ignored between phases
πŸ’» CODE HINTS (1)
canary.setTraffic(0.05)
BURN_RATE_MONITORED_EXPANSION
When increasing canary exposure over time
βœ… RULES (3)
Calculate burn rate in real time
Pause expansion on spike
Roll forward only within error budget
❌ ANTI-PATTERNS (3)
No rollback logic
Full rollout regardless of error trends
Burn rate computed manually post-factum
πŸ’» CODE HINTS (1)
if (burnRate < threshold) canary.expand()
EXPERIMENT_CONTROL_COMPARISON
When measuring impact of canary vs current
βœ… RULES (3)
Compare same metrics for A/B
Use stat sig or confidence bands
Delay rollout if delta exceeds budget
❌ ANTI-PATTERNS (3)
No control group
Comparing different metrics
No visual diff in dashboard
πŸ’» CODE HINTS (1)
dashboard.compare('canary', 'control')
AUTO_ROLLBACK_ON_DEVIATION
When metrics degrade during canary
βœ… RULES (3)
Trigger rollback on threshold breach
Log reason and metrics that failed
Block redeploy until analysis
❌ ANTI-PATTERNS (3)
Manual rollback only
Ignored rollback signal
No deploy freeze post-failure
πŸ’» CODE HINTS (1)
if (slo.failed) canary.rollback()
TIME_BOUND_AND_SCHEDULED_PHASES
When orchestrating rollout over hours/days
βœ… RULES (3)
Predefine time gates per stage
Evaluate after each phase
Allow pause or hold at checkpoints
❌ ANTI-PATTERNS (3)
Instant jump between stages
No pause possible
Schedule ignored after issue found
πŸ’» CODE HINTS (1)
canary.schedule(['5%', '25%', '100%'])
CANARY_TELEMETRY_AND_AUDIT_LOGS
When ensuring accountability and traceability
βœ… RULES (3)
Log each phase and decision
Annotate metric dashboards
Link rollout to ticket/commit
❌ ANTI-PATTERNS (3)
Deploy with no logs
Rollback reason undocumented
No traceability to code change
πŸ’» CODE HINTS (1)
log.canaryEvent({ phase: 'expand', commit: 'abc123' })
πŸ§ͺ VALIDATION
Run canary with phased rollout, trigger rollback on signal, inspect logs/metrics, confirm gating, and burn-rate control.
#297Blue-Green Deployment Matrix6 cells18 rules18 anti6 hints
Define safe cutover strategies using parallel environments to reduce downtime, ensure validation, and support rapid rollback.
environment_provisioningvalidation_methodcutover_strategyrollback_mechanismstate_sync_approachvisibility_and_auditing
PARALLEL_INFRA_WITH_TRAFFIC_SWITCH
When running blue and green versions simultaneously
βœ… RULES (3)
Provision isolated envs (infra + app)
Validate green before switching
Switch traffic via LB or DNS
❌ ANTI-PATTERNS (3)
Shared infra across envs
Switch without pre-check
No rollback signal path
πŸ’» CODE HINTS (1)
lb.route('green')
USER_TRAFFIC_SPLIT_FOR_VALIDATION
When needing real load validation
βœ… RULES (3)
Route subset of traffic to green
Monitor performance and errors
Abort if delta exceeds budget
❌ ANTI-PATTERNS (3)
No metric diff pre/post cut
All traffic cut at once
No user feedback loop
πŸ’» CODE HINTS (1)
route.percent(green=20%)
AUTOMATED_CUTOVER_AND_MONITORING
When switching between environments
βœ… RULES (3)
Trigger cutover via CI/CD
Track cutover duration
Alert on health regression post-switch
❌ ANTI-PATTERNS (3)
Manual switch with no logs
No post-switch alerting
Cutover during peak hours
πŸ’» CODE HINTS (1)
deploy.cutover('green')
INSTANT_ROLLBACK_TO_BLUE
When green causes user-visible issues
βœ… RULES (3)
Preserve blue until green verified
Switch back instantly if error
Log cause and notify owner
❌ ANTI-PATTERNS (3)
Terminate blue immediately
Rollback requires full deploy
No record of rollback reason
πŸ’» CODE HINTS (1)
if (green.failed) route('blue')
STATE_MIGRATION_AND_DATA_SYNC
When state or schema differs across envs
βœ… RULES (3)
Use schema versioning
Ensure backward compatibility
Delay destructive migration until cutover
❌ ANTI-PATTERNS (3)
Green schema breaks blue
Writes during validation phase
Missing sync during rollback
πŸ’» CODE HINTS (1)
migrate.safe('v2')
DEPLOY_AUDIT_AND_HISTORY_TRACKING
When managing complex deploy pipelines
βœ… RULES (3)
Log each environment’s version and status
Link cutover to commit or ticket
Expose audit in dashboard
❌ ANTI-PATTERNS (3)
Manual deploys with no log
No visibility into blue/green status
No version pinning in env
πŸ’» CODE HINTS (1)
audit.log('green deployed', commit='abc123')
πŸ§ͺ VALIDATION
Provision both environments, cutover, monitor metrics, trigger rollback, validate schema compatibility and audit log completeness.
#298Runtime Debugging Matrix6 cells18 rules18 anti6 hints
Define safe and observable methods for investigating live issues in production systems without full redeploys or downtime.
debug_triggeraccess_methoddata_capture_scopesafety_and_isolationaudit_and_expiryoperator_tooling
FEATURE_FLAGGED_DEBUG_PATHS
When exposing internal state for diagnosis
βœ… RULES (3)
Guard paths with admin flag
Disable in standard runtime
Log usage and accessors
❌ ANTI-PATTERNS (3)
Always-on debug routes
No access log
Exposing sensitive data
πŸ’» CODE HINTS (1)
if (flags.debug) return debugInfo()
ON_DEMAND_LOG_LEVEL_ELEVATION
When a service issue needs deeper logs
βœ… RULES (3)
Toggle level via API or control plane
Expire after fixed duration
Log elevation and scope
❌ ANTI-PATTERNS (3)
Permanent log level change
No boundary on elevation
No audit trail for change
πŸ’» CODE HINTS (1)
log.setLevel('DEBUG', ttl=5m)
LIVE_TRACE_INJECTION
When code path is misbehaving intermittently
βœ… RULES (3)
Inject span hooks dynamically
Sample requests with trace ID
Remove instrumentation after N calls
❌ ANTI-PATTERNS (3)
Tracing all traffic blindly
Permanent code modification
No sampling or bounding
πŸ’» CODE HINTS (1)
trace.inject('flowA', limit=100)
SAFE_REMOTE_DEBUG_SESSION
When direct process inspection is required
βœ… RULES (3)
Require MFA and token gating
Set session timeout and audit log
Isolate memory from other tenants
❌ ANTI-PATTERNS (3)
SSH into prod with root
Persistent open ports
No expiration on debug socket
πŸ’» CODE HINTS (1)
remoteDebug.attach(pid, ttl=10m)
RED_TEAM_PROBE_AND_TRACE_MODE
When security or compliance test is underway
βœ… RULES (3)
Tag probe events in telemetry
Trace from ingress to storage
Isolate impact in shadow tenant
❌ ANTI-PATTERNS (3)
Red team events mixed with user logs
No trace ID for test
Permanent probe mode enabled
πŸ’» CODE HINTS (1)
probe.start('exfil_attempt')
DEBUG_TOOLKIT_ACCESS_TRACKING
When internal tools modify system live
βœ… RULES (3)
Log all debug toolkit usage
Require signed requests
Show operator identity in UI/logs
❌ ANTI-PATTERNS (3)
Anonymous debug commands
No linkage to change reason
Access via undocumented endpoints
πŸ’» CODE HINTS (1)
toolkit.logUsage('clear-cache', user)
πŸ§ͺ VALIDATION
Trigger debug path, elevate log, inject trace, and attach remote session. Validate expiry, audit, and safe teardown.
#299Profiling Matrix6 cells18 rules18 anti6 hints
Define structured profiling practices to analyze code performance hotspots, memory usage, CPU time, and improve bottlenecks under real-world load.
profiling_scopetool_typesampling_intervaltrigger_conditionsafety_and_overheadresult_analysis
ON_DEMAND_CPU_PROFILING
When high CPU usage is observed
βœ… RULES (3)
Run profiler with minimal overhead
Target process by PID or container
Limit duration and frequency
❌ ANTI-PATTERNS (3)
Full trace dump on all services
Permanent CPU profiler on
No export format for tool
πŸ’» CODE HINTS (1)
pprof.cpu(target, duration=30s)
MEMORY_LEAK_HEAP_SNAPSHOT
When heap growth or GC pressure is detected
βœ… RULES (3)
Capture heap snapshot after warmup
Analyze retained references
Correlate with release versions
❌ ANTI-PATTERNS (3)
No heap collection trigger
Snapshot without version context
Ignoring internal allocators
πŸ’» CODE HINTS (1)
heap.dump('/tmp/heap.heapsnapshot')
LOW_TRAFFIC_BACKGROUND_PROFILING
When profiling continuously over time
βœ… RULES (3)
Run only under low usage windows
Throttle and rotate profiling sessions
Stream results for offline analysis
❌ ANTI-PATTERNS (3)
Profiling during peak load
No rotation or purging
Results stored inline in logs
πŸ’» CODE HINTS (1)
if (isLowTraffic()) startProfiling()
PERF_EVENT_PROBE_TRIGGERING
When bottlenecks appear under specific ops
βœ… RULES (3)
Use eBPF/perf to attach probes
Aggregate latency by syscall
Visualize histogram over time
❌ ANTI-PATTERNS (3)
Trace every syscall
No filtering by event or process
Profiling causes kernel panic
πŸ’» CODE HINTS (1)
perf trace -e sched:sched_switch -p 1234
SCHEDULED_PROFILING_FOR_HOT_PATHS
When tracking frequently used functions
βœ… RULES (3)
Schedule profiler daily
Capture call graph output
Label with version + env context
❌ ANTI-PATTERNS (3)
Unlabeled flamegraphs
Running profiler without aggregation
No automation of profiling runs
πŸ’» CODE HINTS (1)
flamegraph.capture(target, context=env)
PROFILING_RESULT_DIFF_AND_REPORTING
When analyzing impact of code change
βœ… RULES (3)
Export results to standard format
Compare deltas across runs
Integrate diff view in CI dashboard
❌ ANTI-PATTERNS (3)
No baseline captured
Raw profile dumped with no tooling
No visibility for team
πŸ’» CODE HINTS (1)
profiler.diff(run1, run2).report()
πŸ§ͺ VALIDATION
Capture CPU and heap profiles under load. Compare profiles before/after deploy. Confirm diff view, flamegraph labeling, and storage hygiene.
#300Production Forensics Matrix6 cells18 rules18 anti6 hints
Define structured investigative approaches for post-incident analysis, focusing on evidence capture, correlation, and recovery trail in production.
evidence_captureincident_timeline_buildingsystem_state_snapshotcorrelation_methodretention_and_auditabilityforensic_tooling
LOG_AND_TRACE_FREEZE_ON_INCIDENT
When SLO is breached or error spike detected
βœ… RULES (3)
Snapshot logs, traces, metrics buffer
Isolate impacted pods or containers
Tag all with incident ID
❌ ANTI-PATTERNS (3)
Overwriting evidence in circular buffer
No link between trace/log/alert
No freeze on alert condition
πŸ’» CODE HINTS (1)
incident.capture('latency_slo_breach')
TEMPORAL_TRACE_AND_LOG_CORRELATION
When reconstructing what happened across systems
βœ… RULES (3)
Sort logs/traces by timestamp
Link by request/session ID
Visualize as timeline or DAG
❌ ANTI-PATTERNS (3)
No clock sync between services
No causality modeling
Raw logs only, no timeline view
πŸ’» CODE HINTS (1)
forensics.timeline(traceId)
SYSTEM_STATE_AND_ENV_SNAPSHOT
When debugging environmental contribution to bug
βœ… RULES (3)
Record environment variables
Capture deployment manifest, active flags
Archive container/image version
❌ ANTI-PATTERNS (3)
Missing infra version at incident
No snapshot of runtime flags
Only code trace with no env context
πŸ’» CODE HINTS (1)
snapshot.env('api-node-4')
INCIDENT_CHAIN_OF_EVENTS_LOGGING
When cause is multi-stage or escalated
βœ… RULES (3)
Log manual actions, retries, escalations
Include human and system actors
Correlate with timestamped events
❌ ANTI-PATTERNS (3)
Partial story only from alerts
Missing operator actions
No chain across microservices
πŸ’» CODE HINTS (1)
audit.logEvent('rollbackTriggered', by='oncall')
EVIDENCE_RETENTION_AND_CHAIN_OF_CUSTODY
When analysis or compliance is required
βœ… RULES (3)
Export forensic bundle per incident
Sign and store with hash
Restrict tampering with WORM policy
❌ ANTI-PATTERNS (3)
Log deletion post incident
No export of incident state
No retention beyond 24h buffer
πŸ’» CODE HINTS (1)
incident.archive('bundle-2026-001')
POSTMORTEM_TOOLKIT_AND QUERY INTERFACE
When running retrospective investigation
βœ… RULES (3)
Enable filterable timeline by component
Compare across incidents
Tag learnings and unresolved threads
❌ ANTI-PATTERNS (3)
Static docs only for review
No cross-incident trend view
Manual note taking for lessons
πŸ’» CODE HINTS (1)
postmortem.query('db outage')
πŸ§ͺ VALIDATION
Trigger incident alert. Confirm log freeze, env snapshot, timeline, forensic export, and postmortem query tooling.
β–Ό ⭐ Bonus (301–309) 9 matrices
#301Mass Ingestion & Context Bridge Matrix6 cells12 rules6 anti6 hints
Determines how massive term databases (600K+ entries) are ingested, indexed, scored for relevance, and bridged into the Matrix Context Engine for real-time injection into layouts.
ingestion_methodindexing_strategyrelevance_scoringinjection_target
massctx_001
When ingesting 600K+ terms from local IndexedDB, stream terms in chunks (e.g. 10K) to avoid blocking the main thread and support resumable ingestion.
βœ… RULES (2)
Use a cursor over IndexedDB object store
Ingest 10,000 terms per animation frame slice
❌ ANTI-PATTERNS (1)
Loading entire dataset into memory in one shot
πŸ’» CODE HINTS (1)
cursor.continue(); request.onsuccess = e => buffer.push(e.result);
massctx_002
To enable keyword lookup over massive datasets, construct an inverted index mapping tokens to term IDs.
βœ… RULES (2)
Tokenize all terms using standard tokenizer
Build mapping: token β†’ Set(termIDs)
❌ ANTI-PATTERNS (1)
Linear scan of terms array on every query
πŸ’» CODE HINTS (1)
index['component'] = new Set([id1, id2, id3])
massctx_003
When ranking matched terms by relevance, use BM25 scoring algorithm for context-sensitive ranking.
βœ… RULES (2)
Store term frequency (tf) and document frequency (df) per token
Calculate BM25 with tuned k1, b params
❌ ANTI-PATTERNS (1)
Sorting matches by raw frequency only
πŸ’» CODE HINTS (1)
score = bm25(tf, df, docLen, avgDocLen)
massctx_004
When context budget is limited (e.g. 1024 tokens), select top-K scoring terms to inject into Matrix Context Engine.
βœ… RULES (2)
Sort all candidates by score descending
Keep adding until budget exhausted
❌ ANTI-PATTERNS (1)
Injecting all matches regardless of token cost
πŸ’» CODE HINTS (1)
candidates.sort(byScore).slice(0, K)
massctx_005
When bridging to the Matrix Context Engine, respect the max injection window (e.g. 1024 tokens) by estimating token length of each term.
βœ… RULES (2)
Estimate token count per term (e.g. tiktoken or GPT tokenizer)
Reject terms that exceed remaining window
❌ ANTI-PATTERNS (1)
Overfilling injection buffer beyond model context size
πŸ’» CODE HINTS (1)
if (usedTokens + term.tokens <= 1024) inject(term)
massctx_006
When injecting terms into layout-aware environments, bind each term to its UI component (e.g. grid cell, tooltip, side panel) via the Maestro bridge.
βœ… RULES (2)
Maintain term β†’ component mapping dictionary
Dispatch injected terms to registered layout receivers
❌ ANTI-PATTERNS (1)
Dumping terms into UI without contextual binding
πŸ’» CODE HINTS (1)
componentMap[term.id] = 'SidebarList'; layout.inject(term)
πŸ§ͺ VALIDATION
Verify: chunking avoids memory spikes, inverted index supports fast lookup, BM25 scores are calculated correctly, context budget not exceeded, terms injected to correct layout targets via Maestro.
#302Type Inference Matrix6 cells12 rules6 anti6 hints
Determines how type inference behaves in different contexts β€” variable declarations, return types, function parameters, and destructuring.
inference_contextannotation_requirementprecision_leveltooling_support
infer_001
When initializing a variable with a literal, rely on inference to determine type automatically.
βœ… RULES (2)
Avoid explicit type unless needed
Allow compiler to infer from assigned value
❌ ANTI-PATTERNS (1)
const x: string = 'abc' // redundant
πŸ’» CODE HINTS (1)
const name = 'Alice'
infer_002
When function returns expression directly, allow return type to be inferred from value.
βœ… RULES (2)
Let TS infer return type from return statement
Avoid redundant annotation
❌ ANTI-PATTERNS (1)
Manual annotation on simple one-liners
πŸ’» CODE HINTS (1)
function getId() { return 42 }
infer_003
When writing inline callbacks (e.g. map), allow TS to infer parameter types from array element type.
βœ… RULES (2)
Avoid annotating callback arg manually
Let TS infer from context
❌ ANTI-PATTERNS (1)
(item: string) => item.length when already inferred
πŸ’» CODE HINTS (1)
items.map(item => item.length)
infer_004
When destructuring objects or arrays, allow TS to infer field types based on RHS structure.
βœ… RULES (2)
Prefer const { x } = obj over const x: number = obj.x
Destructure only needed fields
❌ ANTI-PATTERNS (1)
Destructuring then retyping fields manually
πŸ’» CODE HINTS (1)
const { id, name } = user
infer_005
When merging objects with spread, TS infers intersection type combining both sources.
βœ… RULES (2)
Check that overlapping fields are compatible
Avoid spreading incompatible types
❌ ANTI-PATTERNS (1)
Blindly merging without type awareness
πŸ’» CODE HINTS (1)
const full = { ...base, ...override }
infer_006
When creating arrays, let TS infer literal type or union type from elements automatically.
βœ… RULES (2)
Prefer const arr = [1, 2, 3]
Avoid manually annotating simple homogeneous arrays
❌ ANTI-PATTERNS (1)
const arr: number[] = [1, 2, 3] // redundant
πŸ’» CODE HINTS (1)
const flags = [true, false, true]
πŸ§ͺ VALIDATION
Verify: variables inferred on init, return types inferred, callback params inferred, destructuring drives type, spread creates correct intersections, array types inferred.
#303Type Declaration Strategy Matrix6 cells12 rules6 anti6 hints
Determines how types are declared and organized β€” type vs. interface, inline vs. extracted, explicit vs. inferred, and naming conventions.
declaration_stylescoperefactorabilityreadability
typedef_001
When creating simple structural combinations (e.g. union or intersection), use type alias with inline composition.
βœ… RULES (2)
Use type X = A | B
Combine with keyof, typeof for mappings
❌ ANTI-PATTERNS (1)
Creating named interfaces for every trivial case
πŸ’» CODE HINTS (1)
type Result = Success | Failure
typedef_002
When defining object contracts, use interface to support extension and declaration merging.
βœ… RULES (2)
Use interface for component props
Extendable via extends or merging
❌ ANTI-PATTERNS (1)
Overusing type alias for deeply nested props
πŸ’» CODE HINTS (1)
interface Props { title: string }
typedef_003
When a shape is reused across multiple places, extract it into a named type or interface in a shared file.
βœ… RULES (2)
Avoid inline duplication
Name types clearly for reusability
❌ ANTI-PATTERNS (1)
Inline types repeated in many files
πŸ’» CODE HINTS (1)
// types.ts export type User = { id: string }
typedef_004
When a variable’s type is obvious and local, allow inference and avoid unnecessary annotations.
βœ… RULES (2)
Let TS infer from value
Annotate only when ambiguous
❌ ANTI-PATTERNS (1)
const x: number = 5
πŸ’» CODE HINTS (1)
const price = 9.99
typedef_005
When naming types, use suffix conventions like `Props`, `State`, `Input`, `Output` to clarify intent.
βœ… RULES (2)
Use suffixes to signal purpose
Keep naming consistent across project
❌ ANTI-PATTERNS (1)
type A = ... // vague name
πŸ’» CODE HINTS (1)
type LoginInput = {...}
typedef_006
When deciding between type and interface, prefer interface for object shape and type for unions and mapped types.
βœ… RULES (2)
interface = extends, mergeable
type = unions, primitives, mapped
❌ ANTI-PATTERNS (1)
Blind adherence to one style
πŸ’» CODE HINTS (1)
type Primitive = string | number
πŸ§ͺ VALIDATION
Verify: types used contextually (interface vs. type), names clarify purpose, reused types extracted, and inference allowed locally.
#304Semantic Validation Matrix6 cells12 rules6 anti6 hints
Determines how semantic meaning is validated beyond syntax β€” e.g. domain-specific meaning, logical consistency, temporal plausibility, and business rules.
semantic_typevalidation_logicbusiness_contexterror_handling
semantic_001
When a value must meet business logic beyond syntax (e.g. SKU must be active), validate using domain rules.
βœ… RULES (2)
Check value against domain model or DB
Fail validation if inactive or blacklisted
❌ ANTI-PATTERNS (1)
Allowing any syntactically valid SKU
πŸ’» CODE HINTS (1)
if (!sku.isActive) throw Error('Inactive SKU')
semantic_002
When a date has semantic constraint (e.g. DOB must be in past), validate using logical calendar rule.
βœ… RULES (2)
Compare date to current time contextually
Allow edge case override if configured
❌ ANTI-PATTERNS (1)
Allowing DOB in future
πŸ’» CODE HINTS (1)
if (dob > today) error('Invalid DOB')
semantic_003
When two fields interact logically (e.g. end date > start date), validate combination, not each in isolation.
βœ… RULES (2)
Use cross-field validation logic
Surface combined error at appropriate UI level
❌ ANTI-PATTERNS (1)
Validating fields independently without context
πŸ’» CODE HINTS (1)
if (end < start) showError('End must be after start')
semantic_004
When a value (e.g. user ID) must be validated against external or federated systems, enforce consistency rules.
βœ… RULES (2)
Query external source or IDP
Fail if mismatched identity
❌ ANTI-PATTERNS (1)
Assuming internal ID is authoritative
πŸ’» CODE HINTS (1)
validateAgainstIDP(userId)
semantic_005
When numeric input (e.g. hours/week) must make semantic sense, enforce min/max within real-world plausible range.
βœ… RULES (2)
Set min/max per domain best practice
Reject absurd extremes even if technically valid
❌ ANTI-PATTERNS (1)
Allowing 999 hours/week
πŸ’» CODE HINTS (1)
if (hours > 80) error('Too many hours')
semantic_006
When a rule depends on other context (e.g. field visible only in country X), validate only if condition met.
βœ… RULES (2)
Bind validation to visibility logic
Skip if field not applicable in context
❌ ANTI-PATTERNS (1)
Applying validation when field hidden or inactive
πŸ’» CODE HINTS (1)
if (isVisible(field)) validate(field)
πŸ§ͺ VALIDATION
Verify: semantic rules enforced (e.g. active SKUs, DOB in past, end > start), identity checked externally, numeric ranges plausible, context-bound rules conditional.
#305Constraint Source Matrix6 cells12 rules6 anti6 hints
Determines where constraints originate β€” business logic, UI patterns, legal/compliance, backend storage, or external APIs.
source_typeconstraint_originownershipvolatility
source_001
When a rule is part of domain behavior (e.g. age must be >18), it originates in product/business logic layer.
βœ… RULES (2)
Document rule in product spec
Apply consistently in frontend + backend
❌ ANTI-PATTERNS (1)
Scattered enforcement across layers
πŸ’» CODE HINTS (1)
if (age < 18) throw Error('Must be over 18')
source_002
When UI restricts certain input patterns (e.g. no emojis), constraint originates in usability or branding pattern.
βœ… RULES (2)
Validate pattern at input level
Style violation inline
❌ ANTI-PATTERNS (1)
Blocking backend without clear UI indication
πŸ’» CODE HINTS (1)
pattern=/^[a-zA-Z0-9 ]+$/
source_003
When a field must follow a legal rule (e.g. 9-digit SSN), constraint source is compliance team or external law.
βœ… RULES (2)
Reference external compliance spec
Log rule origin for audit
❌ ANTI-PATTERNS (1)
Altering legal constraint for convenience
πŸ’» CODE HINTS (1)
if (!/^\d{9}$/.test(ssn)) throw Error('Invalid SSN')
source_004
When DB column type (e.g. VARCHAR(50)) imposes constraint, rule source is schema definition.
βœ… RULES (2)
Align UI maxLength with DB schema
Reject oversized values at backend
❌ ANTI-PATTERNS (1)
Frontend allows long strings β†’ backend truncates silently
πŸ’» CODE HINTS (1)
<input maxlength='50' />
source_005
When external system defines input shape (e.g. payment gateway allows only 10 chars), rule source is API contract.
βœ… RULES (2)
Read and apply from external API docs
Validate before request sent
❌ ANTI-PATTERNS (1)
Trial/error against external APIs
πŸ’» CODE HINTS (1)
if (input.length > 10) error('Too long for Stripe')
source_006
When admin defines limit dynamically (e.g. max users per org), constraint is user-configured.
βœ… RULES (2)
Load config before applying
Expose limit in UI for awareness
❌ ANTI-PATTERNS (1)
Hardcoding admin-editable limits
πŸ’» CODE HINTS (1)
if (org.users > config.maxUsers) showError()
πŸ§ͺ VALIDATION
Verify: each constraint has traceable source, documented reason, mapped to enforcement point (UI/server), and reflected in config/schema if relevant.
#306Constraint Boundary Matrix6 cells12 rules6 anti6 hints
Determines where constraints are enforced β€” client vs. server, schema vs. code, sync vs. async, pre vs. post mutation.
constraint_locationtiminglayerresilience
constraint_001
When input must be validated before form submission, enforce rules on client synchronously (e.g. length, pattern).
βœ… RULES (2)
Run before submit button activates
Keep logic fast and UI-bound
❌ ANTI-PATTERNS (1)
Relying only on backend for simple length checks
πŸ’» CODE HINTS (1)
onBlur = validateField
constraint_002
When critical logic (e.g. permission, duplicates) must be guaranteed, enforce on server after submission.
βœ… RULES (2)
Repeat all critical constraints server-side
Return actionable errors
❌ ANTI-PATTERNS (1)
Trusting only client
πŸ’» CODE HINTS (1)
POST /submit β†’ validate β†’ persist
constraint_003
When frontend and backend share types (e.g. with TypeScript or JSON schema), validate using same source in both.
βœ… RULES (2)
Generate validators from shared schema
Avoid drift in logic
❌ ANTI-PATTERNS (1)
Forked validation logic across environments
πŸ’» CODE HINTS (1)
validate(input, schema)
constraint_004
When validation requires external resource (e.g. username availability), trigger async call after user stops typing.
βœ… RULES (2)
Use debounce before request
Avoid blocking full form submission
❌ ANTI-PATTERNS (1)
Async validation on every keystroke
πŸ’» CODE HINTS (1)
debounce(() => checkName(name), 500)
constraint_005
When mutation can cause new invalid state (e.g. balance < 0), validate after side effect and revert if needed.
βœ… RULES (2)
Wrap mutation in try/catch
Include rollback logic
❌ ANTI-PATTERNS (1)
No check after dangerous mutation
πŸ’» CODE HINTS (1)
try { applyTransfer() } catch { rollback() }
constraint_006
When server cannot enforce (e.g. browser API constraints), use best-effort client-only checks for resilience.
βœ… RULES (2)
Warn but don't block
Use browser features like input type
❌ ANTI-PATTERNS (1)
Trying to enforce server-level integrity on weak client-side checks
πŸ’» CODE HINTS (1)
<input type='email' required />
πŸ§ͺ VALIDATION
Verify: client sync constraints enforce basic rules, server guards critical rules, shared schemas match, async API-based validation debounced, mutation rollback safe, client-only checks enhance UX.
#307Declarative Rule Schema Matrix6 cells12 rules6 anti6 hints
Determines how validation rules are structured declaratively β€” using JSON schema, rule chaining, conditional rules, and reusable logic blocks.
rule_definitionschema_formatconditional_logicreusability
rule_001
When defining validation schema, use JSON Schema syntax with types like string, number, boolean, array.
βœ… RULES (2)
Use type="string"|"number" etc.
Use required, minLength, max properties
❌ ANTI-PATTERNS (1)
Loose objects with no validation metadata
πŸ’» CODE HINTS (1)
{ type: 'string', minLength: 3, maxLength: 20 }
rule_002
When using function-based validation (e.g. Yup, Zod), chain validators in semantic order (e.g. .required().min(3))
βœ… RULES (2)
Apply .required before .min/.max
Separate logic for better testability
❌ ANTI-PATTERNS (1)
Chaining too many inline conditions
πŸ’» CODE HINTS (1)
yup.string().required().min(3)
rule_003
When a rule applies only if another field has a value, use conditional validation.
βœ… RULES (2)
Use .when() in Yup or if/then in JSON Schema
Ensure fallback defaults
❌ ANTI-PATTERNS (1)
Applying all rules unconditionally
πŸ’» CODE HINTS (1)
.when('otherField', { is: true, then: schemaA })
rule_004
When complex logic is reused across fields, define it as a reusable function or schema block.
βœ… RULES (2)
Write testable validator functions
Register block under global schema registry
❌ ANTI-PATTERNS (1)
Duplicating logic in multiple schema parts
πŸ’» CODE HINTS (1)
const isNationalId = val => /^\d{9}$/.test(val)
rule_005
When combining multiple rule paths, use logical constructs like allOf, oneOf, anyOf, not.
βœ… RULES (2)
Use allOf to combine conditions
Use oneOf for exclusive choices
❌ ANTI-PATTERNS (1)
Multiple rules with no logical structure
πŸ’» CODE HINTS (1)
{ allOf: [ruleA, ruleB] }
rule_006
When building public-facing or self-documented schema, include metadata fields like title, description, examples.
βœ… RULES (2)
Provide human-readable description
Add example values
❌ ANTI-PATTERNS (1)
Schemas that developers can't interpret
πŸ’» CODE HINTS (1)
{ title: 'Email', description: 'Valid email address', example: 'user@example.com' }
πŸ§ͺ VALIDATION
Verify: rules use typed schema, validators chained semantically, conditionals present, reusable logic extracted, logic combined with allOf/oneOf, metadata included.
#308Form Field Behavior Matrix6 cells12 rules6 anti6 hints
Determines how individual form fields behave β€” requiredness, readonly, disabled, autofill behavior, and reset handling.
field_behavioruser_editabilityform_interactionbrowser_support
formfield_001
When a field is mandatory, use the required attribute and reinforce with visual indicator.
βœ… RULES (2)
Use required on <input>
Add * or (required) label indicator
❌ ANTI-PATTERNS (1)
Relying solely on backend validation for required
πŸ’» CODE HINTS (1)
<input required />
formfield_002
When a field shows fixed value (e.g. username), use readonly to prevent editing but allow focus/select.
βœ… RULES (2)
Use readonly not disabled
Style as static text but selectable
❌ ANTI-PATTERNS (1)
Using disabled when field must be copied
πŸ’» CODE HINTS (1)
<input readonly value='john_doe' />
formfield_003
When a field should be skipped entirely (e.g. based on condition), use disabled to exclude from interaction and submission.
βœ… RULES (2)
Use disabled to prevent focus and form submission
Visually gray out field
❌ ANTI-PATTERNS (1)
Relying on CSS only to indicate disabled state
πŸ’» CODE HINTS (1)
<input disabled />
formfield_004
When browser should suggest values (e.g. name, email), use autocomplete attributes to hint.
βœ… RULES (2)
Use autocomplete='email' etc.
Match expected field semantics
❌ ANTI-PATTERNS (1)
Leaving autocomplete off when autofill desired
πŸ’» CODE HINTS (1)
<input autocomplete='email' />
formfield_005
When form has reset button, ensure all fields return to original value or empty as expected.
βœ… RULES (2)
Use <form> with reset button
Track default values if custom form logic
❌ ANTI-PATTERNS (1)
Reset button does not affect JS-managed fields
πŸ’» CODE HINTS (1)
<button type='reset'>Reset</button>
formfield_006
When field includes an icon (e.g. calendar, visibility toggle), ensure it's focusable and click doesn't blur input.
βœ… RULES (2)
Use button/icon inside input wrapper
Prevent blur on mousedown
❌ ANTI-PATTERNS (1)
Icon click causes input to lose focus
πŸ’» CODE HINTS (1)
onMouseDown={e => e.preventDefault()}
πŸ§ͺ VALIDATION
Verify: required uses HTML attr, readonly used for display-only fields, disabled skips submission, autocomplete aids autofill, reset works, and icons inside fields behave properly.
#309Field Type Strategy Matrix6 cells12 rules6 anti6 hints
Determines which input type to use per field intent β€” email, password, number, date, text, URL, with appropriate mobile and accessibility behavior.
field_intentinput_typeui_enhancementaccessibility_tags
fieldtype_001
When collecting user email, use <input type='email'> to trigger email keyboard and browser validation.
βœ… RULES (2)
Use inputmode=email on mobile
Set aria-required if mandatory
❌ ANTI-PATTERNS (1)
Using type=text for email
πŸ’» CODE HINTS (1)
<input type='email' inputmode='email' required />
fieldtype_002
When input is phone number, use <input type='tel'> to provide dialpad on mobile.
βœ… RULES (2)
Use pattern=\d{10} if fixed format
Support country code with placeholder
❌ ANTI-PATTERNS (1)
Using type=number for phone
πŸ’» CODE HINTS (1)
<input type='tel' pattern='\d{10}' />
fieldtype_003
When user enters secret input, use <input type='password'> to hide characters and enable reveal toggle.
βœ… RULES (2)
Include show/hide password button
Set autocomplete='current-password'
❌ ANTI-PATTERNS (1)
Using type=text for passwords
πŸ’» CODE HINTS (1)
<input type='password' autocomplete='current-password' />
fieldtype_004
When numeric values are needed (e.g. quantity), use <input type='number'> to support increment buttons.
βœ… RULES (2)
Set min, max, step attributes as needed
Use inputmode=numeric for better mobile UX
❌ ANTI-PATTERNS (1)
Using text input for numbers without validation
πŸ’» CODE HINTS (1)
<input type='number' min='1' step='1' />
fieldtype_005
When collecting structured dates, use <input type='date'> for native calendar UI.
βœ… RULES (2)
Set max date to today if DOB
Fallback to three dropdowns if unsupported
❌ ANTI-PATTERNS (1)
Using free text for date
πŸ’» CODE HINTS (1)
<input type='date' max='2023-12-31' />
fieldtype_006
When asking for web address, use <input type='url'> to trigger URL validation and correct keyboard.
βœ… RULES (2)
Add placeholder starting with https://
Use inputmode=url
❌ ANTI-PATTERNS (1)
Accepting malformed URLs with type=text
πŸ’» CODE HINTS (1)
<input type='url' inputmode='url' />
πŸ§ͺ VALIDATION
Verify: type=email triggers validation, tel opens dialpad, password hides input, number enforces range, date shows calendar, and URL validates format.
β–Ό 🧩 Gap Fill (311–321) 11 matrices
#311UI Container Isolation Matrix6 cells18 rules18 anti6 hints
Define architectural decisions for isolating UI containers to prevent style, state, and event leakage between independent regions using iframes, shadow DOM, scoped CSS, or web components.
isolation_mechanismstyle_containmentevent_boundarystate_scopeperformance_impactaccessibility_passthrough
IFRAME_STRONG_ISOLATION
When embedding a full third-party application
βœ… RULES (3)
Use iframe with sandbox attributes
Disable script access unless trusted
Restrict same-origin access where possible
❌ ANTI-PATTERNS (3)
Allowing iframe to access parent DOM
Using iframes without sandbox
No fallback for iframe load failure
πŸ’» CODE HINTS (1)
<iframe src='...' sandbox='allow-scripts allow-same-origin'>
SHADOW_DOM_COMPONENT_ENCAPSULATION
When creating reusable UI components
βœ… RULES (3)
Use shadow DOM in web components
Define style boundaries within shadow root
Handle events explicitly across boundaries
❌ ANTI-PATTERNS (3)
Global styles leaking into shadow components
Direct DOM traversal into shadow roots
Relying on document.querySelector() globally
πŸ’» CODE HINTS (1)
this.attachShadow({ mode: 'open' })
CSS_MODULE_STYLE_SCOPING
When isolating styles across co-located UI
βœ… RULES (3)
Use CSS Modules or scoped class generation
Generate unique classnames at build time
Avoid global CSS imports in components
❌ ANTI-PATTERNS (3)
Conflicting class names across modules
Global style override via base class
One global stylesheet per app
πŸ’» CODE HINTS (1)
import styles from './Button.module.css'
EVENT_PROPAGATION_CONTAINMENT
When handling UI events within a widget
βœ… RULES (3)
Stop event propagation at container boundary
Namespace event listeners where applicable
Use shadow DOM to isolate bubbling scope
❌ ANTI-PATTERNS (3)
Global event listener capturing internal events
Accidental propagation of custom events
Re-dispatching native events without namespacing
πŸ’» CODE HINTS (1)
e.stopPropagation()
STATE_SCOPE_ISOLATION_VIA_PROPS
When managing component-local state
βœ… RULES (3)
Use props/state boundaries between modules
Avoid global stores unless needed
Scope context providers to component tree
❌ ANTI-PATTERNS (3)
Using single global store for all widgets
Sharing mutable objects via context
Tight coupling between unrelated components
πŸ’» CODE HINTS (1)
<Provider value={{ isolated: true }}>
ACCESSIBILITY_CONTEXT_PASS_THROUGH
When nesting containers deeply
βœ… RULES (3)
Ensure focus forwarding through boundaries
Propagate ARIA roles where appropriate
Use slot/label bindings in web components
❌ ANTI-PATTERNS (3)
Focus trap inside isolated container
ARIA roles stripped at iframe boundary
Screen reader can't access inner content
πŸ’» CODE HINTS (1)
<slot name='label' aria-labelledby='...'>
πŸ§ͺ VALIDATION
Embed multiple widgets with independent styles, state, and events. Verify no cross-leakage and accessibility is preserved.
#312Tabbed Navigation Matrix6 cells18 rules18 anti6 hints
Define UI and state patterns for implementing tabbed navigation in single-page apps, supporting routing, focus, accessibility, and lazy loading.
tab_state_storagerouting_integrationfocus_managementaria_roles_and_labelslazy_loading_and_prefetchkeyboard_navigation
INTERNAL_STATE_WITHOUT_URL
When tabs are local UI-only (not shareable)
βœ… RULES (3)
Use component state to track selected tab
Reset on route change
Avoid history push
❌ ANTI-PATTERNS (3)
Inconsistent state across refresh
No way to track tab via analytics
Unexpected browser back behavior
πŸ’» CODE HINTS (1)
const [tab, setTab] = useState('overview')
ROUTE_DRIVEN_TAB_URL_SYNC
When tab should be shareable via URL
βœ… RULES (3)
Use query param or subroute per tab
Sync selected tab from URL on mount
Update history appropriately
❌ ANTI-PATTERNS (3)
Tab state only in memory
Manual parsing of URL string
Broken navigation on refresh
πŸ’» CODE HINTS (1)
router.push('/settings?tab=roles')
FOCUS_MANAGEMENT_AND_TABINDEX
When tabs are changed by keyboard or screen reader
βœ… RULES (3)
Set tabindex and focus target on tab switch
Announce new panel via aria-live
Trap focus within panel if needed
❌ ANTI-PATTERNS (3)
Focus lost on switch
No screen reader announcement
Tab panel not focusable
πŸ’» CODE HINTS (1)
panelRef.current.focus()
ARIA_ROLE_TAB_AND_TABPANEL
When building accessible tabs
βœ… RULES (3)
Use role="tablist", role="tab", role="tabpanel"
Link tab and panel via aria-controls
Manage aria-selected state
❌ ANTI-PATTERNS (3)
Missing aria attributes
Improper nesting of tab elements
No indication of selected tab
πŸ’» CODE HINTS (1)
<div role="tab" aria-selected="true">Users</div>
LAZY_LOAD_ON_TAB_ACTIVATION
When optimizing performance of many tab panels
βœ… RULES (3)
Mount panel only when activated
Keep content in memory if needed
Prefetch data on hover or intent
❌ ANTI-PATTERNS (3)
Render all panels on load
Tab switch triggers full reload
Data fetched only on visible paint
πŸ’» CODE HINTS (1)
{activeTab === 'team' && <TeamPanel />}
KEYBOARD_NAVIGATION_AND_ARROWS
When users navigate via keyboard only
βœ… RULES (3)
Use arrow keys to switch tabs
Wrap focus across ends
Announce selection change
❌ ANTI-PATTERNS (3)
Keyboard trap in tablist
Manual focus override
Arrow keys do nothing
πŸ’» CODE HINTS (1)
onKeyDown={handleArrowKeyNavigation}
πŸ§ͺ VALIDATION
Tab through panels, use keyboard to switch, validate URL sync, test screen reader flow, and lazy load behavior.
#313UI Keyboard Accessibility Matrix6 cells18 rules18 anti6 hints
Define best practices and failure points for ensuring keyboard accessibility in interactive UI components, supporting ARIA compliance, navigation, focus behavior, and interaction consistency.
navigation_patternfocus_managementkeyboard_interaction_modelaria_integrationcomponent_type_coveragetesting_and_validation
FOCUS_VISIBLE_AND_TAB_INDEX
When elements receive keyboard focus
βœ… RULES (3)
Use :focus-visible or visible outlines
Respect tabIndex order
Ensure no focus trap occurs unintentionally
❌ ANTI-PATTERNS (3)
outline: none without replacement
Hidden elements receiving focus
Skipping interactive items in tab order
πŸ’» CODE HINTS (1)
element.style.outline = '2px solid blue'
ARROW_KEY_NAV_IN_COMPOSITES
When navigating between items inside a widget (e.g. tabs, menus)
βœ… RULES (3)
Use horizontal/vertical arrow keys per ARIA spec
Loop or constrain focus as needed
Announce selected state
❌ ANTI-PATTERNS (3)
Focus stays stuck on one item
Arrow keys do nothing
Focus jumps to non-intended elements
πŸ’» CODE HINTS (1)
onKeyDown={handleArrowNavigation}
ESCAPE_KEY_FOR_EXIT
When user is inside a modal or popup
βœ… RULES (3)
Bind Escape key to close modal/dialog
Return focus to triggering element
Announce closing to screen reader if needed
❌ ANTI-PATTERNS (3)
Escape key has no effect
Focus lost after dialog closes
Requires mouse to exit overlay
πŸ’» CODE HINTS (1)
if (e.key === 'Escape') closeModal()
ARIA_ROLE_AND_STATE_ANNOUNCEMENT
When rendering toggleable or interactive elements
βœ… RULES (3)
Use role=button/menu/tab/checkbox etc.
Update aria-pressed/expanded/selected as needed
Ensure label is programmatically associated
❌ ANTI-PATTERNS (3)
Clickable div with no role
Missing aria attributes on state change
Non-descriptive labels
πŸ’» CODE HINTS (1)
<div role='button' aria-pressed='true'>Mute</div>
KEYBOARD_ACCESS_FOR_ALL_COMPONENTS
When building custom interactive components
βœ… RULES (3)
Ensure Enter and Space activate actionable items
Simulate mouse events if needed
Document key bindings if non-standard
❌ ANTI-PATTERNS (3)
Actions only wired to onClick
Keyboard-only users blocked
Unexpected behavior on Enter
πŸ’» CODE HINTS (1)
onKeyDown={e => e.key === 'Enter' && activate()}
ACCESSIBILITY_TEST_AUTOMATION
When validating keyboard navigation in CI
βœ… RULES (3)
Write test cases for keyboard flows
Use tools like axe-core or playwright-accessibility
Test across screen readers if feasible
❌ ANTI-PATTERNS (3)
Manual-only testing
No test for keyboard behavior
Missing focus state assertions
πŸ’» CODE HINTS (1)
expect(activeElement).toHaveFocus()
πŸ§ͺ VALIDATION
Navigate UI with keyboard only. Verify focus visibility, component accessibility, Enter/Space behavior, Escape exit, and tab order. Run CI tests.
#314Empty State Matrix6 cells18 rules18 anti6 hints
Define best practices and failure points for designing empty states in UI β€” including first-time use, no data, errors, filters, and onboarding use cases.
empty_state_typevisual_guidancecall_to_actionuser_emotion_handlinglocalization_and_contexttest_coverage
FIRST_TIME_USER_EMPTY
When user visits feature with no prior data
βœ… RULES (3)
Explain what this screen is for
Use icon or mascot to soften experience
Provide action to get started
❌ ANTI-PATTERNS (3)
Blank page with no message
Overwhelming form without context
Technical jargon in first-time flow
πŸ’» CODE HINTS (1)
if (!user.hasData) showEmpty('firstTime')
FILTER_RESULTS_EMPTY
When filters yield zero results
βœ… RULES (3)
Show current filters in summary
Offer reset or suggestions
Use helpful tone (not blaming)
❌ ANTI-PATTERNS (3)
Generic 'No results' only
No visibility into active filters
No CTA or exit path
πŸ’» CODE HINTS (1)
if (results.length === 0) showEmpty('filters')
ERROR_BASED_EMPTY_STATE
When backend or API error occurs
βœ… RULES (3)
Use friendly illustration and title
Log technical details in console
Provide retry or fallback link
❌ ANTI-PATTERNS (3)
Exposing raw error to user
No explanation or guidance
No retry or feedback option
πŸ’» CODE HINTS (1)
catch (e) => showEmpty('error')
ONBOARDING_EMPTY_MODE
When feature has multiple steps before content appears
βœ… RULES (3)
Break down steps visually
Show progress or checklist
Animate or illustrate flow
❌ ANTI-PATTERNS (3)
All-or-nothing experience
Jump straight into complex UI
No indicator of required steps
πŸ’» CODE HINTS (1)
if (!user.completedSetup) showEmpty('onboarding')
EMPTY_STATE_LOCALIZATION
When adapting UI for multiple locales
βœ… RULES (3)
Avoid wordplay that's hard to translate
Support pluralization and gender where needed
Mirror visual direction for RTL locales
❌ ANTI-PATTERNS (3)
Hardcoded English puns
Text cut-off in other languages
Misaligned illustration for language direction
πŸ’» CODE HINTS (1)
i18n.t('empty_state.no_items')
UNIT_TEST_FOR_EMPTY_VARIANTS
When testing multiple empty states per screen
βœ… RULES (3)
Test each scenario (first-time, error, filter)
Verify correct component renders
Mock API, auth, and data
❌ ANTI-PATTERNS (3)
One snapshot only
No tests for error paths
Assumes empty never happens
πŸ’» CODE HINTS (1)
expect(screen.getByText('No results')).toBeInTheDocument()
πŸ§ͺ VALIDATION
Trigger each empty state manually or via mocks. Verify messaging, CTA, visuals, i18n, and test coverage.
#315Scroll and Focus Handling Matrix6 cells18 rules18 anti6 hints
Define patterns and risks for managing scroll position and focus behavior during navigation, modal opening, async content load, or dynamic layout changes.
trigger_contextscroll_restorationfocus_targetingaccessibility_considerationsanimation_and_feedbackedge_case_handling
MODAL_OPEN_REFOCUS_AND_SCROLL_LOCK
When opening modal over background content
βœ… RULES (3)
Set focus to first focusable item
Lock background scroll
Restore focus to trigger on close
❌ ANTI-PATTERNS (3)
No focus shift on open
Body scroll continues in background
Focus lost or reset after close
πŸ’» CODE HINTS (1)
dialogRef.current.focus()
IN_PAGE_NAVIGATION_SCROLL_BEHAVIOR
When navigating via anchor links or tab switches
βœ… RULES (3)
Use scrollIntoView with behavior: 'smooth'
Highlight target section temporarily
Avoid blocking scroll with layout shifts
❌ ANTI-PATTERNS (3)
No scroll or jump behavior
Content flashes past user’s viewport
Missing visual cue at target
πŸ’» CODE HINTS (1)
targetEl.scrollIntoView({ behavior: 'smooth' })
ASYNC_CONTENT_LOAD_AND_SCROLL_RESET
When rendering data after user action
βœ… RULES (3)
Preserve scroll position across updates
Scroll to new content only when intended
Debounce or delay animations
❌ ANTI-PATTERNS (3)
Auto-scroll on every load
State updates wipe scroll position
List resets to top unnecessarily
πŸ’» CODE HINTS (1)
preserveScrollRef.current = window.scrollY
ACCESSIBLE_FOCUS_AFTER_ROUTING
When page or route changes in SPA
βœ… RULES (3)
Set focus to page heading or landmark
Announce section via aria-live
Reset scroll unless restoring history
❌ ANTI-PATTERNS (3)
No focus target on new screen
Multiple tabbable elements receive focus
Reader doesn’t detect screen change
πŸ’» CODE HINTS (1)
mainRef.current.focus(); ariaLive.announce('Dashboard')
DYNAMIC_LAYOUT_CHANGE_SCROLL_DEFENSE
When accordion expands or collapses
βœ… RULES (3)
Animate open/close transitions
Prevent scroll jumps by buffering space
Scroll only if user requested section
❌ ANTI-PATTERNS (3)
Collapse causes content jump
Scroll into hidden section
Keyboard user loses focus or context
πŸ’» CODE HINTS (1)
accordion.toggle(id); scrollIfFocused(id)
TESTING_SCROLL_AND_FOCUS_EVENTS
When validating scroll/focus logic in CI
βœ… RULES (3)
Mock scroll/focus in tests
Test modals, routes, and list interactions
Assert scroll/focus transitions explicitly
❌ ANTI-PATTERNS (3)
No tests for scroll behavior
Focus logic only tested manually
Flaky scroll assertions
πŸ’» CODE HINTS (1)
expect(document.activeElement).toBe(panelRef.current)
πŸ§ͺ VALIDATION
Trigger modal, in-page nav, async load, and accordion. Validate scroll preservation, focus flow, a11y announcements, and test coverage.
#316UI Customization Hooks Matrix6 cells18 rules18 anti6 hints
Define structured mechanisms to enable safe, bounded, and documented customization of UI elements via theme, plugin, slots, render props, or context.
customization_typeexposure_surfacescoping_and_isolationsafety_guardsdocumentation_and_discoveryfallback_strategy
THEME_TOKEN_CUSTOMIZATION
When allowing design changes via theming
βœ… RULES (3)
Use CSS variables or theme objects
Document token meanings
Restrict changes to color, spacing, typography
❌ ANTI-PATTERNS (3)
Global !important overrides
Inline style hacks
Overriding internal class structure
πŸ’» CODE HINTS (1)
theme.colors.primary = '#0040ff'
SLOT_BASED_CONTENT_INSERTION
When enabling injection of markup into component
βœ… RULES (3)
Define named slots in base component
Expose slot boundaries and constraints
Fallback to default content
❌ ANTI-PATTERNS (3)
InnerHTML injection
No constraints on slotted content
No default if slot is missing
πŸ’» CODE HINTS (1)
<slot name='footer'>Default text</slot>
RENDER_PROP_API_FOR_BEHAVIOR
When component allows behavioral variation
βœ… RULES (3)
Pass data and handlers via render prop
Call as function, not element
Document expected API
❌ ANTI-PATTERNS (3)
Render prop treated as React node
Props with unclear contract
Component internal state bypassed
πŸ’» CODE HINTS (1)
<List renderItem={item => <Row data={item} />} />
PLUGIN_EXTENSION_POINT
When supporting user-defined extensions
βœ… RULES (3)
Expose plugin API with boundaries
Restrict access to host internals
Use lifecycle hooks or events
❌ ANTI-PATTERNS (3)
Plugin runs in host context directly
Full access to host memory or store
No versioning or API guarantees
πŸ’» CODE HINTS (1)
pluginSystem.register('onSubmit', fn)
CONTEXT_BASED_VARIANT_INJECTION
When changing component logic per usage context
βœ… RULES (3)
Use React Context or DI container
Define override boundaries
Avoid leaking state across scopes
❌ ANTI-PATTERNS (3)
One global context for entire app
Override reaches deep into nested component
No boundary between consumer trees
πŸ’» CODE HINTS (1)
<CustomizationContext.Provider value={...}>
FALLBACK_TO_BASE_UI_BEHAVIOR
When customization is partial or fails
βœ… RULES (3)
Check for null/undefined customization
Fallback to safe default component
Log or warn on invalid customization
❌ ANTI-PATTERNS (3)
Blank screen if slot missing
Crash on invalid render prop
No default styles when theme fails
πŸ’» CODE HINTS (1)
const Footer = props.renderFooter || DefaultFooter
πŸ§ͺ VALIDATION
Attempt customization with theme, slots, render props, and context. Break customization and confirm fallback. Inspect logs, docs, and constraints.
#317UI Feedback Responsiveness Matrix6 cells18 rules18 anti6 hints
Define how and when to provide visual, tactile, or auditory feedback to user actions across sync and async flows, preventing uncertainty or overreaction.
action_typefeedback_latency_targetfeedback_channelreversibility_or_cancelaccessibility_equivalenceerror_and_retry_path
INSTANT_FEEDBACK_ON_CLICK
When user clicks a button or taps
βœ… RULES (3)
Show visual state (pressed, loading)
Play haptic or sound if enabled
Disable double-click briefly
❌ ANTI-PATTERNS (3)
No visible response for >200ms
Click triggers nothing
Double-click causes duplicate request
πŸ’» CODE HINTS (1)
button.classList.add('active')
ASYNC_OPERATION_PROGRESS_UI
When action takes >300ms to complete
βœ… RULES (3)
Use spinners, skeletons, or loading bars
Label with action name (e.g. β€˜Saving…’)
Avoid layout shifts when showing feedback
❌ ANTI-PATTERNS (3)
Silent loading
Layout jump on feedback
Infinite spinner with no progress hint
πŸ’» CODE HINTS (1)
showSpinnerUntil(promise)
SUCCESS_CONFIRMATION_WITH_ANIMATION
When async operation completes successfully
βœ… RULES (3)
Show checkmark or transition
Auto-dismiss confirmation if not critical
Log or notify background success if passive
❌ ANTI-PATTERNS (3)
Success feels like nothing happened
Lack of animation or feedback
Obnoxious modal for minor confirmation
πŸ’» CODE HINTS (1)
animateCheckmark(); setTimeout(hide, 2s)
UNDO_OR_REDO_FEEDBACK_ACTION
When user performs destructive or significant action
βœ… RULES (3)
Show β€˜undo’ snackbar or banner
Delay actual execution if safe
Announce keyboard shortcut if available
❌ ANTI-PATTERNS (3)
Permanent delete with no undo
Instant destructive action with no notice
Undo hidden in obscure menu
πŸ’» CODE HINTS (1)
toast({message: 'Deleted', action: 'Undo'})
ACCESSIBLE_FEEDBACK_EQUIVALENCE
When feedback is visual or auditory only
βœ… RULES (3)
Use aria-live regions for status
Trigger screen reader announcements
Respect user settings for motion/sound
❌ ANTI-PATTERNS (3)
Animation with no alternative
Sound-only feedback
Aria label missing for key messages
πŸ’» CODE HINTS (1)
<div role='status' aria-live='polite'>Saved!</div>
ERROR_AND_RETRY_VISIBILITY
When async fails or partially succeeds
βœ… RULES (3)
Show error toast or inline message
Provide retry or contact options
Log error silently for diagnostics
❌ ANTI-PATTERNS (3)
Failure ignored or silent
β€˜Something went wrong’ with no help
Retry button hidden or missing
πŸ’» CODE HINTS (1)
catch (err) => showError('Upload failed', retry)
πŸ§ͺ VALIDATION
Trigger sync and async actions, verify loading, success, and error states. Test with keyboard, screen reader, and motion-disabled mode.
#318Data Density Modes Matrix6 cells18 rules18 anti6 hints
Define toggles and layout considerations for switching between dense and spacious modes in data-heavy UIs (e.g. tables, forms), balancing readability, screen real estate, and interaction speed.
density_mode_typetoggle_mechanismlayout_scaling_rulesuser_preference_persistencecomponent_compatibilityaccessibility_review
DENSITY_TOGGLE_CONTROL
When user needs to switch between compact and relaxed layout
βœ… RULES (3)
Provide visible toggle (icon, switch, dropdown)
Label modes clearly (e.g. β€˜Compact’, β€˜Comfort’)
Avoid jargon (β€˜normal’, β€˜legacy’, etc.)
❌ ANTI-PATTERNS (3)
No toggle for dense layout
Toggle hidden in obscure menu
Unclear mode names
πŸ’» CODE HINTS (1)
<Toggle label='Density' options={['Compact', 'Comfort']} />
LAYOUT_TOKEN_SCALING
When adapting spacing systemically
βœ… RULES (3)
Scale tokens (spacing, font, line) by mode
Avoid hardcoded px values
Apply density theme at layout root
❌ ANTI-PATTERNS (3)
Manually overriding per component
Inconsistent paddings across table rows
No change to font/line height
πŸ’» CODE HINTS (1)
theme.spacing.row = density === 'compact' ? 4 : 12
REMEMBER_USER_DENSITY_CHOICE
When user revisits UI or device
βœ… RULES (3)
Store in localStorage or profile
Sync across tabs or devices if possible
Default to system or app standard if unset
❌ ANTI-PATTERNS (3)
Reset to default on every load
No persistence mechanism
Only remembered in memory
πŸ’» CODE HINTS (1)
localStorage.setItem('density', mode)
COMPONENT_OPT_IN_SUPPORT
When customizing dense mode per widget
βœ… RULES (3)
Use density-aware styles or tokens
Test layout for each density
Avoid breakage when mode changes dynamically
❌ ANTI-PATTERNS (3)
Hardcoded dimensions
Widgets unaware of mode context
Only some components support density
πŸ’» CODE HINTS (1)
componentProps.spacing = density === 'compact' ? 'xs' : 'md'
DENSITY_AND_A11Y_AUDIT
When testing compact layouts for usability
βœ… RULES (3)
Check for 44x44 tap targets
Validate keyboard spacing and tab order
Respect prefers-reduced-motion if toggled
❌ ANTI-PATTERNS (3)
Tiny buttons in compact mode
Unreachable controls
Motion overuse in dense layout
πŸ’» CODE HINTS (1)
expect(button.offsetWidth).toBeGreaterThan(44)
DENSITY_MODE_TEST_COVERAGE
When running visual regression or layout tests
βœ… RULES (3)
Include tests for all supported modes
Test nested density toggles
Snapshot tables, forms, and navs
❌ ANTI-PATTERNS (3)
Only default mode tested
No tests for edge components
Breakage on nested layout contexts
πŸ’» CODE HINTS (1)
test.each(['compact', 'comfort'])(mode => renderWithDensity(mode))
πŸ§ͺ VALIDATION
Toggle between density modes, inspect layout, touch targets, and component behavior. Run a11y checks and regression tests.
#319UI Personalization Matrix6 cells18 rules18 anti6 hints
Define boundaries, capabilities, and persistence mechanisms for user-driven UI personalization such as layout, themes, data visibility, and feature toggles.
personalization_typepersistence_scopeuser_control_and_resetsecurity_and_privacyconflict_resolutiontesting_and_recovery
THEME_AND_LAYOUT_PREFERENCES
When users choose dark/light mode, density, or panel layout
βœ… RULES (3)
Store in profile or localStorage
Reflect immediately in UI
Respect OS/browser defaults as fallback
❌ ANTI-PATTERNS (3)
No persistence
Theme resets after refresh
Toggle buried in settings menu
πŸ’» CODE HINTS (1)
localStorage.setItem('theme', 'dark')
WIDGET_VISIBILITY_AND_ORDERING
When dashboard widgets can be rearranged or hidden
βœ… RULES (3)
Track widget IDs and sort order
Allow restore to default
Sync across devices if user is logged in
❌ ANTI-PATTERNS (3)
Fixed widget positions
State stored only in DOM
Lost config on logout
πŸ’» CODE HINTS (1)
userPrefs.widgets = ['weather', 'sales', 'inbox']
COLUMN_AND_TABLE_PREFERENCES
When user configures which data columns to show
βœ… RULES (3)
Save visibility, order, and width
Apply across relevant screens
Expose reset or template option
❌ ANTI-PATTERNS (3)
Always show all columns
Customizations apply to wrong screen
Hidden controls to revert layout
πŸ’» CODE HINTS (1)
columns.filter(col => userPrefs.visibleCols.includes(col.id))
PREFERENCE_CONFLICT_RESOLUTION
When server and local config differ
βœ… RULES (3)
Prompt user to choose
Use timestamps or versioning
Support partial merges
❌ ANTI-PATTERNS (3)
Local preferences silently overwritten
Merge fails without notice
No indication of which config applied
πŸ’» CODE HINTS (1)
if (server.ts > local.ts) askUserToResolve()
USER_PRIVACY_AND_DATA_SCOPE
When personalization stores sensitive layout or data
βœ… RULES (3)
Minimize stored sensitive data
Use encryption or secure cookies
Document what is stored and where
❌ ANTI-PATTERNS (3)
Storing PII in localStorage
Hidden server sync without notice
No audit or data wipe option
πŸ’» CODE HINTS (1)
secureStore.save('layoutPrefs', encryptedData)
TEST_RESTORE_AND_DEFAULT_FALLBACK
When users need to reset layout or debug
βœ… RULES (3)
Provide β€˜reset layout’ button
Log fallback events
Expose version of prefs in devtools/logs
❌ ANTI-PATTERNS (3)
No way to reset broken layout
Default applied with no notice
Dev tools unaware of prefs version
πŸ’» CODE HINTS (1)
resetToDefaults(); log('prefs version', prefs.version)
πŸ§ͺ VALIDATION
Customize UI, reload, logout/login, and validate persistence, reset, conflict resolution, and devtools visibility.
#320UI Notifications Matrix6 cells18 rules18 anti6 hints
Define design and behavior patterns for transient and persistent notifications in the UI β€” covering toasts, banners, inbox, escalation, and accessibility.
notification_typedisplay_duration_and_dismissalplacement_and_priorityaccessibility_and_aria_supportpersistence_and_inbox_linkagetesting_and_tracking
TOAST_SUCCESS_INFO
When informing user of non-blocking event
βœ… RULES (3)
Auto-dismiss in <5s
Position bottom-right or top-right
Allow manual close
❌ ANTI-PATTERNS (3)
Toast persists indefinitely
Blocks interaction
Lacks visual distinction by type
πŸ’» CODE HINTS (1)
toast.success('Saved successfully')
ERROR_BANNER_FOR_CRITICAL_FAILURE
When action fails or user needs attention
βœ… RULES (3)
Position at top of container or page
Red color, clear icon and message
Dismiss or auto-fade after action
❌ ANTI-PATTERNS (3)
Silent failure
Hidden banner in scroll
Modal on every error
πŸ’» CODE HINTS (1)
<Alert severity='error'>Upload failed</Alert>
PERSISTENT_NOTIFICATION_IN_INBOX
When message is not time-sensitive or needs audit
βœ… RULES (3)
Add to user’s notification center
Track read/unread state
Support marking and linking
❌ ANTI-PATTERNS (3)
No record after toast disappears
Read status not tracked
Inbox not integrated with UI state
πŸ’» CODE HINTS (1)
notifications.add({ id, type, unread: true })
ARIA_LIVE_AND_A11Y_SUPPORT
When announcing dynamic messages
βœ… RULES (3)
Use role=alert or aria-live=assertive
Ensure off-screen content is focused
Avoid announcement spam
❌ ANTI-PATTERNS (3)
Toast with no aria tag
Repeated announcements flood reader
Critical message not spoken
πŸ’» CODE HINTS (1)
<div role='alert'>Form saved</div>
ESCALATION_RULES_AND_LEVELS
When user ignores or misses multiple alerts
βœ… RULES (3)
Escalate to banner or inbox
Increase prominence on repeat failure
Cap escalation to avoid fatigue
❌ ANTI-PATTERNS (3)
Always modal escalation
Same toast 5x in 10 seconds
User bombarded with identical message
πŸ’» CODE HINTS (1)
escalateIfUnseen(id, level='banner')
NOTIFICATION_EVENT_TEST_AND_LOGGING
When validating delivery and impact
βœ… RULES (3)
Log impressions and closes
Tag user interaction with notification
Test rendering logic in CI
❌ ANTI-PATTERNS (3)
No analytics on notification usage
Failure to test notification logic
Dismiss action not recorded
πŸ’» CODE HINTS (1)
analytics.track('toast_shown', { type: 'success' })
πŸ§ͺ VALIDATION
Trigger all notification types. Test dismiss, aria live, inbox persistence, escalation, analytics, and focus behavior.
#321Embedded Content Matrix6 cells18 rules18 anti7 hints
Define how to safely and efficiently embed external or cross-origin content into an application, addressing communication, sandboxing, sizing, and fallback concerns.
embedding_methodsandbox_policysizing_strategycommunication_channelsecurity_headersfallback_on_failure
IFRAME_SANDBOX_WITH_FALLBACK
When embedding third-party apps or widgets via iframe
βœ… RULES (3)
Use iframe sandbox attributes to limit capabilities
Provide fallback UI on load error or timeout
Log errors for debugging and monitoring
❌ ANTI-PATTERNS (3)
No sandbox set
Silent failure on embed error
Fallback is missing or misleading
πŸ’» CODE HINTS (2)
<iframe sandbox='allow-scripts allow-same-origin'>
onerror=showFallback()
STRICT_ORIGIN_MESSAGE_FILTERING
When using postMessage to communicate with embedded frame
βœ… RULES (3)
Validate origin of all incoming messages
Define and enforce message schema
Use structured cloning or safe parsing
❌ ANTI-PATTERNS (3)
Accepting any origin
Loose schema validation
Parsing raw JSON without checks
πŸ’» CODE HINTS (1)
if (event.origin === 'https://trusted.app') handle(event.data)
RESPONSIVE_IFRAME_SCALING
When iframe content should match host layout
βœ… RULES (3)
Use aspect-ratio or container queries
Enable resize observer from host or child
Apply width/height via CSS not attributes
❌ ANTI-PATTERNS (3)
Fixed pixel height iframe
Manual iframe resizing via JS only
Content clipped inside viewport
πŸ’» CODE HINTS (1)
iframe.style.aspectRatio = '16 / 9'
CSP_AND_XFRAME_PROTECTION
When embedding or being embedded across domains
βœ… RULES (3)
Set Content-Security-Policy headers
Use X-Frame-Options where supported
Avoid inline scripts inside embed
❌ ANTI-PATTERNS (3)
No CSP on embedded source
Framable pages without XFO
Unsafe-eval enabled in CSP
πŸ’» CODE HINTS (1)
Content-Security-Policy: frame-ancestors 'self' https://host.app
LAZY_LOAD_EMBED_ON_VIEW
When embedded content is below the fold or rarely used
βœ… RULES (3)
Use IntersectionObserver to trigger load
Replace placeholder on visibility
Log or track usage patterns
❌ ANTI-PATTERNS (3)
All embeds load on initial page render
No visibility tracking
User sees blank embed on interaction
πŸ’» CODE HINTS (1)
observer.observe(iframePlaceholder)
UNMOUNT_AND_CLEANUP_ON_EXIT
When user navigates away from embed context
βœ… RULES (3)
Remove iframe DOM node on route change
Unsubscribe message listeners
Clear related timers or intervals
❌ ANTI-PATTERNS (3)
Listeners stay active after removal
Iframe remains in DOM but hidden
Global vars persist across embed switches
πŸ’» CODE HINTS (1)
window.removeEventListener('message', handler)
πŸ§ͺ VALIDATION
Embed trusted/untrusted content with fallback, lazy load, secure communication, responsive sizing, and safe teardown. Verify CSP and message origin enforcement.
β–Ό πŸ”­ Matrix Ξ© β€” Observer 1 matrices
#999Omega β€” System Coverage & Gap Detection Matrix6 cells18 rules13 anti6 hints
Monitor the overall health of the Intend Matrix System by detecting missing decision areas, overloaded responsibilities, dead zones, and unresolvable cross-layer links.
detection_scopesignal_sourcethreshold_policyalert_severityrecommendation_typemonitoring_frequency
COVERAGE_GAP_DETECTION
When a user intent activates the system but no matrix exists to cover the decision category
βœ… RULES (3)
Track intent-to-matrix miss frequency
Cluster unmatched intents by category
Trigger alert when unmatched count exceeds threshold
❌ ANTI-PATTERNS (2)
Letting unclassified decisions fall through
Creating catch-all logic instead of new matrices
πŸ’» CODE HINTS (1)
if (unmatchedIntents > threshold) suggestNewMatrix()
REPEATED_HEURISTIC_DETECTION
When the routing system asks the same question repeatedly across sessions
βœ… RULES (3)
Log all Laser/routing clarification prompts
Cluster repeated phrasing patterns
Mark as heuristic hot-spot if β‰₯3 clusters lack coverage
❌ ANTI-PATTERNS (2)
Allowing routing questions to pile up
Assuming questions are temporary workarounds
πŸ’» CODE HINTS (1)
if (questionCluster.count > 3 && !hasMatrix) flagHeuristicGap()
OVERLOADED_MATRIX_DETECTION
When a matrix is triggered in too many unrelated decision flows
βœ… RULES (3)
Track activations by intent category
Flag matrices used across >5 distinct intent clusters
Recommend separation or companion matrix
❌ ANTI-PATTERNS (2)
Letting one matrix answer all related-but-different needs
Expanding single matrix scope indefinitely
πŸ’» CODE HINTS (1)
if (matrix.intentTypes.length > 5) recommendSplit(matrix.id)
DEAD_ZONE_LOCK_DETECTION
When Matrix 0 and anchors produce default configurations due to lack of guidance
βœ… RULES (3)
Track forced/default lock reasons in decision log
Mark intents with >50% fallback use
Correlate to matrix coverage score
❌ ANTI-PATTERNS (2)
Treating fallback logic as equivalent to structured decision
No audit trail for why fallback was used
πŸ’» CODE HINTS (1)
if (lockedDefaults > 0.5) alertDeadZone(intent.id)
CROSS_LAYER_ORPHAN_DETECTION
When matrix cross-references point to non-existent dependencies
βœ… RULES (3)
Validate all cross_layer matrix links
Check that each layer transition has bridging matrix
Alert on unresolvable references
❌ ANTI-PATTERNS (2)
Broken chain from UI β†’ Integration β†’ Data
Orphan matrix with unsatisfied dependency
πŸ’» CODE HINTS (1)
if (!exists(matrix.crossLayer[i])) reportOrphan(matrix.id)
SYSTEM_EVOLUTION_REPORTING
When generating a health snapshot or quarterly matrix roadmap
βœ… RULES (3)
Track coverage ratio per layer
Log gap closure rate over time
Generate next-matrix suggestions by trend heatmap
❌ ANTI-PATTERNS (3)
No visibility into system growth
Matrix additions disconnected from gaps
Manual inventory reconciliation
πŸ’» CODE HINTS (1)
generateCoverageReport(layers).export('omega_q3_summary.json')
πŸ§ͺ VALIDATION
Simulate unmatched intent, repeated routing patterns, and default fallbacks. Confirm Omega logs issue, flags gap type, and recommends new matrix with reference to layer and type.