| name | enterprise-webapp |
| description | Full-stack enterprise web application development guide covering frontend architecture (React, design systems, state management, forms), backend patterns (layered architecture, REST API, validation), async processing, caching (cache-aside, write-through, write-behind), auth/authz (JWT, RBAC/ABAC), security, accessibility (WCAG 2.1 AA), performance, observability, testing strategy, error handling, database patterns, and CI/CD. |
| user-invokable | true |
| args | [{"name":"area","description":"Specific area to focus on — e.g., 'frontend', 'backend', 'auth', 'caching', 'testing' (optional)","required":false}] |
First: Use the frontend-design skill for design principles and anti-patterns.
Scope: Full-stack web application development — frontend, backend, infrastructure, security, and observability.
Mandate: Every deliverable must be production-grade, secure, accessible, observable, and maintainable by a team of engineers without tribal knowledge.
0. Pre-Flight: Research Before Writing
Before writing a single line of code, the agent must:
- Read the codebase — scan existing patterns, naming conventions, folder structure, and active dependencies.
- Check official documentation — never guess an API shape, config key, or library version. Confirm it.
- Identify constraints — auth strategy, DB engine, caching layer, deployment target, existing test suite, CI/CD pipeline.
- Surface ambiguities — ask exactly one clarifying question per unknown rather than making silent assumptions.
- State the plan — before editing files, output a brief numbered implementation plan and wait for acknowledgment if the change set touches more than 3 files.
1. Project Structure & Conventions
1.1 Monorepo Layout
/
├── apps/
│ ├── web/ # Frontend (React/Next.js or Vite+React)
│ └── api/ # Backend (FastAPI / Node / Go)
├── packages/
│ ├── ui/ # Shared component library
│ ├── types/ # Shared TypeScript types / Zod schemas
│ └── utils/ # Pure utility functions, no side effects
├── infra/ # IaC (Terraform / Pulumi / Bicep)
├── .env.example # Committed template — never commit real secrets
└── docker-compose.yml
1.2 Naming Conventions
| Artifact | Convention | Example |
|---|
| React components | PascalCase file + export | UserProfileCard.tsx |
| Hooks | use prefix, camelCase | useAuthSession.ts |
| API route handlers | kebab-case | user-profile.ts |
| DB tables | snake_case, plural | audit_events |
| Env vars | SCREAMING_SNAKE | DATABASE_URL |
| CSS classes (Tailwind) | Utility-first | — |
| Constants | UPPER_SNAKE | MAX_RETRY_ATTEMPTS |
1.3 File Size Discipline
- Components: split when >200 lines.
- Route handlers: split when >80 lines; extract service layer.
- Utility modules: one responsibility per file.
- No barrel re-exports that mask circular dependencies.
2. UI/UX Design Principles
2.1 Design System Foundation
Every UI must be built on a design token layer — never hard-code colors, spacing, or typography values.
export const tokens = {
color: {
primary: { 50: '#eff6ff', 500: '#3b82f6', 900: '#1e3a8a' },
neutral: { 50: '#f8fafc', 500: '#64748b', 950: '#020617' },
danger: { 500: '#ef4444' },
success: { 500: '#22c55e' },
warning: { 500: '#f59e0b' },
},
spacing: { xs: '4px', sm: '8px', md: '16px', lg: '24px', xl: '40px', '2xl': '64px' },
radius: { sm: '4px', md: '8px', lg: '12px', full: '9999px' },
shadow: { sm: '0 1px 2px rgb(0 0 0 / .05)', md: '0 4px 6px rgb(0 0 0 / .07)' },
font: { sans: '"Inter Variable", system-ui, sans-serif', mono: '"JetBrains Mono", monospace' },
motion: { fast: '100ms', normal: '200ms', slow: '350ms', ease: 'cubic-bezier(.4,0,.2,1)' },
} as const;
2.2 Component Architecture
Follow Atomic Design: Atoms → Molecules → Organisms → Templates → Pages.
2.3 Loading States, Empty States & Errors
Every data-driven surface must handle all four states:
| State | Requirement |
|---|
| Loading | Skeleton that mirrors content layout |
| Empty | Contextual illustration + actionable CTA |
| Error | Human-readable message + retry action + error reference code |
| Success | Confirmation feedback inline OR toast |
3. Frontend Development Principles
3.1 State Management Hierarchy
1. useState / useReducer → component-local, transient UI state
2. Context API → low-frequency, cross-tree state (theme, locale)
3. Zustand / Jotai → app-level client state
4. React Query / SWR → server state (cache, sync, background refresh)
5. URL params → shareable, bookmarkable filter/pagination state
Never put server data in Zustand. Server state and client state have different invalidation strategies.
3.2 Data Fetching with React Query
export const userKeys = {
all: () => ['users'] as const,
list: (filters: UserFilters) => [...userKeys.all(), 'list', filters] as const,
detail: (id: string) => [...userKeys.all(), 'detail', id] as const,
};
export function useUsers(filters: UserFilters) {
return useQuery({
queryKey: userKeys.list(filters),
queryFn: () => fetchUsers(filters),
staleTime: 30_000,
gcTime: 5 * 60 * 1000,
retry: (failCount, err) => failCount < 2 && err.status !== 404,
});
}
3.3 Form Handling
Use React Hook Form + Zod — never build manual form state.
3.4 Code Splitting & Bundle Optimization
- Lazy-load heavy routes with
React.lazy() + Suspense.
- Dynamic import heavy third-party libs at call site.
- Never import entire icon libraries — use named imports only.
4. Backend Development Principles
4.1 Layered Architecture
Request → Route/Controller → Service → Repository → Database
- Controllers: parse/validate request, call service, serialize response. No business logic.
- Services: all business logic, orchestration, transaction management. No SQL.
- Repositories: all DB queries. No business logic.
4.2 API Design (REST)
Resource Verb Path Body / Params
──────────────────────────────────────────────────────────
List GET /api/v1/users ?page&limit&sort&filter
Create POST /api/v1/users CreateUserDTO
Get GET /api/v1/users/:id
Update PATCH /api/v1/users/:id Partial<UpdateUserDTO>
Delete DELETE /api/v1/users/:id
Always version APIs (/api/v1/). Consistent error and success envelopes.
4.3 Input Validation
Validate at every trust boundary — never trust client data, never trust inter-service data.
5. Asynchronous Processing
5.1 When to Go Async
Use async when the operation takes longer than 200ms, involves external I/O, is not required for the immediate response, or can fail and be retried.
5.2 Task Queue Architecture
API Handler → Enqueue job → Worker Pool → Process → Result event
5.3 Concurrency Rules
- Never
await inside forEach — use Promise.all or for...of.
- Cap fan-out parallelism with
p-limit or asyncio.Semaphore.
- Never hold a DB transaction open while making external HTTP calls.
6. Caching Patterns
6.1 Pattern Decision Matrix
| Pattern | Use When | Stale Risk | Write Complexity |
|---|
| Cache-Aside | Read-heavy, tolerable staleness | Medium | Low |
| Read-Through | Abstracted cache layer | Low | Low |
| Write-Through | Strong consistency required | Very Low | Medium |
| Write-Behind | High write throughput | Medium | High |
| Write-Around | Large, rarely-re-read data | High | Low |
6.2 Cache Rules of Thumb
- Always set a TTL.
- Use cache stampede protection.
- Never cache PII without encryption at rest.
- Cache keys must include tenant/org ID in multi-tenant systems.
- Instrument cache hit rate — if below 80%, review the strategy.
7. Authentication & Authorization
7.1 Architecture
Access tokens: short-lived (15 minutes). Refresh tokens: httpOnly, Secure, SameSite=Strict cookie — never in localStorage.
7.2 Authorization: RBAC + ABAC
Define role → permission matrix. Implement ownership/org-scoping for ABAC.
7.3 Security Headers (every response)
Strict-Transport-Security, Content-Security-Policy, X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Referrer-Policy, Permissions-Policy.
7.4 API Rate Limiting
Per-user, per-endpoint rate limiting backed by Redis sliding window.
8. Accessibility (WCAG 2.1 AA — Mandatory)
- Color contrast: 4.5:1 text, 3:1 large text / UI components.
- Keyboard navigable — no mouse-only interactions.
- Focus ring visible and not obscured.
- All interactive elements have accessible name.
- Form errors: announced by screen readers.
- Page has
<h1> and logical heading hierarchy.
9. Performance
9.1 Core Web Vitals Targets
| Metric | Target |
|---|
| LCP | < 2.5s |
| INP | < 200ms |
| CLS | < 0.1 |
| TTFB | < 600ms |
9.2 Backend Performance Checklist
- N+1 queries: use DataLoader or explicit joins.
- Cursor-based pagination for large datasets.
- Indexes on every FK and filtered/sorted column.
- Compression: gzip/brotli responses ≥1KB.
10. Observability
10.1 Structured Logging
Use structured JSON logging with redaction of sensitive fields. Always include correlation IDs.
10.2 Distributed Tracing
Every request carries a Trace ID from entry through all downstream services.
10.3 Health Checks
router.get('/health/live', (req, res) => res.json({ status: 'ok' }));
router.get('/health/ready', async (req, res) => {
});
11. Testing Strategy
11.1 Test Pyramid
┌────────────────────┐
│ E2E / Browser │ ← 10%
├────────────────────┤
│ Integration Tests │ ← 20%
├────────────────────┤
│ Unit Tests │ ← 70%
└────────────────────┘
11.2 Coverage Thresholds
Lines: 85%, Functions: 85%, Branches: 75%, Statements: 85%.
12. Error Handling
12.1 Domain Error Classes
Typed error hierarchy: AppError → ValidationError, NotFoundError, ConflictError, ForbiddenError, UnauthorizedError, RateLimitError.
12.2 Global Error Handler
Expected domain errors: log at info. Unexpected errors: log at error, never leak internals.
12.3 Frontend Error Boundaries
Wrap every major route/organism in an ErrorBoundary.
13. Database & Data Layer
13.1 Schema Design Rules
- Every table has:
id UUID, created_at TIMESTAMPTZ, updated_at TIMESTAMPTZ.
- Soft delete via
deleted_at TIMESTAMPTZ.
- All FK constraints at DB level.
13.2 Migration Discipline
- Migrations are additive — never drop or rename in a single deploy.
- Multi-step rename: add new → deploy + backfill → remove old.
- Every migration must be reversible.
14. CI/CD & Deployment
14.1 Pipeline Stages
Quality (lint, typecheck, test, audit, SAST) → Build → Deploy staging → Deploy production.
14.2 Container Security
Multi-stage builds, non-root user, minimal attack surface.
15. Agent Behavior Rules
- Small commits: one logical change per commit.
- No silent assumptions: surface ambiguities before coding.
- Explain non-obvious choices: leave
// NOTE: comments.
- Preserve existing patterns: don't introduce competing patterns.
- Security by default: all new endpoints require auth unless explicitly marked public.
- Test alongside code: unit tests in the same commit as the feature.
- No TODO left behind: open tracked issues instead.
- Accessibility is a feature: broken keyboard nav or ARIA ships a bug.
- Performance is a constraint: degradation requires mitigation.
- Document decisions, not obvious code: comments explain why, not what.
- No console.log in production: all logging through structured logger.
- Exit gracefully: handle SIGTERM, drain in-flight requests.