0% found this document useful (0 votes)
277 views13 pages

Trae Code Quality Guidelines

This document outlines comprehensive coding and design principles across various domains, including frontend, backend, security, performance, and UI design. It emphasizes best practices such as clean code, accessibility, responsive design, and modular architecture while also detailing specific guidelines for different programming languages and frameworks. Additionally, it provides a framework for translating style keywords into consistent design rules, ensuring a cohesive user experience.

Uploaded by

dev.faisee.yt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
277 views13 pages

Trae Code Quality Guidelines

This document outlines comprehensive coding and design principles across various domains, including frontend, backend, security, performance, and UI design. It emphasizes best practices such as clean code, accessibility, responsive design, and modular architecture while also detailing specific guidelines for different programming languages and frameworks. Additionally, it provides a framework for translating style keywords into consistent design rules, ensuring a cohesive user experience.

Uploaded by

dev.faisee.yt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

rules:

# GENERAL UNIVERSAL RULES


- Always write clean, modular, and well-documented code.
- Always follow DRY (Don’t Repeat Yourself), KISS (Keep It Simple, Stupid), and
SOLID principles.
- Always prefer readability and maintainability over cleverness.
- Always include inline comments for tricky logic, no matter the language.
- Always use semantic and descriptive naming for variables, functions, and
classes.
- Never leave unused imports, dead code, or console logs in final output.
# FRONTEND (Websites / Extensions)
- Always prefer **Flexbox** or **CSS Grid** for layout (no inline styles except
when unavoidable).
- Always structure HTML with semantic tags (header, main, footer, section,
article, nav).
- Always ensure accessibility: use alt text, aria labels, proper heading
hierarchy.
- Always ensure mobile-first responsive design (min-width breakpoints).
- Always support both light and dark mode with a theme toggle.
- Always optimize images and media for performance.
- Always minify and bundle assets for production builds.
# BACKEND / GENERAL CODE
- Always validate user input (sanitize + escape where necessary).
- Always handle errors gracefully with try/catch or equivalent.
- Always structure code in modules/files instead of long single files.
- Always use environment variables for secrets (no hardcoding API keys or
tokens).
- Always write functions that do one thing only (single responsibility).
- Always write reusable utility functions for repeated logic.
- Always include logging for debugging (but remove in production).
# JAVASCRIPT / TYPESCRIPT
- Prefer use arrow functions unless a `function` keyword is necessary (like
constructors).
- Always write asynchronous code with async/await (avoid raw `.then()` chaining).
- Always type everything if using TypeScript.
- Always lint with ESLint + Prettier before finalizing.
# PYTHON
- Always follow PEP8 style guide.
- Always use virtual environments for dependencies.
- Always document functions with docstrings.
- Always use list/dict comprehensions when appropriate.
- Never use wildcard imports (`from module import *`).
# SECURITY
- Never expose credentials, tokens, or sensitive data in code.
- Always hash and salt passwords before storing.
- Always validate all external inputs (backend + frontend).
- Always use HTTPS for API calls.
- Always prevent XSS and CSRF attacks in web apps.
# PERFORMANCE
- Always lazy load images, scripts, and components when possible.
- Always debounce or throttle expensive functions (scroll, resize, input).
- Always compress large files and assets before using them.
- Always optimize database queries (indexes, joins).
- Always avoid nested loops when a hash map or set could solve it.
# DOCUMENTATION & TESTING
- Always write [Link] for every project with setup instructions.
- Always document API endpoints if a backend is included.
- Always add at least basic unit tests for critical functions.
- Always write TODO comments for incomplete sections.
- Always include version control best practices (meaningful commit messages,
branching).
# GIT / VERSION CONTROL
- Always use `.gitignore` properly (node_modules, build, env files).
- Always use meaningful commit messages (“Fix login bug” not “stuff”).
- Always commit small, atomic changes (not giant unrelated bundles).
- Always keep `main` or `master` branch stable.
- Always use feature branches for new functionality.
# UNIVERSAL UI PRINCIPLES
- Always design interfaces that are clean, balanced, and visually harmonious.
- Always follow modern UI design principles:
• Generous whitespace
• Clear hierarchy (big bold headers, smaller readable body text)
• Consistent alignment
• Smooth, minimal transitions
- Always ensure accessibility: high-contrast mode, readable fonts, scalable text.
- Always prefer vector graphics (SVG/Canvas) for crisp visuals.
# "BEAUTIFUL / SEXY / MODERN"
- “Beautiful” → Soft gradients, balanced whitespace, smooth corners, subtle
shadows.
- “Sexy” → Dark themes, neon/glow accents, high contrast, futuristic vibes.
- “Modern” → Flat/minimal design, clean typography (e.g., Inter, Roboto,
Poppins), grid layouts.
- “Luxury” → Black/white + gold/silver accents, serif fonts for elegance, high-
res textures.
# STYLE KEYWORDS (PLAIN WORD → DESIGN RULES)
- “Minimal” → White or neutral background, very limited colors (2–3), thin lines,
lots of whitespace.
- “Graffiti” → Bright, clashing colors, spray-paint textures, bold funky fonts,
chaotic layering.
- “3D” → Depth using perspective, lighting, and shadows. Use CSS 3D transforms or
WebGL/[Link].
- “Flat” → No shadows, no gradients, just solid colors and simple shapes.
- “Futuristic” → Neon blue/purple, holographic gradients, glowing borders,
circuit-like layouts.
- “Clean” → Balanced spacing, consistent grid, soft colors, no clutter.
- “Dark Mode” → Black/gray base, muted accent colors, glowing highlights if
needed.
- “Light Mode” → White/soft gray background, pastel or subtle accents, clean
lines.
- “Playful” → Rounded corners, vibrant colors, cartoony fonts, bouncy
transitions.
- “Serious/Corporate” → Neutral palette, thin sans-serif fonts, conservative use
of animation.
# ANIMATIONS & MOTION
- Always use smooth 200–500ms transitions (ease-in-out).
- Always prefer subtle animations: fade, slide, scale — avoid distracting effects
unless explicitly requested.
- “Beautiful” → Use micro-interactions (hover states, button feedback, card
lift).
# TYPOGRAPHY
- Always use a modern sans-serif (Poppins, Inter, Roboto, SF Pro) unless
otherwise specified.
- Use max 2 fonts per project: one for headings, one for body.
- Maintain consistent font scale (H1 > H2 > H3 > Body).
# COLOR SYSTEM
- Always pick a 3-color system: Primary, Secondary, Accent.
- Use color psychology:
• Blue → Trust, calm, tech
• Red → Power, urgency
• Green → Growth, success
• Purple → Luxury, mystery
• Yellow → Energy, creativity
- Always ensure contrast is WCAG compliant.
# LAYOUT
- Always use CSS Grid/Flexbox for layouts.
- Always design mobile-first, responsive scaling up to desktop.
- Always center critical UI elements for balance.
- Always keep navigation consistent across pages/screens.

# EXTENSIONS / DASHBOARD
- Always design lightweight, minimal panels (no clutter).
- Always ensure UI scales in small popups.
- Always use icons with tooltips to save space.
- Always follow platform guidelines (Chrome, Firefox, Edge).
# CORE PRINCIPLE
- When user gives plain style words (like “beautiful”, “sexy”, “luxury”,
“playful”, “graffiti”),
always map them to a consistent set of design rules for colors, layout,
typography, and motion.
- Always apply universal design best practices (responsiveness, accessibility,
performance).
# GENERAL VIB
- "Beautiful" → Soft gradients, subtle shadows, balanced whitespace, harmonious
color palette.
- "Sexy" → Dark base, neon/glow accents, futuristic fonts, sleek animations.
- "Modern" → Flat/minimal design, clean grid, sans-serif fonts, simple color
schemes.
- "Luxury" → Black/white + gold/silver accents, serif headings, high-res images.
- "Minimal" → Neutral colors, lots of whitespace, thin lines, very few UI
elements.
- "Clean" → Balanced grid, pastel or muted palette, predictable navigation,
uncluttered.
- "Playful" → Bright colors, rounded corners, cartoony fonts, fun animations.
- "Serious/Corporate" → Neutral palette, muted colors, sans-serif, conservative
animations.
- "Graffiti" → Bold clashing colors, spray-paint textures, chaotic typography,
layered visuals.
- "Futuristic" → Neon blue/purple, holographic gradients, glowing borders,
digital patterns.
- "Retro" → Pixelated fonts, low-fi colors, CRT effects, skeuomorphic buttons.
- "Cyberpunk" → Dark background, neon accents, glitch effects, condensed fonts.
- "Nature" → Greens, browns, earth tones, organic textures, flowing shapes.
- "Sci-Fi" → Metallic tones, holographic UI, sharp angular lines, futuristic
sound cues.
# COLOR MOOD
- "Dark Mode" → Black/gray base, muted accent colors, subtle shadows.
- "Light Mode" → White/soft gray base, pastel accents, clean icons.
- "Vibrant" → Bold, saturated primary colors with strong contrast.
- "Pastel" → Soft, low-saturation colors, gentle contrast.
- "Muted" → Desaturated, earthy tones, calm atmosphere.
- "Luxury" → Black + gold, or white + silver, high contrast.
- "Energetic" → Red, orange, yellow, fast transitions.
- "Calm" → Blues, greens, soft gradients, slow animations.
# TYPOGRAPH
- "Modern" → Sans-serif (Inter, Roboto, Poppins).
- "Luxury" → Serif (Playfair Display, Georgia).
- "Playful" → Rounded, cartoony fonts (Baloo, Comic Neue).
- "Serious" → Thin sans-serif (Helvetica Neue, Lato).
- "Graffiti" → Handwritten / spray-paint styled fonts.
- "Retro" → Pixel/arcade fonts.
- "Futuristic" → Condensed or geometric sans-serif.
# LAYOUT STYLE
- "Minimal" → Grid/flex with large whitespace, few elements.
- "Clean" → Clear sections, proper hierarchy, semantic structure.
- "Dense" → Lots of content per screen, smaller spacing, info-heavy.
- "Luxury" → Full-screen sections, large images, central alignment.
- "Graffiti" → Overlapping layers, tilted/rotated elements, asymmetry.
- "3D" → Perspective transforms, depth shadows, parallax layers.
# MOTION & INTERACTION
- "Beautiful" → Subtle fades, smooth 200–400ms transitions.
- "Sexy" → Glow effects, hover highlights, smooth scaling.
- "Playful" → Bouncy easing, wobble effects, overshoot animations.
- "Luxury" → Slow fade-ins, elegant slide transitions.
- "Graffiti" → Rough, chaotic motion, spray-like reveals.
- "Futuristic" → Glitch transitions, holographic scanning effects.
- "Retro" → Pixel transitions, CRT flicker, frame skips.
# GAME UI / 2D / 3
- "Beautiful" → Parallax backgrounds, smooth particles, layered depth.
- "Sexy" → HUD with neon glow, animated health bars, sleek menus.
- "Minimal" → Transparent overlays, thin HUD lines, flat icons.
- "Graffiti" → Textured menus, spray effects, bold chaotic art.
- "3D" → Interactive camera-based parallax, object shadows, depth-of-field UI.
- "Retro" → Pixel HUD, chunky menus, old-school arcade feel.
- "Futuristic" → Holographic HUD, neon grid backgrounds, scanning animations.
# EXTENSIONS & DASHBOARD
- Always scale UI for small popup panels.
- "Minimal" → Clean icons, whitespace-heavy, tooltips.
- "Sexy" → Compact, dark, glowing accents.
- "Corporate" → Neutral palette, charts, consistent data tables.
- "Playful" → Rounded icons, colorful highlights, bouncy transitions.
# CORE COMBINATION LOGI
- Always combine adjectives logically:
• "Modern" → Clean, flat, minimalistic base.
• "3D" → Add depth, perspective, parallax, shadows.
• If "Modern" + "3D" → Keep clean structure but add subtle 3D depth (cards,
parallax, glassmorphism).
• If "Minimal" + "3D" → Very few elements, but those elements have
depth/light.
• If "Graffiti" + "3D" → Bold spray textures and fonts mapped onto 3D objects
(walls, cubes).
• If "Retro" + "3D" → Pixel textures but arranged in 3D space (voxel style).
• If "Luxury" + "3D" → Gold/silver metallic textures, elegant shadows, glossy
surfaces.
• If "Playful" + "3D" → Bouncy cartoon shapes, rounded 3D buttons, vibrant
colors.
• If "Futuristic" + "3D" → Neon holographic panels, glowing depth grids,
animated perspective.
# 2D / 3D PRIORIT
- If style includes "2D":
• Flat shapes, vector icons, solid colors.
• Animations = slides, fades, scales only.
- If style includes "3D":
• Depth (z-index), lighting, shadows, perspective transforms.
• Support for WebGL / [Link] / Godot nodes where applicable.
• Interactive parallax based on cursor/camera.
- If both "2D" + "3D" are present:
• Keep core flat style but enhance key elements with 3D effects.
• Example: Flat background + 3D cards, or 2D typography floating in 3D
parallax layers.
# MODERN +
- "Modern + 2D" → Flat design, neutral colors, responsive grid, sans-serif fonts.
- "Modern + 3D" → Glassmorphism, depth shadows, clean geometric layouts with 3D
highlights.
- "Modern + Minimal" → Very light palette, simple grid, almost no decoration.
# MINIMAL +
- "Minimal + 2D" → Pure flat, 2-color scheme, whitespace heavy.
- "Minimal + 3D" → Few elements but strong depth: floating cards, subtle
perspective.
- "Minimal + Playful" → Few but vibrant, rounded playful objects.
# GRAFFITI +
- "Graffiti + 2D" → Spray-paint textures, chaotic fonts, layered flat images.
- "Graffiti + 3D" → Graffiti mapped on 3D surfaces (walls, cubes, billboards).
- "Graffiti + Modern" → Controlled chaos: graffiti textures inside clean grid
layouts.
# RETRO +
- "Retro + 2D" → Pixel art, flat arcade HUDs.
- "Retro + 3D" → Voxel style, isometric pixel blocks, CRT shaders in 3D space.
- "Retro + Futuristic" → Neon pixel synthwave, cyberpunk arcade.
# LUXURY +
- "Luxury + 2D" → Flat gold/black palette, serif typography.
- "Luxury + 3D" → Metallic textures, glossy reflections, elegant depth.
# FUTURISTIC +
- "Futuristic + 2D" → Neon lines, grid backgrounds, glitch effects.
- "Futuristic + 3D" → Holographic panels, floating UI, glowing parallax.
# UI + Design Principles
- Always separate **UI** from **logic** (never mix rendering with data/logic).
- Layering:
- 3D/WebGL → run in background canvas.
- 2D/game HUD/UI → separate overlay canvas or DOM.
- Never reset scene when updating UI.
- Input:
- Ensure UI clicks/touch don’t interfere with gameplay/controls.
- Escape/back should always exit overlays.
- Responsiveness:
- Mobile-first scaling.
- Safe zones for curved/notched screens.
- Auto-scale HUD in games.

### Visual Feedback


- Every action gives feedback (hover, click, highlight, glow, animation).
- In 3D → clickable objects must highlight/animate slightly.
- UI transitions ≤200ms, GPU-accelerated where possible.

## ⚡ Performance
- Always target **60 FPS minimum**.
- Lazy load heavy assets.
- Batch draw calls and use **Level of Detail (LOD)** for 3D.
- Use caching for repeated computations.
- Never block UI with heavy loops → use workers/async.
- Minimize DOM reflows, batch style changes.

## Security
- Sanitize all user input (no XSS, injection).
- Never expose secrets or tokens in code.
- Always use HTTPS + secure cookies.
- Extensions: request **minimum permissions**.
- Games/apps: sandbox untrusted code.

## ✅ Error Handling
- Wrap risky operations with **try/catch**.
- Fail gracefully (never crash silently).
- Show friendly error messages for users.
- Log technical details silently for devs.

## 📱 Cross-Platform & Responsiveness


- Websites → mobile-first, responsive.
- Games → auto-scale UI/HUD to device resolution.
- Extensions → Chromium + Firefox support.
- Input → keyboard + mouse + touch + gamepad (where possible).
- Provide **fallbacks** if advanced features fail (e.g., 2D fallback if WebGL
fails).

## Maintainability
- Use **modular code** (components, systems).
- Configurable constants, no hardcoding.
- Self-explanatory names, minimal comments (only for complex logic).
- Keep dependencies minimal and updated.

## 🧪 Testing & Debugging


- Test on:
- Low + high-end devices.
- Multiple browsers/platforms.
- Different resolutions/orientations.
- Provide **fallbacks** if APIs fail.
- Add unit tests for critical logic (auth, saving, payments).

## 📊 Productivity & Workflow


- Always generate:
- `[Link]` with project overview.
- `.env` for secrets/config.
- Proper `[Link]` / `[Link]`.
- Automate builds, minify, tree-shake.
- Enable hot reload/live preview for dev.
- Version control with Git (clean commits, ignore build artifacts).

## 🎨 Generative / Creative Systems


- Randomness should be **seeded** for reproducibility.
- Provide sliders/controls for users to tweak generative outputs.
- Optimize large asset generation with workers/async.
## 🧠 Plain Word → Functionality Map
- **Beautiful** → balanced layout, consistent theme, smooth animations.
- **Sexy** → sleek, glowing accents, bold typography, fast transitions.
- **Modern** → responsive, minimalistic, neumorphism/glassmorphism/material design.
- **Smooth** → 60fps, seamless transitions, responsive controls.
- **Stable** → no crashes, state preserved across UI/scene updates.
- **Interactive** → instant feedback, visual/audio/haptic cues.
- **Playable/Usable** → intuitive controls, logical flow, onboarding/tutorial.
- **Fast** → optimized load, caching, async ops.
- **Secure** → no leaks, sanitized inputs, safe storage.
- **Scalable** → architecture allows more features/users without breaking.

## 🔮 Meta-Rules
- Never sacrifice **usability for looks** (beauty + function balanced).
- Always follow **accessibility** (contrast, ARIA roles, keyboard navigation).
- Every project must deliver: **beauty + speed + stability + usability +
security**.==================
# RULES: FLUTTER (ANDROID + WINDOWS DESKTOP)

[UI/UX DESIGN RULES]


- Always use adaptive layouts (LayoutBuilder, MediaQuery).
- Define breakpoints: mobile(<600dp), tablet (600–1024dp), desktop (>1024dp).
- Android → follow Material 3 (Material You), bottom nav, FAB, gestures.
- Windows → use native window menus, resizable windows, keyboard shortcuts, hover
states.
- Always provide both light & dark themes; allow system + manual toggle.
- Use 8dp spacing grid consistently.
- Typography must scale with textScaleFactor; clamp for big screens.
- On desktop → ensure keyboard focus rings, hover states; on mobile → provide
haptic/ripple feedback.
- For 2D/3D rendering, use CustomPaint / Scene with overlays; keep controls outside
the canvas.

[FUNCTIONALITY & ARCHITECTURE RULES]


- Use a single state management approach (BLoC, Riverpod, or Provider).
- Follow separation of concerns: UI ↔ domain ↔ data layers.
- Heavy tasks must run in Isolates or via compute().
- Use WorkManager (Android) or Windows tasks for background jobs.
- Persistence → Hive / SQFlite / ObjectBox; configs → SharedPreferences / Secure
Storage.
- Networking → dio/http with interceptors, retries, backoff.
- Ask permissions only when needed; provide rationale UI.

[PERFORMANCE RULES]
- Target 60 FPS on all devices.
- Use const constructors where possible.
- Optimize rebuilds (ValueListenableBuilder, Consumer).
- Use RepaintBoundary for expensive subtrees.
- Optimize assets (webp, cached_network_image, multiple resolutions).
- Defer heavy tasks; lazy-load noncritical features.

[ACCESSIBILITY & I18N]


- Add semantics to all custom widgets.
- Support dynamic text scaling and high-contrast.
- Provide RTL layout where applicable.
- Use intl/ARB files for localization.

[PACKAGING & DISTRIBUTION]


- Android: build signed AAB/APK, use Play App Signing.
- Windows: package with msix or Inno Setup, sign executables.
- CI/CD must build, sign, and distribute artifacts automatically.

[SECURITY]
- Store secrets only in secure storage (flutter_secure_storage).
- Use HTTPS everywhere; consider cert pinning for sensitive apps.
- Obfuscate release builds (–obfuscate –split-debug-info).
- Enable Windows crash reporting.

[TESTING]
- Unit tests, widget tests, integration tests required.
- Test lifecycle hooks (pause, resume, background, minimize).
- Test on low-end devices and low-RAM Windows machines.
[CHECKLIST]
- Adaptive responsive layout done
- Platform conventions followed
- State management consistent
- Heavy tasks offloaded
- Assets optimized
- Accessibility & localization added
- Secure storage in use
- Signed builds packaged
- Tests written & CI setuup
# RULES: ELECTRON (WINDOWS DESKTOP)

[APP ARCHITECTURE]
- Keep main process minimal (window lifecycle, menus, auto-updates).
- Renderer handles UI; sandboxed with nodeIntegration disabled.
- Use preload scripts with [Link]() for APIs.
- Validate all IPC input at main process.

[SECURITY RULES]
- contextIsolation: true, nodeIntegration: false.
- Whitelist IPC channels only; reject unknown ones.
- Strict Content Security Policy in renderer.
- Disable webview unless sandboxed.
- Keep dependencies updated, audit regularly.

[UI/UX DESIGN RULES]


- Provide native-feeling window (custom titlebar with minimize/max/close).
- Support Windows DPI scaling and multiple resolutions.
- Use Fluent UI or style to match Windows conventions.
- Provide system tray icon + context menu if app runs in background.
- Support keyboard shortcuts and accelerators.
- Add splash/loading screen on startup.

[FUNCTIONALITY RULES]
- Single instance lock enabled.
- Use native dialogs ([Link] etc).
- Notifications → Windows Action Center compatible.
- Heavy tasks offloaded to worker threads/child processes.
- Use BrowserView for embedded web instead of webview if possible.

[PERFORMANCE]
- Lazy load heavy modules.
- Avoid blocking main thread; keep it responsive.
- Minimize memory use; close unused windows.
- Use GPU-accelerated transforms for animations.

[PACKAGING & UPDATING]


- Build with electron-builder/forge.
- Package as NSIS, MSI, or MSIX.
- Sign executables & installers with EV cert.
- Implement autoUpdater with signed updates & rollback.

[SECURITY HARDENING]
- Never expose [Link] to renderer.
- Use [Link]() for jump lists/notifications.
- sandbox: true for BrowserWindows when possible.
- Regular security scans (npm audit, SAST).
[ACCESSIBILITY & I18N]
- Ensure keyboard navigation and focus rings.
- Test with Narrator & high-contrast mode.
- Localize UI strings, support RTL layouts.

[TESTING]
- Unit tests for renderer logic.
- Integration tests using Spectron/Playwright.
- Crash handling for renderer with safe restart.

[CHECKLIST]
- contextIsolation + preload enforced
- IPC channels validated
- CSP set & secure
- Auto-updater with signed builds
- Code signing certificate applied
- Single-instance behavior enabled
- Accessibility checked
- Worker threads for heavy task==================
# RULES: NATURAL LANGUAGE UNDERSTANDING

[DESIGN LANGUAGE MAP]

[INTERACTION LANGUAGE MAP]


- "smooth" → 60fps animations, GPU acceleration, transitions <200ms, easing
functions (easeInOut, cubic).
- "snappy" → instant response, low input latency, feedback within 100ms.
- "responsive" → works across devices, auto-resizes, touch-friendly targets ≥48dp.
- "consistent" → reusable components, same button styles, same animation speeds,
typography scale system.

[FUNCTIONALITY LANGUAGE MAP]


- "fast" → optimized loops, async operations, caching, minimal load times (<2s web,
<3s app).
- "stable" → error handling everywhere, never crash, state preserved between UI
reloads.
- "secure" → sanitize inputs, encrypt storage, use HTTPS/SSL/TLS, minimal
permissions.
- "scalable" → modular architecture, config-driven, reusable components, supports
future growth.
- "lightweight" → low RAM usage, minimal dependencies, fast startup.
- "powerful" → rich feature set, automation, shortcuts, customization options.

[USER LANGUAGE TO ACTIONS]


- If client says "I want it simple" → minimal UI, one clear call-to-action, clean
typography.
- If client says "make it professional" → neutral palette, grid layouts, formal
fonts, no excessive animations.
- If client says "make it futuristic" → glassmorphism, neon cyberpunk accents, 3D
backgrounds, glowing icons.
- If client says "make it fun" → vibrant colors, playful animations, sound
feedback, gamified UI.
- If client says "make it corporate" → muted palette, structured grids, data
visualization, minimal motion.

[UNIVERSAL META-RULES]
- Always interpret vague terms ("beautiful", "cool", "modern") as combinations of
design, functionality, and responsiveness rules above.
- Never generate plain/unstructured layouts when user uses aesthetic words — always
map to concrete style guides.
- Always combine with accessibility (contrast ratio, ARIA, keyboard navigation).
- Always balance form and function (never beauty-only or utility-only).

#
### "3D"
- Use [Link] / Babylon / WebGL / WebGPU in-browser; for native games use Godot.
- Keep 3D in separate render layer (canvas or WebGL view). UI overlays must be DOM
or separate UI canvas.
- LOD: implement at least 3 LOD levels. Default to low LOD on mobile/low GPU.
- Textures: power-of-two, compressed (KTX2/ETC2/ASTC), max 2048px for hero models;
512–1024 for secondary.
- Drawcalls target: <100 on mid hardware; <30 ideal.
- Provide "Disable 3D" toggle and static fallback image.

### "2D"
- Use SVG or Canvas 2D; vector-first for scalability.
- For pixel art, maintain integer scaling; avoid smoothing.
- Animations: sprite atlases or CSS transforms.

## COLOR & ACCESSIBILITY RULES


- Always check WCAG AA contrast minimum: 4.5:1 for normal text, 3:1 for large.
- Provide semantic color tokens: `--color-primary`, `--color-on-primary`, `--color-
bg`, etc.
- Do not use color alone to convey meaning (add text/icons).
- Provide focus styles: visible 3–4px outline or focus ring.

## UI + 3D / Canvas INTEGRATION RULES (critical)


- Run WebGL/Canvas in its own layer (a canvas element) with `pointer-events`
toggled appropriately.
- Always render UI in a DOM overlay or ui-canvas above scene. UI updates must not
recreate the scene.
- Avoid reinitializing WebGL context on UI changes. Use state diffing to update
objects.
- Do heavy model processing (decoding, mesh import) in a Worker / background
thread. Post message final assets.
- Use OffscreenCanvas for heavy draws when supported.
- Keep event routing clear: UI elements capture events first; pass others to scene.

## FUNCTIONALITY KEYWORDS → EXACT IMPLEMENTATION RULES


### "Fast" / "Optimized"
- Network: use CDN + `Cache-Control` + `stale-while-revalidate`. Use `prefetch` and
`preconnect` for critical resources.
- Code: tree-shake, minify, use ES modules, split vendor bundles, lazy-load
routes/components.
- Images: WebP/AVIF, `srcset`, `sizes`, `loading="lazy"` for non-hero images.
DB: paginate large lists, use indexes, avoid N+1 queries.
- Client: use memoization, debounce (200–300ms) for expensive inputs.

### "Secure" / "Privacy"


- Always use HTTPS/TLS. HSTS recommended on server.
- Sanitize all inPut server & client side. Use parameterized queries or ORM.
- CSP: set strict Content-Security-Policy with nonces where needed.
- Auth: prefer OAuth2.0 / OIDC or JWT with short expirations + refresh tokens and
rotate refresh tokens on reuse.
- Secrets: never commit. Store in secret manager (Vault/GCP Secret Manager/Azure
KeyVault). For local dev, `.env` + `.[Link]`.
- Extensions: request minimal permissions; explain why each is needed in settings;
use `declarativeNetRequest` for Chrome MV3 where possible.
- Telemetry: opt-in by default. Hash/anonymize IDs.

### "Stable" / "Robust"


- Circuit-breaker pattern for flaky dependencies.
- Retry with exponential backoff for transient network ops (max 3 retries, jitter).
- Use health checks, rate-limiting, and graceful degradation.
- Data migrations: use versioned migrations and safe rollback.

### "Offline" / "Work Offline"


- Use service workers (web) and IndexedDB/local storage for data caching and
queueing offline actions.
- Provide clear offline UX indicators.
- Implement conflict resolution strategies (last-write-wins or merge UI).

### "Scalable"
- Horizontal scale: stateless APIs behind load balancers, share storage (S3, Cloud
Storage).
- Use queues (e.g., RabbitMQ, SQS) for long tasks. Use autoscaling rules for worker
pools.
- Monitor scaling metrics and auto-scale.

### "Reproducible / Deterministic"


- Seed all randomness in generative tasks and expose seed in UI.
- For generative models: store model version + prompt + seed + params with outputs.

### "Realtime" / "Streaming"


- Use WebSockets / WebRTC / Server-Sent Events for low-latency updates.
- Use chunked uploads/streaming for large content.

---

## DATA & ASSET RULES


- Compression: gzip/brotli for text; compressed texture formats for 3D.
- Image sizes: hero ≤ 1200–2000 px, thumbnails ≤ 400 px; mobile versions scaled
down.
- Audio: use streaming for long audio; normalize levels; provide mute controls.
- Font loading: use `font-display: swap` and preload critical fonts.

---

## UX & BEHAVIOR RULES (noob → dev specifics)


- “Make it easy”: 3-step max for primary flows. Primary CTA visible above the fold.
- “Don’t lose my data”: autosave drafts every 5–30s depending on action. Confirm
before destructive actions.
- “Make it secure”: require re-auth for sensitive ops (change password, close
account).
- “Make it fast”: show skeleton loaders or progressive UI; never show blank
screens.

---

## TESTING RULES
- Unit tests: cover >70% critical logic. Use mocks for external APIs.
- Integration tests: critical user flows (signup, purchase, save) end-to-end.
- Performance tests: Lighthouse budget for web (Time-to-Interactive < 3s, LCP < 2s
if possible).
- Visual regression: run Percy/Chromatic or Playwright snapshots.
- Game tests: automation for common input flows and performance on low-end devices.
---

## DEVOPS / CI / RELEASE RULES


- PR checks: lint, unit tests, build, security scan (Snyk/npm audit), license
check.
- Deploy pipeline: build → test → staging → canary → prod with rollback.
- Use feature flags for risky releases. Canary <5% before full rollout.
- Versioning: semantic versioning for public packages; keep changelog.

---

## TELEMETRY / OBSERVABILITY
- Logs: structured JSON with trace IDs. Do not log personal data.
- Metrics: request latency, error rates, CPU, memory; set alerts for SLO breaches.
- Crash reporting: Sentry/Crashlytics with opt-in telemetry.

---

## DOCUMENTATION & HANDOVER


- Provide README with local dev steps, env variables, build steps, and run
commands.
- Provide API docs (OpenAPI/GraphQL schema) and sample requests.
- Provide simple architecture diagram and data flow for major features.

---

## COMBINATION PRIORITY RULES (how to merge multiple adjectives)


1. **Security & Accessibility** override visual choices always.
2. **Stability & Performance** outrank decorative complexity (e.g., heavy 3D).
3. For `A + B` combos:
- If A=“Minimal” and B=“3D” → minimal UI + small, focused 3D hero with toggle.
- If A=“Luxury” and B=“Minimal” → white space + premium serif + subtle gold
accents.
- If A=“Graffiti” + B=“Corporate” → create controlled graffiti areas (hero only)
while keeping corporate grid and readable typography.

# 🧠 Universal AI Agent Continuity & Stability Rules

## 📌 Code Preservation
- Never **delete or overwrite** existing working code unless the user explicitly
says so.
- Always **add new functionality incrementally** instead of replacing everything.
- When asked for changes → **modify only the required part** of the code, keep the
rest intact.
- Keep backups of the last stable version (auto-generate
`backup_code_<timestamp>.txt` before major edits).
- For large edits → show a "diff" (before vs after) so user sees what changed.

## 🔄 Memory & Context


- Always **remember past choices in this project session**:
- UI style (dark, minimal, graffiti, modern, etc.).
- Functionality patterns (modular, async, DRY, etc.).
- Preferred libraries, frameworks, or coding style.
- If switching tasks → keep project memory but start a new context for the new
request.
- Never “forget” previously established rules unless the user resets the project.

## ⚙️ Adaptation & Switching


- If asked to make something **different** (e.g., new page, feature, or system) →
**add it separately** instead of replacing old work.
- Support **multi-style coexistence**: one project can have a minimal dashboard, a
graffiti landing page, and a modern shop.
- Clearly label modules/components so styles and functions don’t clash.
- Always check: “Do you want this as a new feature/module or modify the old one?”

## Stability Rules
- Always verify code before output:
- No broken imports, missing dependencies, or unfinished functions.
- Ensure UI doesn’t disappear because of overwriting root elements.
- Never output “placeholder toy code” (like just 10 lines) for serious
functionality.
- If the task is vague, **ask clarifying questions first** instead of wiping code.

## Project Structure
- Always maintain a clean, scalable structure:
- `src/` for code
- `assets/` for images/models
- `styles/` for CSS or themes
- `components/` for reusable UI
- Organize by features (not just by type) to avoid chaos.
- Preserve directory structure when generating new files.

## 🔐 User Intent Safeguards


- If the user says vague words like “make it better”:
- **Never replace** → always enhance based on stored rules (UI + functionality
sets).
- If uncertain → ask: “Do you want me to refine or rebuild?”
- If asked to “start new” → create a new project folder, don’t overwrite the old
one.

## 🧪 Testing & Regression


- After changes, check if:
- Old features still work (no regressions).
- New code integrates without breaking.
- Provide a quick **test/demo code snippet** so the user can verify instantly.

## 🧠 Plain Word → Stability Map


- **Keep** → preserve all old code, add new only.
- **Change** → only touch the specific module requested.
- **New** → create a fresh file/component without removing anything.
- **Better** → enhance based on stored rules (UI + functionality).
- **Different** → separate module with new rules, don’t overwrite old.
- **Reset** → allowed only if user confirms full wipe.
nEVER FAKE COMPLETION OF TASKS OR PROVIUDE ANY CRASHING Fake unworking nontested
code always complete all the given tasks completely and proeprly to give desired
output
if given and refernece to a site or clone of a project from the web always use
playwright to get the work done with assitace apply patch

You might also like