{"id":"aa8c750f-9c4b-494e-80ab-7798c0ffceca","entityType":"agent","slug":"clawhub-azeem-akram-claw-fullstack-developer","name":"FullStack Developer","canonicalUrl":"https://www.xpersona.co/agent/clawhub-azeem-akram-claw-fullstack-developer","canonicalPath":"/agent/clawhub-azeem-akram-claw-fullstack-developer","generatedAt":"2026-10-11T17:41:15.927Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-11T15:14:39.526Z","emptyReason":null},"description":"Acts as a complete full-stack software developer that designs and builds production applications end-to-end by following the Software Development Lifecycle (... Skill: FullStack Developer Owner: azeem-akram Summary: Acts as a complete full-stack software developer that designs and builds production applications end-to-end by following the Software Development Lifecycle (... Tags: latest:1.0.0 Version history: v1.0.0 | 2026-04-22T21:15:42.312Z | user Initial release of \"Fullstack Developer\" skill for end-to-end application builds. - Provides a comprehensive, step-by-step SDLC","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1K downloads reported by the source. Last updated 10/11/2026.","installCommand":"clawhub skill install s170rp89vvq9zv6gs31yek51n985apbg:claw-fullstack-developer","sourceUrl":"https://clawhub.ai/azeem-akram/claw-fullstack-developer","homepage":"https://clawhub.ai/azeem-akram/skills/claw-fullstack-developer","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/azeem-akram/claw-fullstack-developer","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/azeem-akram/skills/claw-fullstack-developer","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":60,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Acts as a complete full-stack software developer that designs and builds production applications end-to-end by following the Software Development Lifecycle (..."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-11T15:14:39.526Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T15:14:39.526Z","emptyReason":null},"stars":null,"forks":null,"downloads":1042,"packageName":null,"latestVersion":"1.0.0","tractionLabel":"1K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T15:14:39.506Z","emptyReason":null},"lastUpdatedAt":"2026-10-11T15:14:39.526Z","lastCrawledAt":"2026-10-11T15:14:39.506Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-12T15:14:39.506Z","lastVerifiedAt":null,"highlights":[{"version":"1.0.0","createdAt":"2026-04-22T21:15:42.312Z","changelog":"Initial release of \"Fullstack Developer\" skill for end-to-end application builds. - Provides a comprehensive, step-by-step SDLC workflow for all full-stack app requests, from requirements to deployment and maintenance. - Handles frontend, backend, database, API, authentication, testing, CI/CD, security, observability, and deployment decisions. - Promotes building in vertical slices, proven tech choices, security-first implementation, and runnable code at every phase. - Responds to vague or detailed project requests, asking clarifying questions and summarizing requirements before coding. - Defines clear checklists and best practices for each software development phase, ensuring reliability and maintainability.","fileCount":13,"zipByteSize":52675}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s170rp89vvq9zv6gs31yek51n985apbg:claw-fullstack-developer","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-azeem-akram-claw-fullstack-developer/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-azeem-akram-claw-fullstack-developer/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-azeem-akram-claw-fullstack-developer/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-azeem-akram-claw-fullstack-developer/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-azeem-akram-claw-fullstack-developer/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-azeem-akram-claw-fullstack-developer/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-11T17:41:15.924Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-azeem-akram-claw-fullstack-developer/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-azeem-akram-claw-fullstack-developer/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-azeem-akram-claw-fullstack-developer/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-azeem-akram-claw-fullstack-developer/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-11T15:14:39.526Z","emptyReason":null},"readme":"Skill: FullStack Developer\n\nOwner: azeem-akram\n\nSummary: Acts as a complete full-stack software developer that designs and builds production applications end-to-end by following the Software Development Lifecycle (...\n\nTags: latest:1.0.0\n\nVersion history:\n\nv1.0.0 | 2026-04-22T21:15:42.312Z | user\n\nInitial release of \"Fullstack Developer\" skill for end-to-end application builds.\n\n- Provides a comprehensive, step-by-step SDLC workflow for all full-stack app requests, from requirements to deployment and maintenance.\n- Handles frontend, backend, database, API, authentication, testing, CI/CD, security, observability, and deployment decisions.\n- Promotes building in vertical slices, proven tech choices, security-first implementation, and runnable code at every phase.\n- Responds to vague or detailed project requests, asking clarifying questions and summarizing requirements before coding.\n- Defines clear checklists and best practices for each software development phase, ensuring reliability and maintainability.\n\nArchive index:\n\nArchive v1.0.0: 13 files, 52675 bytes\n\nFiles: references/api-design.md (9286b), references/authentication.md (9193b), references/backend-stacks.md (9110b), references/database-design.md (9170b), references/deployment-cicd.md (11585b), references/frontend-stacks.md (6851b), references/observability.md (9616b), references/sdlc-phases.md (7375b), references/security-checklist.md (9383b), references/testing-strategies.md (10402b), skill-card.md (2590b), SKILL.md (11390b), _meta.json (143b)\n\nFile v1.0.0:SKILL.md\n\n---\nname: fullstack-developer\ndescription: Acts as a complete full-stack software developer that designs and builds production applications end-to-end by following the Software Development Lifecycle (SDLC). Use this skill whenever the user asks to build, scaffold, or design an application, website, SaaS product, CRUD app, dashboard, API service, multi-tier system, or anything that spans frontend + backend + database — even if they don't explicitly say \"full-stack.\" Also trigger for requests like \"build me an app that does X,\" \"create a website for Y,\" \"I need a tool that lets users Z,\" \"turn this idea into working code,\" or any scope that requires coordinated frontend, backend, data, and deployment decisions. Covers React/Next.js/Vue/Svelte, Node/Python/Go/Rust backends, SQL/NoSQL databases, REST/GraphQL APIs, authentication, Docker, CI/CD, cloud deployment, testing, security, and observability.\n---\n\n# Full-Stack Developer\n\nYou are acting as an experienced full-stack engineer. Your job is to take a user's idea — whether a vague sentence or a detailed spec — and move it through the Software Development Lifecycle into a working, deployable application. This skill defines **how** you operate, not just **what** to build.\n\n## Core operating principles\n\n1. **Don't skip the lifecycle.** Jumping straight to code on a non-trivial app produces rework. Even a five-minute requirements pass saves hours of refactoring. Scale the rigor to the size of the project — a weekend prototype doesn't need a formal architecture doc, but it does need at least one sentence about what it must do and who uses it.\n2. **Work in vertical slices.** Build one thin end-to-end path (e.g., a single feature from UI → API → DB → deploy) before broadening. This surfaces integration problems early and gives the user something runnable at every step.\n3. **Pick boring, proven tools by default.** Novel stacks are liabilities for most apps. Deviate only when the user asks, or when the problem genuinely demands it.\n4. **Make the app runnable locally before anything else.** A README with `npm install && npm run dev` (or equivalent) that actually works is worth more than 1000 lines of unused code.\n5. **Security, testing, and observability are not \"later\" tasks.** Wire them in during implementation — bolting them on afterward is how real vulnerabilities ship.\n\n## The SDLC workflow you follow\n\nFor every non-trivial build request, move through these seven phases in order. You may compress phases (a small project might do Requirements + Planning + Design in one short response), but never skip the thinking behind them.\n\n### Phase 1 — Requirements Analysis\n\nBefore writing any code, answer:\n- **Who are the users?** (end users, internal team, public, yourself)\n- **What must the app do?** (3–7 bullet functional requirements)\n- **What must it NOT do?** (explicit non-goals prevent scope creep)\n- **Non-functional requirements**: expected traffic, latency, data volume, compliance (GDPR, HIPAA, PCI), offline support, SEO, accessibility\n- **Success criteria**: how will we know it works?\n\nIf the user's request is vague (\"build me a productivity app\"), ask 3–5 sharp clarifying questions before proceeding. If it's concrete enough, restate the requirements back to the user in 4–8 bullets so they can catch misunderstandings cheaply. Read `references/sdlc-phases.md` for the full checklist.\n\n### Phase 2 — Planning\n\nTranslate requirements into a concrete plan:\n- **Scope**: MVP vs. full build. Cut ruthlessly for MVP.\n- **Milestones**: vertical slices, each independently demoable.\n- **Risks**: what could go wrong (third-party APIs, performance, auth complexity)\n- **Tech stack decision**: pick the stack here, justify in one line per choice. See `references/frontend-stacks.md` and `references/backend-stacks.md` for selection guidance.\n\nOutput a short plan (not a Gantt chart — a list of slices in build order).\n\n### Phase 3 — Design & Architecture\n\nSketch the system before coding:\n- **Data model**: entities, relationships, key fields. If SQL, draft the schema. If NoSQL, draft document shapes and access patterns.\n- **API surface**: endpoints (REST) or schema (GraphQL) with inputs/outputs. See `references/api-design.md`.\n- **Component tree** (frontend): pages, shared components, state boundaries\n- **Auth model**: who logs in, via what (password, OAuth, magic link), what they can see. See `references/authentication.md`.\n- **Deployment target**: Vercel, AWS, Fly, Railway, self-hosted. Pick now — it affects code choices.\n- **Directory layout**: show the tree before creating files.\n\nFor non-trivial systems, draft an ASCII diagram of the request flow (client → CDN → API → DB → external services). Seeing data flow prevents architecture mistakes that are painful to unwind later.\n\n### Phase 4 — Implementation\n\nBuild in this order, as a vertical slice per feature:\n1. **Database schema + migrations** (source of truth first)\n2. **Backend API** (the contract the frontend depends on)\n3. **Frontend UI** (consume the API)\n4. **Integration glue** (auth, file upload, payments, email)\n5. **Wire up observability** (logs, error tracking) from the first real endpoint — not after launch\n\nImplementation guidelines:\n- Check in working code at each slice boundary, not at the end.\n- Use environment variables for all secrets; never commit `.env`. Commit `.env.example`.\n- Write `README.md` as you go — setup, env vars, how to run.\n- Use TypeScript for JS projects unless the user objects; the long-term cost of untyped JS on a full app is too high.\n- Keep controllers/routes thin, push logic into services, keep data access in repositories/models. This matters less for a 200-line app and a lot for a 20,000-line app.\n\nSee `references/frontend-stacks.md`, `references/backend-stacks.md`, and `references/database-design.md` for stack-specific patterns.\n\n### Phase 5 — Testing\n\nApply the testing pyramid — lots of fast unit tests, fewer integration tests, a handful of end-to-end tests. See `references/testing-strategies.md`.\n\nAt minimum for any app going beyond \"local prototype\":\n- **Unit tests** on pure business logic (pricing, validation, domain rules)\n- **Integration tests** on API endpoints hitting a real test database\n- **One happy-path E2E test** per critical user flow (signup, checkout, core action)\n- **Type checks and linting** wired into the dev loop\n\nDo not mock things you own. Mock at the edges (third-party HTTP, email providers, payment processors). Integration tests that mock your own database pass when your code is broken.\n\n### Phase 6 — Deployment & CI/CD\n\n- Containerize with Docker when the target requires it (most cloud platforms); skip for serverless platforms that handle this (Vercel, Netlify).\n- Set up **CI** that runs on every push: install, lint, typecheck, test, build. If any fails, block merge.\n- Set up **CD** that deploys `main` automatically to staging, and tagged releases (or `main` with approval) to production.\n- Configure **secrets** in the platform's secret store — never in code or plain env files in the repo.\n- Set up **database migrations** that run as part of deploy, not manually.\n\nSee `references/deployment-cicd.md` for platform-specific recipes (Vercel, AWS, Fly.io, Railway, Docker + VPS).\n\n### Phase 7 — Maintenance & Operations\n\nBefore considering the app \"done\":\n- **Observability**: structured logs, error tracking (Sentry or equivalent), uptime monitoring, basic metrics. See `references/observability.md`.\n- **Backups**: automated database backups with a tested restore procedure. An untested backup is not a backup.\n- **Security review**: run through `references/security-checklist.md` — auth, input validation, rate limiting, secrets, dependencies, HTTPS, CORS, CSP.\n- **Runbook**: a short doc for \"how to deploy,\" \"how to roll back,\" \"how to rotate a secret,\" \"what to do if the DB is down.\"\n- **Dependency strategy**: a tool like Dependabot or Renovate, plus a policy for when to upgrade.\n\n## How to choose the stack\n\nDefault recommendations when the user has no preference:\n\n| Concern | Default | When to deviate |\n|---|---|---|\n| Frontend | Next.js (App Router) + TypeScript + Tailwind | Use Vue/Nuxt or SvelteKit if the user prefers; plain React + Vite for SPA-only; server-rendered Django/Rails templates if the team is backend-heavy |\n| Backend | Next.js route handlers (for small apps) or a separate Node/Fastify or Python/FastAPI service (for larger apps) | Go for high-concurrency services; Django/Rails for content-heavy apps with heavy ORM use |\n| Database | PostgreSQL | SQLite for local-first/single-user; MongoDB when the data is genuinely document-shaped; DynamoDB for serverless at scale |\n| ORM/Query | Prisma (Node) or SQLAlchemy (Python) or sqlc (Go) | Raw SQL when performance or precision matters |\n| Auth | Auth.js / Clerk / Supabase Auth | Roll your own only if the user has strong reasons |\n| Hosting | Vercel (Next.js) or Railway/Fly.io (containerized) | AWS when the user is already there or needs specific AWS services |\n| CI/CD | GitHub Actions | GitLab CI / CircleCI when the repo is there |\n| Observability | Sentry + Vercel/platform logs | Datadog / Grafana Cloud for larger deployments |\n\nDon't spend 20 turns debating stack choices with the user. Pick, justify in one line, and move. The user can redirect.\n\n## When to read reference files\n\nRead the relevant reference **before** starting the corresponding phase — not after. Skimming it first prevents you from writing code you'll need to rewrite.\n\n- `references/sdlc-phases.md` — detailed checklist for each SDLC phase\n- `references/frontend-stacks.md` — Next.js / React / Vue / Svelte patterns\n- `references/backend-stacks.md` — Node / Python / Go patterns\n- `references/database-design.md` — schema design, migrations, indexes, SQL vs. NoSQL\n- `references/api-design.md` — REST, GraphQL, versioning, pagination, errors\n- `references/authentication.md` — password, OAuth, JWT, session, roles\n- `references/testing-strategies.md` — pyramid, fixtures, mocking, E2E\n- `references/deployment-cicd.md` — Docker, GitHub Actions, Vercel, AWS, Fly\n- `references/security-checklist.md` — pre-launch security review\n- `references/observability.md` — logs, metrics, traces, alerts\n\n## Output expectations\n\nFor a typical build request, produce:\n1. A short **Requirements & Plan** section (bulleted, not prose-heavy)\n2. A **Design** section with data model + API sketch + directory tree\n3. **Working code** organized by the directory tree you proposed\n4. A **README.md** with setup, run, deploy, and common tasks\n5. A brief **\"What's next\"** list — things deferred for v2, tech debt called out honestly\n\nKeep the prose tight. The user wants a working app, not a textbook. Long explanations belong in comments at the point where a future reader will need them, not in chat.\n\n## A note on scope discipline\n\nWhen the user asks for feature X, deliver feature X. Don't invent feature Y because it \"seemed useful.\" Don't add admin dashboards, multi-tenancy, or i18n unless asked. Every unrequested feature is code the user now owns, tests, and maintains. A small, sharp v1 that does one thing well beats a sprawling v1 that does seven things halfway.\n\nWhen you are unsure whether to include something, mention it in \"What's next\" as a deferred decision instead of building it.\n\nFile v1.0.0:_meta.json\n\n{\n  \"ownerId\": \"kn7a8ekj5emmr1j5yeqpb5f4ys85bg9h\",\n  \"slug\": \"claw-fullstack-developer\",\n  \"version\": \"1.0.0\",\n  \"publishedAt\": 1776892542312\n}\n\nFile v1.0.0:references/api-design.md\n\n# API Design\n\nGuidance for designing REST and GraphQL APIs that age well.\n\n## REST vs. GraphQL — how to choose\n\n**Default to REST.** It's simpler, better-cached, easier to debug, and matches HTTP semantics. Most apps need REST.\n\nPick GraphQL when:\n- Multiple clients (web, iOS, Android) have genuinely different data needs from the same backend\n- The app has deeply nested data and REST endpoints are proliferating into N+M mess\n- A team has strong GraphQL experience already\n\nDon't pick GraphQL for:\n- A public API (the resolver N+1 problem and caching story are hard)\n- A small app with one frontend (overkill — REST is faster to build)\n\ntRPC is a third option for monorepos where frontend and backend share types. It's fantastic for this case — you get end-to-end type safety without the GraphQL overhead.\n\n## REST design\n\n### URL structure\n- Resources are **nouns, plural**: `/users`, `/orders`, not `/getUsers` or `/user`.\n- Use HTTP methods correctly: `GET` (read, idempotent, cacheable), `POST` (create), `PUT` (full replace), `PATCH` (partial update), `DELETE` (remove).\n- Nest when there's a true parent-child: `/orders/{id}/items`. Don't nest three levels deep — `/orgs/{oid}/projects/{pid}/tasks/{tid}` is a maintenance burden. Prefer `/tasks/{tid}` with scope enforced by auth.\n\n### Path patterns\n```\nGET    /users                 # list (with query params for filtering/pagination)\nPOST   /users                 # create\nGET    /users/{id}            # read one\nPATCH  /users/{id}            # partial update\nDELETE /users/{id}            # delete\n\nGET    /users/{id}/orders     # sub-resource list\n```\n\n### Status codes — use them correctly\n- **200** OK — successful read or update with body returned\n- **201** Created — successful creation; include the new resource in the body and a `Location` header\n- **204** No Content — successful operation with no body (e.g., DELETE)\n- **400** Bad Request — malformed request or validation failure\n- **401** Unauthorized — not authenticated\n- **403** Forbidden — authenticated but not allowed\n- **404** Not Found — resource doesn't exist (or authed user can't see it — don't leak existence)\n- **409** Conflict — state conflict (duplicate email, version mismatch)\n- **422** Unprocessable Entity — validation failure (some APIs prefer this over 400)\n- **429** Too Many Requests — rate limited\n- **500** Internal Server Error — server bug (log it, page oncall)\n- **503** Service Unavailable — temporarily down\n\nDon't return 200 with `{\"error\": \"...\"}`. Use the HTTP status. Clients rely on it for retry logic and error handling.\n\n### Error response shape\nPick one shape and stick to it across every endpoint:\n```json\n{\n  \"error\": {\n    \"code\": \"VALIDATION_FAILED\",\n    \"message\": \"Human-readable message.\",\n    \"details\": [\n      { \"field\": \"email\", \"issue\": \"already_taken\" }\n    ]\n  }\n}\n```\n\nThe `code` is machine-readable (clients switch on it). The `message` is for humans/logs. `details` is optional structured info.\n\n### Pagination\nTwo styles, pick one:\n\n**Cursor-based (recommended)** — handles inserts mid-stream, scales well:\n```\nGET /posts?limit=20&cursor=eyJpZCI6MTIzfQ==\nResponse:\n{\n  \"data\": [...],\n  \"next_cursor\": \"eyJpZCI6MTQzfQ==\",\n  \"has_more\": true\n}\n```\n\n**Offset-based** — simpler, fine for small datasets or stable-ordered results:\n```\nGET /posts?page=2&page_size=20\nResponse:\n{\n  \"data\": [...],\n  \"page\": 2,\n  \"page_size\": 20,\n  \"total\": 847\n}\n```\n\nNever return unbounded lists. A default `limit` (50–100) protects the DB and the client.\n\n### Filtering, sorting, searching\n- Filtering: `?status=active&role=admin`\n- Sorting: `?sort=created_at` (default asc), `?sort=-created_at` (desc). Or separate `sort_by` and `order` params.\n- Searching: `?q=search+terms` for simple search. For complex, a dedicated endpoint (`POST /search`) with a body.\n\n### Versioning\n- **URL version** (`/v1/users`) — most common, easy to understand, easy to route differently.\n- **Header version** (`Accept: application/vnd.company.v1+json`) — cleaner URLs, harder to test.\n\nPick one, document it. Prefer URL versioning for public APIs.\n\nAvoid version proliferation: it's easier to keep v1 stable and add optional fields than to ship v2, v3, v4. Only bump major version for breaking changes.\n\n### Authentication patterns\n- **Bearer tokens** (JWT or opaque): `Authorization: Bearer <token>`\n- **API keys** (machine-to-machine): `Authorization: Bearer <key>` or `X-API-Key: <key>`\n- **Session cookies** (same-site web apps): HTTP-only, Secure, SameSite=Lax\n\nSee `references/authentication.md` for the auth system design.\n\n### Idempotency\nClients retry on network errors. If the user hits \"Pay Now\" and the browser disconnects, the request may or may not have happened. Idempotency keys solve this:\n\n```\nPOST /payments\nIdempotency-Key: user-session-abc-attempt-1\nBody: { amount: 100, ... }\n```\n\nThe server checks: have I seen this key before? If yes, return the stored response. If no, process and store. Stripe, AWS, and other serious APIs all do this.\n\nApply to: payment creation, sending emails, creating external resources, anything costly or visible.\n\n### Rate limiting\nSet limits on every endpoint. Signal them with:\n```\nX-RateLimit-Limit: 100\nX-RateLimit-Remaining: 47\nX-RateLimit-Reset: 1712345678\nRetry-After: 30\n```\n\nReturn 429 when exceeded. Tighter limits on auth endpoints (login, signup, password reset) — these are brute-force targets.\n\n### OpenAPI / docs\nGenerate OpenAPI specs automatically. FastAPI does this for free; Fastify has a plugin; NestJS too. Publish at `/docs` (or `/api-docs`). Up-to-date, auto-generated docs beat a hand-written `API.md` that's out of date.\n\n## GraphQL design\n\n### Schema design\n- **Nodes and edges.** Define clear types; relationships are edges between types.\n- **Keep mutations narrow.** A `createUser` mutation takes user fields, not an omnibus \"doEverything\" input.\n- **Consistent naming.** Types in `PascalCase`, fields in `camelCase`, enums in `SCREAMING_CASE`.\n- **Nullability matters.** Be deliberate — `User.email: String!` (always present) vs `User.phone: String` (optional). Don't make everything non-null by default.\n- **Relay-style connections** for paginated lists: `posts(first: 10, after: \"cursor\"): PostConnection`.\n\n### Resolver pitfalls\n- **N+1 queries.** A naïve resolver fetches the parent list, then per-item fetches children → N+1 DB calls. Use DataLoader to batch and cache.\n- **Depth limits / complexity limits.** Public APIs need these; a malicious client can construct a query that asks for 1M items via deeply nested fields. Use `graphql-depth-limit` and query complexity analysis.\n- **Auth at every resolver,** not just the entry point. A user who can query `user(id)` may still be able to reach `user.privateField` unless the field-level auth says otherwise.\n\n### Tooling\n- **Server**: Apollo Server, GraphQL Yoga, or Pothos (TypeScript-first, code-first).\n- **Client**: Apollo Client, Relay, or urql. Apollo is the most common default.\n- **Codegen**: `graphql-codegen` generates TypeScript types from the schema. Use it.\n\n## tRPC (TypeScript monorepo)\n\nIf both backend and frontend are TypeScript in one repo, tRPC gives you end-to-end type safety with near-zero config:\n\n```ts\n// server\nexport const appRouter = router({\n  getUser: procedure\n    .input(z.object({ id: z.string() }))\n    .query(({ input }) => db.user.findUnique({ where: { id: input.id } })),\n});\nexport type AppRouter = typeof appRouter;\n\n// client\nconst user = await trpc.getUser.query({ id: \"123\" }); // fully typed\n```\n\nUse tRPC when: monorepo, TypeScript, no non-TS clients. Avoid when: public API, mobile clients, polyglot stacks.\n\n## Webhooks\n\nWhen your app needs to notify external systems of events:\n\n- **Sign every payload.** Include a signature header (HMAC-SHA256 of the body with a secret). The receiver verifies it.\n- **Timestamp the payload** and include it in the signature. Reject requests older than 5 minutes to prevent replay.\n- **Retry with exponential backoff** on 5xx / timeout. Give up after a reasonable limit (24h, 48h).\n- **Idempotency**: include an event ID. Receivers dedupe on it.\n- **Endpoint format**: `POST` with JSON body. Respond 2xx fast; queue the actual work.\n\nWhen your app receives webhooks (Stripe, GitHub, etc.):\n- Verify the signature before processing anything.\n- Respond 2xx immediately; do the work async via a job queue.\n- Store events by their ID; dedupe on retries.\n\n## API design — what to avoid\n\n- **RPC-style names in REST**: `/getUserById`, `/deleteOrder`. Use resource URLs + HTTP methods.\n- **Inconsistent response shapes.** If `GET /users` returns `{data: [...]}` but `GET /orders` returns a bare array, clients suffer. Pick a shape; stick to it.\n- **Returning nothing useful on POST.** Creating a resource without returning it forces the client to do a second GET. Return the created object.\n- **Allowing `DELETE` without a 2xx idempotent contract.** A second `DELETE` on a deleted resource should return 204 or 404 — both are fine, just be consistent. Don't return 500.\n- **Unbounded result sets.** Always paginate.\n- **Exposing internal IDs** (database auto-increments) in URLs. Use UUIDs.\n- **Mixing plural/singular.** `/user/{id}` and `/orders`. Pick plural for everything.\n\nFile v1.0.0:references/authentication.md\n\n# Authentication & Authorization\n\nAuth is where apps get compromised. Default to proven libraries and infrastructure; roll your own only when you have to.\n\n## Use a library. Seriously.\n\nBad: writing your own password hashing, session management, or OAuth flow.\nGood: using one of:\n\n| Option | Best for |\n|---|---|\n| **Clerk** | Fastest to ship. Good UI components. Paid after free tier. |\n| **Auth.js (NextAuth)** | Open source, flexible, works with Next.js natively. DIY UI. |\n| **Supabase Auth** | Bundled with Supabase DB. Good if you're already on Supabase. |\n| **Auth0 / Okta** | Enterprise, SSO-heavy, compliance-heavy use cases. |\n| **Lucia** | Lightweight, library-style, good if you want control without reinventing crypto. |\n| **Passport.js** | Node ecosystem standard, lots of strategies. Lower-level. |\n| **FusionAuth / Keycloak** | Self-hosted, full-featured, operationally heavier. |\n\nPick based on constraints:\n- **Hosted or self-hosted?** Hosted (Clerk/Auth0) is faster; self-hosted (Lucia, Keycloak) gives you full control of user data.\n- **Does the user data need to live in your DB?** If yes → Lucia / Auth.js / Supabase. If no → Clerk / Auth0 are fine.\n- **Do you need SSO/SAML for enterprise customers?** Auth0 / WorkOS / Clerk's enterprise tier.\n\n## Authentication flows\n\n### Username + password\nStill the most common. Must include:\n- **Strong password hashing**: argon2id (preferred), or bcrypt with cost factor 12+. Never MD5, SHA-1, SHA-256 alone, or anything custom.\n- **Email verification** before allowing login for sensitive apps.\n- **Password reset**: email-delivered time-limited one-time token. Token expires in 15–60 min, single-use, invalidates on use.\n- **Breach checks**: integrate with Have I Been Pwned API or similar to reject known-breached passwords at signup.\n- **Rate limiting** on login and password reset endpoints.\n\n### OAuth / Social login\n\"Sign in with Google/GitHub/Apple.\" Use a library — the flow has too many security-critical details (PKCE, state, nonce) to get right manually.\n- **Always validate the state parameter** to prevent CSRF.\n- **Use PKCE** for public clients (SPAs, mobile).\n- **Account linking**: decide how you handle a user who signs up with email, then later tries to log in with Google using the same email. (Usually: link automatically if email is verified on both sides, or prompt the user.)\n\n### Magic links (passwordless email)\nEasy to implement, reduces password fatigue. Downsides: dependent on email delivery, no offline access, more friction per login than a saved password.\n- **Tokens are short-lived** (15 min) and single-use.\n- **Rate limit** link requests per email.\n\n### Passkeys / WebAuthn\nThe future of auth. Native support in all modern browsers. Libraries (SimpleWebAuthn, Clerk, Supabase) make this straightforward.\n\n### SSO (SAML, OIDC)\nFor enterprise customers. Use WorkOS, Auth0, or Keycloak. Don't implement SAML from scratch — the spec is a minefield.\n\n### Multi-factor authentication (MFA)\n- **TOTP** (Google Authenticator, Authy) — default choice. Libraries: `otplib`, `pyotp`.\n- **SMS** — avoid as sole factor (SIM-swap vulnerable); OK as a backup.\n- **WebAuthn / security keys** — strongest MFA.\n- **Backup codes** — issue 8–10 one-time codes at MFA enrollment; users will lose their phone.\n\n## Session management\n\nTwo models:\n\n### Session tokens (stateful)\nStore sessions server-side (DB or Redis). Send a random token (stored hashed in DB) as a cookie.\n\nPros: trivial to revoke (delete the row), easy to list active sessions, shorter cookies.\nCons: DB lookup per request (though trivial with Redis/indexed lookup).\n\n**Default to this model** for most web apps.\n\n### JWT (stateless)\nSigned token carries claims. Server verifies signature, reads claims.\n\nPros: no DB lookup per request.\nCons: **can't be revoked** without additional infrastructure. Storing blocklists defeats the \"stateless\" benefit.\n\nUse JWT when:\n- You have multiple services that all need to authenticate users and you don't want a shared session DB\n- Short expiration is acceptable (access tokens: 5–15 min; paired with refresh tokens)\n- The \"can't revoke\" property is acceptable or mitigated\n\n**Don't use JWT for long-lived sessions in a monolith.** The revocation problem is real.\n\n### Cookie settings\nIf using cookies (and you usually should for web):\n- `HttpOnly` — inaccessible to JS, prevents XSS-based theft\n- `Secure` — HTTPS only\n- `SameSite=Lax` (default) or `SameSite=Strict` for higher security\n- `SameSite=None; Secure` only when you truly need cross-site (third-party embed contexts)\n- Short `Max-Age` for session cookies; rotate on privilege changes\n\n### Refresh tokens\nAccess token (short-lived, 5–15 min) + refresh token (long-lived, 30–90 days).\n- Store refresh tokens server-side so you can revoke them.\n- Rotate refresh tokens on use (one-time-use) — detects token theft.\n- On detected reuse, revoke the whole session family.\n\n## Authorization (what the user is allowed to do)\n\nAuthentication proves who. Authorization decides what they can do. They're different concerns — don't conflate them.\n\n### Models by complexity\n\n**Role-based (RBAC)** — users have roles, roles have permissions:\n```\nuser.role = \"admin\" | \"editor\" | \"viewer\"\n```\nSimplest. Fits most B2C and small B2B apps.\n\n**Attribute-based (ABAC)** — permissions depend on attributes of user and resource:\n```\ncan_edit_post(user, post) =\n  user.id == post.author_id\n  OR user.role == \"admin\"\n  OR (user.role == \"editor\" AND post.org_id == user.org_id)\n```\nUse when rules involve relationships between users and specific resources.\n\n**Relationship-based (ReBAC)** — permissions follow graph relationships (Google Docs, GitHub):\n\"Users who have 'editor' on the folder containing this file can edit the file.\"\nTools: OpenFGA, Oso, Permit.io.\n\n### Where to enforce\n**At every layer that handles data:**\n1. **API layer**: reject unauthorized requests with 401/403 before doing any DB work.\n2. **Service layer**: centralize `can_user_do_X(user, resource)` checks. Never scatter role checks across the codebase.\n3. **Data layer**: if using multi-tenant schema, enforce tenant scoping in the repo layer — one forgotten filter = data leak. For Postgres, row-level security (RLS) can be an additional defense.\n\n**Never trust the frontend.** The UI hiding the delete button does not mean the user can't DELETE. Re-check on every mutation.\n\n### Role check pattern\nBad:\n```ts\nif (user.role === 'admin') { ... }   // scattered across 40 files\n```\n\nGood:\n```ts\n// lib/permissions.ts — one place\nexport function canDeletePost(user: User, post: Post): boolean {\n  return user.role === 'admin' || post.authorId === user.id;\n}\n\n// in the service\nif (!canDeletePost(user, post)) throw new ForbiddenError();\n```\n\nWhen the rule changes, you change it in one place.\n\n## Common auth mistakes\n\n- **Storing passwords in plain text or with weak hashing.** Use argon2id or bcrypt. Always.\n- **Leaking user existence** via different error messages (\"no such user\" vs. \"wrong password\"). Use the same message for both.\n- **Sending auth tokens in URL query strings.** They end up in access logs, referrers, browser history. Use headers or body.\n- **No logout.** Actually delete the session server-side on logout, not just the client cookie.\n- **Missing rate limits** on login, signup, password reset. Brute-force central.\n- **JWT with long expiration and no revocation story.** The stolen token works until it expires.\n- **Trusting the `Authorization` header without verifying the signature.** Verify every time — never cache the \"yes, this token is valid\" result across requests unnecessarily.\n- **Using the same secret across environments.** Prod JWT secret must not be the same as staging or dev. Rotate on breach.\n- **Not rotating secrets after an employee leaves** or on suspected compromise.\n- **Giving every authenticated user admin access in dev** \"for convenience,\" then accidentally deploying that flag to prod. Never ship dev shortcuts.\n\n## Session takeover / account recovery — design for the bad day\n\n- **Account recovery flow**: what happens when a user loses access to their email? Have a documented process, even if it's \"contact support.\" Don't invent a recovery mechanism under duress after a real user reports it.\n- **Suspicious activity**: log ips, user-agents, login times. Email the user on first login from a new device/location.\n- **Force logout on password change** (and optionally on role/email change) — invalidate all sessions.\n- **Credential stuffing protection**: monitor for patterns (many logins from one IP, many failures on distinct emails). Integrate a CAPTCHA after N failures.\n\n## Secrets management\n\n- Never commit secrets. `.gitignore` `.env`. Use `.env.example` with placeholder values.\n- In CI/CD: use the platform's secret store (GitHub Actions secrets, Vercel env vars, AWS Secrets Manager).\n- In production: AWS Secrets Manager, GCP Secret Manager, HashiCorp Vault, Doppler, or Infisical. Rotate on a schedule and on any suspected compromise.\n- At boot, validate all required secrets are present — fail fast with a clear error message. Don't silently fall back to a dev default.\n\nFile v1.0.0:references/backend-stacks.md\n\n# Backend Stacks\n\nPatterns and defaults for the major backend runtimes.\n\n## Choosing a backend\n\n| If you need... | Pick |\n|---|---|\n| Fast iteration, same-repo as Next.js, moderate load | **Next.js route handlers / API routes** |\n| Standalone Node service, serious throughput | **Fastify** or **NestJS** |\n| Python ecosystem (ML, data, scientific) | **FastAPI** |\n| Full-featured framework with ORM and admin | **Django** or **Ruby on Rails** |\n| High concurrency, low memory, strict typing | **Go** (stdlib + chi or Gin) |\n| Maximum performance, strong type safety | **Rust** (axum or actix-web) |\n| Real-time / WebSocket-heavy | Node with Socket.IO, or Elixir/Phoenix for truly massive scale |\n\nDefault: **Next.js route handlers** for small/medium apps (frontend + backend in one repo), **Fastify** or **FastAPI** for standalone services.\n\n## Universal backend principles\n\n- **Input validation at the boundary.** Every request body, query param, and path param gets validated before it touches your business logic. Use Zod (Node/TS), Pydantic (Python), or struct tags + validator (Go).\n- **Structured errors.** Return JSON like `{\"error\": {\"code\": \"USER_NOT_FOUND\", \"message\": \"...\"}}`. Never leak stack traces or raw DB errors to clients.\n- **Don't put business logic in the route handler.** Route handler parses input → calls a service function → formats the response. The service is what you unit-test.\n- **Database connection pooling.** Instantiate the pool once; never `new Client()` per request.\n- **Transactions around multi-step writes.** Partial writes cause data corruption nightmares.\n- **Idempotency for destructive or billable operations.** Use idempotency keys on payment creation, emails, etc.\n- **Rate limiting** on auth endpoints at minimum. `express-rate-limit`, `@fastify/rate-limit`, `slowapi` for FastAPI, or a reverse proxy (Cloudflare, nginx).\n- **CORS** configured explicitly. Default-deny, allow specific origins.\n- **Secrets via environment variables**, loaded through a validated config module. The config module crashes the app on missing secrets — no silent fallbacks.\n\n## Node.js — Fastify (recommended for standalone)\n\n### Why Fastify over Express\n- 2–3× faster under load\n- Native schema validation (no extra middleware)\n- Better TypeScript support\n- Plugin-based architecture that scales to large codebases\n- Active maintenance\n\nExpress is fine for legacy reasons but don't start new projects with it in 2026.\n\n### Project structure\n```\nsrc/\n  server.ts              # Fastify instance, register plugins\n  config.ts              # env var validation (Zod)\n  plugins/               # auth, DB, rate limiting\n  modules/\n    users/\n      users.routes.ts    # HTTP layer\n      users.service.ts   # business logic\n      users.repo.ts      # DB access\n      users.schema.ts    # Zod schemas\n      users.test.ts\n    orders/\n      ...\n  lib/\n    db.ts                # Prisma or Drizzle client singleton\n    logger.ts            # pino instance\n```\n\n### Example route (Fastify + Zod + Prisma)\n```ts\n// users.routes.ts\nimport { FastifyPluginAsync } from 'fastify';\nimport { z } from 'zod';\nimport { createUser } from './users.service';\n\nconst CreateUserBody = z.object({\n  email: z.string().email(),\n  name: z.string().min(1).max(100),\n});\n\nexport const usersRoutes: FastifyPluginAsync = async (fastify) => {\n  fastify.post('/users', async (req, reply) => {\n    const body = CreateUserBody.parse(req.body);\n    const user = await createUser(body);\n    return reply.code(201).send(user);\n  });\n};\n```\n\n### Logging\nUse `pino` (comes with Fastify). Log structured JSON. Include request ID, user ID, timing.\n\n## Node.js — NestJS\n\nPick NestJS when:\n- Team has Angular / strong OOP background\n- App is large and benefits from opinionated module structure\n- You want DI out of the box\n\nDon't pick NestJS for a small app — the overhead doesn't pay off until the codebase is large.\n\n## Python — FastAPI (recommended for Python)\n\n### Why FastAPI\n- Async-first, fast under load\n- Pydantic for validation — best-in-class\n- Automatic OpenAPI docs\n- Type hints throughout\n\n### Project structure\n```\napp/\n  main.py                # FastAPI app, router registration\n  config.py              # pydantic-settings\n  db.py                  # SQLAlchemy engine + session\n  deps.py                # FastAPI dependencies (auth, DB session)\n  modules/\n    users/\n      router.py\n      service.py\n      schemas.py         # Pydantic models\n      models.py          # SQLAlchemy models\n      repo.py\n  middleware/\n  tests/\npyproject.toml           # use Poetry or uv\n```\n\n### Example endpoint\n```python\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom pydantic import BaseModel, EmailStr\nfrom sqlalchemy.orm import Session\nfrom .service import create_user\nfrom ..deps import get_db\n\nrouter = APIRouter(prefix=\"/users\", tags=[\"users\"])\n\nclass UserCreate(BaseModel):\n    email: EmailStr\n    name: str\n\n@router.post(\"\", status_code=201)\ndef create(body: UserCreate, db: Session = Depends(get_db)):\n    return create_user(db, body)\n```\n\n### Testing\n`pytest` + `httpx.AsyncClient` for integration tests. Use an in-memory SQLite or a dedicated test Postgres.\n\n## Python — Django\n\nPick Django when:\n- Content-heavy app with lots of CRUD\n- You want an admin interface for free\n- Team is Python-first and already knows Django\n\nDon't pick Django if you need async performance or the app is primarily an API — FastAPI is a better fit.\n\n## Go\n\n### Why Go\n- Best-in-class concurrency (goroutines)\n- Low memory footprint\n- Fast compile, fast startup\n- Great for services that scale horizontally\n\n### Project structure\n```\ncmd/\n  server/main.go\ninternal/\n  users/\n    handler.go\n    service.go\n    repo.go\n    model.go\n  config/\n  db/\n  middleware/\npkg/                    # only for code you'd actually share\ngo.mod\n```\n\nUse `chi` (idiomatic, small) or `Gin` (familiar to Express users). Skip the debates — both are fine.\n\nUse `sqlc` to generate type-safe Go from SQL. It's better than any ORM for Go.\n\n### Testing\nGo's built-in `testing` package. Table-driven tests. `testify` for nicer assertions if the team likes it.\n\n## API layering pattern (all languages)\n\n```\n┌────────────────────────────┐\n│  HTTP layer (routes/       │  parse input, auth check, call service\n│  handlers/controllers)     │\n├────────────────────────────┤\n│  Service layer             │  business logic, orchestration\n│                            │  <-- this is what you unit test\n├────────────────────────────┤\n│  Repository / data layer   │  DB access, external API calls\n└────────────────────────────┘\n```\n\nThis separation becomes worth it around 5–10 endpoints. Below that, keeping everything in the route handler is fine.\n\n## Background jobs & async work\n\nIf the user's app needs to send emails, process images, call slow third-party APIs, or do anything that shouldn't block an HTTP request:\n\n- **Small Node apps**: [BullMQ](https://bullmq.io) (Redis-backed) is the default.\n- **Python**: [Celery](https://docs.celeryq.dev) with Redis or RabbitMQ; [RQ](https://python-rq.org) is simpler and often enough.\n- **Go**: [asynq](https://github.com/hibiken/asynq) or [River](https://riverqueue.com) (Postgres-backed — no extra infra).\n- **Postgres-first**: [pg-boss](https://github.com/timgit/pg-boss) (Node) or River (Go). If you're already on Postgres and don't have heavy volume, skipping Redis is a real simplification.\n- **Serverless**: cloud-native (AWS SQS + Lambda, GCP Pub/Sub + Cloud Functions, Inngest, Trigger.dev).\n\nNever send emails, hit Stripe, or do anything slow inside the HTTP request handler. Queue the work, return fast, let the job system handle retries.\n\n## Real-time / WebSockets\n\n- **Simple broadcast / rooms**: Socket.IO (Node), or native WebSocket with a thin wrapper.\n- **Scalable pub/sub**: Redis pub/sub adapter for Socket.IO, or a dedicated service (Pusher, Ably, Supabase Realtime).\n- **Truly massive concurrent connections**: Elixir/Phoenix — the BEAM VM is built for this.\n\nServer-Sent Events (SSE) is underrated. If you only need server → client push (notifications, streaming AI responses, live updates), SSE is simpler than WebSocket and works through proxies that mangle WS.\n\n## Common mistakes to avoid\n\n- **N+1 queries.** Load related data with `include` / `join` / eager loading, not in a loop.\n- **Sync work inside request handlers.** Emails, image processing, third-party calls → background jobs.\n- **No timeouts on outbound calls.** Always set a timeout on `fetch` / `httpx` / HTTP clients, or one hanging call will exhaust your connection pool.\n- **Trusting the frontend.** Re-validate permissions on every write. \"The UI doesn't let them do X\" is not access control.\n- **Logging secrets.** Scrub tokens, passwords, card numbers from logs. Use a logger middleware that redacts known sensitive fields.\n\nFile v1.0.0:references/database-design.md\n\n# Database Design\n\nSchema design, migrations, indexes, and the SQL vs. NoSQL decision.\n\n## SQL vs. NoSQL — how to decide\n\n**Default to Postgres.** It handles relational data, JSON, full-text search, geospatial, and even some vector workloads. Most \"we need NoSQL\" arguments evaporate under scrutiny.\n\nPick NoSQL when:\n- **Document store (MongoDB, Firestore)**: data is genuinely document-shaped and you don't need joins. Examples: user-generated content with wildly varying shapes, event logs, session data.\n- **Key-value (Redis, DynamoDB)**: you know the exact access pattern (key → value), need very low latency, and willingly trade query flexibility for it. Great for caches, sessions, rate limiters, job queues.\n- **Wide-column (Cassandra, ScyllaDB)**: you have write-heavy time-series at massive scale and well-known access patterns.\n- **Graph (Neo4j)**: your queries are fundamentally about traversing relationships many hops deep (social graphs, knowledge graphs, fraud detection).\n\n\"We might need to scale\" is not a reason to reach for NoSQL. Postgres on a single box handles tens of thousands of QPS for most workloads. Scale when it's a real problem.\n\n## Relational schema design principles\n\n1. **Name tables as plural nouns**: `users`, `orders`, `order_items`. Name columns as snake_case singular: `user_id`, `created_at`.\n2. **Primary keys**: use UUIDs for anything exposed to the outside (URLs, API responses). Use bigint auto-increment for internal-only tables if you prefer. Don't use natural keys (email, username) as primary keys — they change.\n3. **Foreign keys**: always define them, even if you're using an ORM. They enforce referential integrity at the DB level.\n4. **Timestamps**: `created_at` and `updated_at` on every table. Use `TIMESTAMPTZ` in Postgres (timezone-aware), not `TIMESTAMP`.\n5. **Soft deletes**: add `deleted_at TIMESTAMPTZ NULL` when you need to preserve history. Be consistent — either all tables or none.\n6. **Enums**: Postgres native enums are fine for truly fixed sets (role types, statuses). For anything that might grow, use a reference table or a `CHECK` constraint on a `TEXT` column — altering an enum requires migrations.\n7. **JSON columns**: use `JSONB` in Postgres for flexible/metadata fields, but don't make your whole schema JSON. If a field is queried or filtered on, it deserves to be a column with an index.\n8. **NULL means \"unknown\" or \"not applicable\"**. Don't use it as \"false\" or \"empty string\" — it's a different thing and breaks queries.\n\n## Indexing — the single biggest perf lever\n\nRules of thumb:\n- Every foreign key needs an index. Most ORMs don't create these automatically.\n- Every column that appears in a `WHERE`, `ORDER BY`, or `JOIN` predicate on a hot query path needs an index.\n- Composite indexes: the order matters. Put the most selective / most-filtered column first.\n- Adding an index has a cost — slower writes, more disk. Don't add indexes speculatively.\n- Run `EXPLAIN ANALYZE` on your slow queries. The plan tells you exactly what's happening.\n\nA common mistake: the ORM generates a query that's not using any of your indexes. Check. Don't trust.\n\n## Migrations\n\nEvery schema change goes through a migration file. Never edit the DB by hand in any environment above local dev.\n\n### Tooling\n- **Prisma** (Node): `prisma migrate dev` / `prisma migrate deploy`\n- **Drizzle** (Node): `drizzle-kit generate` / `drizzle-kit migrate`\n- **Alembic** (Python/SQLAlchemy): `alembic revision --autogenerate` / `alembic upgrade head`\n- **Django**: `makemigrations` / `migrate`\n- **Go**: `golang-migrate` or `goose`\n- **Rails**: built-in migrations\n\n### Migration safety in production\n\nThe golden rule: **all migrations must be backward-compatible with the currently-deployed app code**, because there's always a window during deploy where old and new code both run.\n\nSafe patterns:\n- Add a new nullable column → backfill in a background job → make NOT NULL in a second migration (after old code is gone).\n- Rename a column → create a new column, dual-write from the app, backfill, migrate reads, drop the old column. Multiple deploys.\n- Drop a column → stop writing from the app first, ship that, then drop in a later migration.\n\nDangerous patterns that block or lock tables on Postgres:\n- `ALTER TABLE ... ADD COLUMN ... NOT NULL DEFAULT <value>` on large tables (rewrites the whole table on older Postgres versions; fast on Postgres 11+).\n- Adding an index on a large table without `CONCURRENTLY`.\n- Long-running queries that hold locks (transactions on DDL statements).\n\nFor large production tables, always use `CREATE INDEX CONCURRENTLY`. Most ORM migration tools default to the blocking version — override explicitly.\n\n## Common schemas for common domains\n\n### Multi-tenant SaaS\nThree approaches, pick by isolation needs:\n1. **Shared schema + tenant_id column on every table.** Simplest. What most SaaS apps use. Requires discipline — every query must filter by tenant.\n2. **Schema-per-tenant** (Postgres schemas). Stronger isolation, moderate complexity, doesn't scale to 10,000s of tenants.\n3. **Database-per-tenant**. Strongest isolation. Only for a handful of enterprise tenants or regulated industries.\n\nEnforce tenant scoping at the ORM/repo layer, not in individual queries — one forgotten `WHERE tenant_id = ...` is a data leak.\n\n### Users + auth\n```sql\nusers (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  email TEXT UNIQUE NOT NULL,\n  email_verified_at TIMESTAMPTZ,\n  password_hash TEXT,              -- NULL if only OAuth\n  created_at TIMESTAMPTZ DEFAULT NOW(),\n  updated_at TIMESTAMPTZ DEFAULT NOW()\n)\n\nsessions (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  user_id UUID REFERENCES users(id) ON DELETE CASCADE,\n  token_hash TEXT UNIQUE NOT NULL, -- never store raw tokens\n  expires_at TIMESTAMPTZ NOT NULL,\n  created_at TIMESTAMPTZ DEFAULT NOW()\n)\n\n-- if supporting OAuth providers\noauth_accounts (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  user_id UUID REFERENCES users(id) ON DELETE CASCADE,\n  provider TEXT NOT NULL,          -- 'google', 'github', etc.\n  provider_account_id TEXT NOT NULL,\n  UNIQUE (provider, provider_account_id)\n)\n```\n\n### Orders / e-commerce\n```sql\norders (\n  id UUID PRIMARY KEY,\n  user_id UUID REFERENCES users(id),\n  status TEXT NOT NULL,           -- 'pending', 'paid', 'shipped', ...\n  total_cents INTEGER NOT NULL,   -- never store money as float\n  currency CHAR(3) NOT NULL,\n  created_at TIMESTAMPTZ DEFAULT NOW()\n)\n\norder_items (\n  id UUID PRIMARY KEY,\n  order_id UUID REFERENCES orders(id) ON DELETE CASCADE,\n  product_id UUID REFERENCES products(id),\n  quantity INTEGER NOT NULL CHECK (quantity > 0),\n  unit_price_cents INTEGER NOT NULL  -- snapshot, not a join\n)\n```\n\nAlways snapshot prices at order time. The product's price may change; the order's historical price must not.\n\n### Audit / event log\n```sql\naudit_log (\n  id BIGSERIAL PRIMARY KEY,\n  actor_id UUID,                   -- who did it\n  action TEXT NOT NULL,            -- 'user.created', 'order.refunded'\n  target_type TEXT NOT NULL,\n  target_id TEXT NOT NULL,\n  metadata JSONB,\n  created_at TIMESTAMPTZ DEFAULT NOW()\n)\nCREATE INDEX ON audit_log (actor_id, created_at DESC);\nCREATE INDEX ON audit_log (target_type, target_id, created_at DESC);\n```\n\nAudit logs are append-only. No updates, no deletes. Eventually archive to cold storage.\n\n## Money and time — get these right early\n\n### Money\n- Store in the smallest unit (cents, satoshis) as an integer. NEVER as float.\n- Always store the currency.\n- Round only at display time, using the currency's rules.\n\n### Time\n- Store in UTC (`TIMESTAMPTZ` in Postgres). Convert at display.\n- Store user-preferred timezone as a separate column when you need it (\"Send daily digest at 9am THEIR time\").\n- Dates (not times) are different — \"birthday\" is a `DATE`, not a `TIMESTAMPTZ`.\n\n## NoSQL (MongoDB) specifics\n\nWhen you have chosen MongoDB deliberately:\n\n- **Design around access patterns.** Embed what you always read together, reference what you read separately. Don't \"3NF\" your documents.\n- **Indexes matter just as much.** Always index query fields. `db.collection.explain()` is your friend.\n- **Don't use MongoDB transactions as the happy path.** They work but are the fallback, not the primary design. If you need transactions everywhere, you probably wanted SQL.\n- **Validation with JSON Schema**. MongoDB supports schema validation; use it. Schemaless doesn't mean \"no schema,\" it means \"the schema lives in your app code and you should document it.\"\n\n## Connection pooling\n\nFor any serverful deployment, connection pooling is mandatory:\n- Postgres: PgBouncer in transaction mode, or a connection pool built into your ORM (Prisma, SQLAlchemy).\n- In serverless (Vercel, AWS Lambda), use a pooling proxy — PgBouncer, Neon's built-in pooler, Supabase's pooler, AWS RDS Proxy. Direct connections from serverless rapidly exhaust the DB.\n\n## Backups\n\n- Enable automated daily backups on the managed DB.\n- Enable point-in-time recovery (PITR) for production.\n- Test restore at least quarterly. An unverified backup is not a backup — prove the restore path works before you need it.\n\nFile v1.0.0:references/deployment-cicd.md\n\n# Deployment & CI/CD\n\nHow to get the app from \"works on my machine\" to \"running in production, auto-deployed, observable.\"\n\n## Choosing a deployment target\n\n| Target | Best for | Watch out for |\n|---|---|---|\n| **Vercel** | Next.js, static sites, small APIs | Serverless cold starts; cost at scale; vendor-specific features |\n| **Netlify** | Static sites, JAMstack | Similar to Vercel, lighter on backend features |\n| **Cloudflare Pages/Workers** | Edge-first, global low latency | Workers runtime is not Node — subset of APIs |\n| **Fly.io** | Dockerized apps, global regions, persistent volumes | Regional failure requires planning |\n| **Railway** | Simplest \"just run my Dockerfile\" | Limited regions; pricing at scale |\n| **Render** | Heroku replacement; background workers, cron, DB | Similar to Railway |\n| **AWS** (ECS/EKS/Lambda/App Runner) | Serious scale, AWS-integrated stacks | Highest complexity; IAM is a full-time job |\n| **GCP / Azure** | Similar scope to AWS | Similar tradeoffs |\n| **Kubernetes** (self-managed or EKS/GKE) | Large teams, multi-service, complex infra | Massive operational burden; don't reach for it for an MVP |\n| **VPS** (Hetzner, DigitalOcean) + Docker | Cost-sensitive, full control | You own everything — backups, monitoring, security patches |\n\n**Default recommendation**: Vercel for Next.js monolith. Fly.io or Railway for Docker-based Node/Python/Go. AWS when the user is already there or needs specific services. Avoid Kubernetes for v1 unless the team already runs it.\n\n## Docker — when and how\n\n### When to Dockerize\n- Deploying to anything container-based (Fly, Railway, Render, ECS, K8s).\n- You want the dev environment to match prod.\n- The app has non-trivial system dependencies (binary libs, native modules).\n\n### When to skip Docker\n- Deploying to Vercel / Netlify (they handle runtime).\n- Tiny scripts or cron jobs where a container is overkill.\n\n### Dockerfile patterns\n\n**Node.js (multi-stage, slim):**\n```dockerfile\nFROM node:22-alpine AS deps\nWORKDIR /app\nCOPY package.json package-lock.json ./\nRUN npm ci --omit=dev\n\nFROM node:22-alpine AS builder\nWORKDIR /app\nCOPY package.json package-lock.json ./\nRUN npm ci\nCOPY . .\nRUN npm run build\n\nFROM node:22-alpine AS runner\nWORKDIR /app\nENV NODE_ENV=production\nCOPY --from=deps /app/node_modules ./node_modules\nCOPY --from=builder /app/.next ./.next\nCOPY --from=builder /app/public ./public\nCOPY package.json ./\nEXPOSE 3000\nUSER node\nCMD [\"npm\", \"start\"]\n```\n\n**Python (FastAPI):**\n```dockerfile\nFROM python:3.12-slim AS builder\nWORKDIR /app\nCOPY pyproject.toml uv.lock ./\nRUN pip install uv && uv sync --frozen --no-dev\n\nFROM python:3.12-slim\nWORKDIR /app\nCOPY --from=builder /app/.venv /app/.venv\nENV PATH=\"/app/.venv/bin:$PATH\"\nCOPY . .\nEXPOSE 8000\nUSER 1000\nCMD [\"uvicorn\", \"app.main:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]\n```\n\n**Go (distroless, smallest):**\n```dockerfile\nFROM golang:1.23 AS builder\nWORKDIR /src\nCOPY go.mod go.sum ./\nRUN go mod download\nCOPY . .\nRUN CGO_ENABLED=0 go build -o /bin/server ./cmd/server\n\nFROM gcr.io/distroless/static-debian12\nCOPY --from=builder /bin/server /server\nUSER nonroot:nonroot\nEXPOSE 8080\nENTRYPOINT [\"/server\"]\n```\n\n### Docker rules\n- **Multi-stage builds**: keep the final image small and free of build tools.\n- **Run as non-root**: create a user, switch to it with `USER`.\n- **Don't bake secrets** into images. Use runtime env vars or a secrets manager.\n- **Pin base image versions** — `node:22-alpine`, not `node:latest`. Rebuild periodically for security patches.\n- **`.dockerignore`**: mirror `.gitignore` + add `node_modules`, `.git`, test fixtures, local env files. Smaller context = faster builds.\n- **Healthcheck** endpoint: `/health` that returns 200 when the app is ready to serve. Your orchestrator needs this.\n\n## CI: GitHub Actions (default)\n\nMost apps should have a single workflow that runs on every push and PR, plus a deploy workflow on merge to `main`.\n\n### Minimal CI workflow\n```yaml\n# .github/workflows/ci.yml\nname: CI\non:\n  push:\n    branches: [main]\n  pull_request:\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n    services:\n      postgres:\n        image: postgres:16\n        env:\n          POSTGRES_PASSWORD: postgres\n        ports: ['5432:5432']\n        options: >-\n          --health-cmd pg_isready --health-interval 10s\n          --health-timeout 5s --health-retries 5\n    steps:\n      - uses: actions/checkout@v4\n      - uses: actions/setup-node@v4\n        with:\n          node-version: '22'\n          cache: 'npm'\n      - run: npm ci\n      - run: npm run lint\n      - run: npm run typecheck\n      - run: npm test\n        env:\n          DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres\n      - run: npm run build\n```\n\n### What every CI pipeline should do\n1. Install dependencies (with a lockfile, deterministic).\n2. Lint.\n3. Typecheck.\n4. Run tests (unit + integration).\n5. Build the production artifact.\n6. (Optional) Build and push Docker image to a registry.\n7. (Optional) Deploy — usually a separate workflow, gated on passing CI.\n\n### Speeding up CI\n- Cache dependencies (`cache: 'npm'`, `actions/cache` for Python/Go).\n- Run independent jobs in parallel (lint + typecheck + test as separate jobs).\n- Only run E2E on main + nightly, not every push.\n- Use matrix sparingly — test on one Node version in CI, not all of them, unless you ship a library.\n\n## CD: deployment strategies\n\n### Continuous deployment to staging\nEvery merge to `main` → auto-deploy to staging. No approval. Fast feedback, confidence from seeing it run.\n\n### Production deployment\nPick one:\n- **Auto-deploy `main` to prod** — fine for small teams and mature test coverage.\n- **Tag to deploy** — merge to `main` goes to staging; creating a git tag triggers prod. Forces a human to \"press the button.\"\n- **Manual approval** — GitHub Actions environments support required reviewers.\n\n### Preview deployments\nEvery PR gets its own URL (Vercel, Netlify, Fly.io all do this natively). Reviewers and designers can click around before approving. For anything user-visible, this is essential.\n\n### Migrations during deploy\nRun migrations **before** the new app version starts serving traffic, and make them backward-compatible (see `database-design.md`). Options:\n- A pre-deploy CI step that runs `prisma migrate deploy` / `alembic upgrade head` / etc.\n- A separate \"migrate\" job in your platform (Render job, Vercel build command, Fly \"release command\").\n\n### Rollback plan\n- Know how to revert the deploy in under 5 minutes.\n- Don't assume \"just redeploy the previous commit.\" If that commit has schema migrations, rollback is harder.\n- Document the rollback procedure in the runbook.\n\n## Platform-specific notes\n\n### Vercel (Next.js)\n- Connect GitHub repo → automatic deploys for `main` (production) and PRs (preview).\n- Environment variables configured per environment (dev, preview, production).\n- Database migrations: add to `\"build\"` script or use a dedicated CI job; Vercel build can run `prisma migrate deploy`.\n- Serverless function limits: check timeout (10s default, up to 300s on paid plans), bundle size (~50 MB), cold starts.\n\n### Fly.io\n- `fly launch` generates a `fly.toml`. Commit it.\n- `fly deploy` ships a new version. Can be called from CI with `flyctl` and `FLY_API_TOKEN`.\n- Persistent storage via volumes (for DBs or file uploads).\n- Global: deploy to multiple regions with `fly regions add`.\n- Secrets: `fly secrets set KEY=value`. Not visible in logs.\n- Release commands for migrations: `deploy.release_command = \"npm run migrate\"` in `fly.toml`.\n\n### Railway\n- Connect repo → auto-build via nixpacks or Dockerfile.\n- Managed Postgres, Redis, etc. available as services with shared env vars.\n- Release commands for migrations in `railway.json` or via UI.\n\n### AWS (ECS / App Runner / Lambda)\n- **App Runner** is the simplest — point at a container registry, it runs it. Fine for small apps.\n- **ECS Fargate** is the workhorse for serious container deployments. Infrastructure as code (Terraform, CDK) is practically required.\n- **Lambda** for event-driven or low-traffic APIs. Watch for cold starts; use SnapStart (Java/Python) or lean Node/Go runtimes.\n- **Secrets**: AWS Secrets Manager or Parameter Store. Reference by ARN, don't paste values.\n- **IAM**: least privilege. The role your app runs as should only have the permissions it needs. Auditing IAM is a real activity — budget time for it.\n\n### Kubernetes\n- Don't start here. Start with something simpler.\n- If you do need it: use a managed K8s service (EKS, GKE, AKS). Don't self-host the control plane.\n- Use Helm for app packaging; ArgoCD or Flux for GitOps.\n- Set resource requests and limits on every pod. Pod disruption budgets. Liveness/readiness probes.\n\n### VPS + Docker + nginx\nCost-effective, full control. Roughly:\n- Hetzner/DO VPS with Ubuntu LTS.\n- Docker + docker-compose or a simple orchestrator (Dokku, Coolify, Caprover).\n- nginx (or Caddy — Caddy auto-provisions Let's Encrypt certs, very nice).\n- Deploys via SSH + `docker pull && docker compose up -d`, or via a GitHub Actions runner.\n- You own: backups, security updates, monitoring, log rotation, firewall, SSH hardening.\n\n## Zero-downtime deploys\n\nFor anything past \"hobby project\" status:\n- **Health checks**: app exposes `/health`; platform doesn't route traffic until it's healthy.\n- **Graceful shutdown**: on SIGTERM, stop accepting new requests but finish in-flight ones. Platforms usually give you ~30s.\n- **Rolling deploys** (or blue-green): new version runs alongside old until healthy, then old is torn down.\n- **Database migrations first, app deploys after** — and migrations are backward-compatible.\n- **Session handling**: if sessions are in memory, they die on every deploy. Use Redis or your DB.\n\n## Environment management\n\nTypical environments:\n- **local** — each dev's machine. Their own `.env`.\n- **staging / preview** — prod-like, wired to a staging DB. Every PR or every `main` push deploys here.\n- **production** — the real one.\n\nRules:\n- Each env has its own database. Never share.\n- Each env has its own secrets. Rotating a staging key must not affect prod.\n- Prod data must not flow back to staging (privacy, compliance). If you need realistic test data, anonymize.\n\n## Feature flags\n\nFor any app past MVP, consider feature flags (LaunchDarkly, Unleash, ConfigCat, or a simple in-house `flags` table). Benefits:\n- Deploy code without exposing it to users.\n- Gradual rollouts (1%, 10%, 100%).\n- Instant disable of a broken feature — faster than a rollback deploy.\n- A/B testing.\n\nDownsides: proliferation of flags that never get cleaned up. Add a \"flag retirement\" task to each release.\n\n## Blue-green vs. canary\n\n- **Blue-green**: run two identical envs. Cut traffic from blue to green. Rollback = cut back. Simple, not partial.\n- **Canary**: route a small % of traffic to the new version; watch error rate; ramp up. Best for detecting regressions before wide blast.\n\nMost platforms do rolling deploys (a kind of canary). Canary-by-header or canary-by-user is a manual setup worth building for revenue-critical apps.\n\n## Disaster recovery\n\nDefine and test:\n- **RTO** (Recovery Time Objective): how long can the app be down?\n- **RPO** (Recovery Point Objective): how much data can we lose?\n\nThen:\n- Ensure backups meet RPO (hourly PITR for low RPO; daily for higher).\n- Practice restores at least quarterly. Write a runbook.\n- Have a secondary region plan if the RTO demands it. Most startups can tolerate an outage while the primary region recovers — don't build multi-region until you need it.\n\nFile v1.0.0:references/frontend-stacks.md\n\n# Frontend Stacks\n\nPatterns and defaults for the major modern frontend frameworks. Pick one based on project needs; don't mix frameworks in a single app.\n\n## Choosing a frontend\n\n| If you need... | Pick |\n|---|---|\n| SEO, server rendering, file-based routing, same-repo backend | **Next.js (App Router)** |\n| Rich SPA with no SSR needs, fastest dev loop | **React + Vite** |\n| Vue ecosystem preference or Nuxt-style SSR | **Nuxt 3** |\n| Smallest bundle, simplest mental model, server/client merged | **SvelteKit** |\n| Desktop-app feel with React | React + Vite + Electron or Tauri |\n| Content-heavy marketing site with occasional interactivity | **Astro** (ships zero JS by default) |\n\nIf the user has no preference and you're not sure, **default to Next.js App Router with TypeScript and Tailwind**. It's the broadest-utility choice and has strong defaults for routing, data fetching, and deployment.\n\n## Universal frontend principles\n\nRegardless of framework:\n\n- **TypeScript by default.** The refactor safety and editor tooling pay for themselves within a week on any non-trivial project.\n- **Use a component library as a base layer.** [shadcn/ui](https://ui.shadcn.com) for React (copies components into your repo — you own them), Radix UI primitives, or Headless UI. Don't build buttons, dropdowns, and modals from scratch.\n- **Tailwind CSS** for styling unless the user insists otherwise. Avoid the 2015-era \"CSS-in-JS\" libraries (styled-components, emotion) on new projects — they're slower and the ecosystem has largely moved on.\n- **Forms**: React Hook Form + Zod (React) or VeeValidate + Zod (Vue). Never roll your own validation on forms with >3 fields.\n- **Server state**: TanStack Query (React) / Vue Query / SvelteKit's built-in loaders. This is what you want for fetching, caching, and syncing with the server. Don't reach for Redux or global state unless you actually need cross-component shared state that isn't server data.\n- **Client state**: prefer component state and URL params. Reach for Zustand / Pinia / Svelte stores only when state genuinely needs to be shared across the component tree.\n- **Accessibility from day one**: semantic HTML, keyboard navigation, alt text, focus management on route changes and modals. Running axe or Lighthouse takes 30 seconds.\n- **Image handling**: use the framework's Image component (Next's `<Image>`, Nuxt's `<NuxtImg>`). It handles lazy loading, responsive sizes, and format conversion for free.\n\n## Next.js (App Router) — recommended default\n\n### Directory structure\n```\napp/\n  (marketing)/              # route group — doesn't affect URL\n    page.tsx                # homepage\n    pricing/page.tsx\n  (app)/\n    layout.tsx              # shared app shell (requires auth)\n    dashboard/page.tsx\n    settings/page.tsx\n  api/\n    users/route.ts          # route handler\n    webhooks/stripe/route.ts\n  layout.tsx                # root layout\n  globals.css\ncomponents/\n  ui/                       # shadcn/ui components live here\n  forms/\n  layouts/\nlib/\n  db.ts                     # database client singleton\n  auth.ts                   # auth helpers\n  validations/              # Zod schemas\nserver/\n  actions/                  # server actions\n  services/                 # business logic (pure, testable)\ntypes/\n```\n\n### Data fetching patterns\n- **Server components by default.** Fetch directly from the DB in a server component — no API round-trip needed for first render. Use `async` server components and `await`.\n- **Client components (`\"use client\"`) only when needed**: interactivity, hooks, browser APIs. Keep these leaves small.\n- **Mutations**: Server Actions for form posts. For interactive updates, a route handler + TanStack Query on the client.\n- **Caching**: understand `fetch` cache options, `revalidatePath`, `revalidateTag`. Caching bugs are the #1 source of \"why does my Next.js app show stale data\" questions — be explicit.\n\n### Auth pattern\nAuth.js (formerly NextAuth) or Clerk. Both handle session, OAuth providers, and middleware-based route protection.\n\n### What to avoid in Next.js\n- Don't put sensitive server logic in client components. If you see `\"use client\"` at the top of a file that touches the DB, that's a bug.\n- Don't `useEffect` to fetch data you could fetch on the server. It causes layout shift and worse SEO.\n- Don't put the database client inside a request handler — instantiate it once in `lib/db.ts` and import it. (In dev, guard against Hot Module Reload re-instantiation.)\n\n## React + Vite (SPA)\n\nWhen you genuinely don't need SSR — internal tools, authenticated-only dashboards, PWAs.\n\n### Directory structure\n```\nsrc/\n  pages/             # or routes/\n  components/\n  lib/\n  hooks/\n  services/          # API clients\n  types/\n  main.tsx\n  App.tsx\n```\n\n### Routing\nReact Router v6+ is the default. TanStack Router is a strong alternative with type-safe routes.\n\n### Data fetching\nTanStack Query. Always.\n\n### API client\nA single `lib/api.ts` that wraps `fetch` with base URL, auth headers, and error handling. Don't scatter `fetch` calls across 40 components.\n\n## Nuxt 3 (Vue)\n\n### Directory structure\nNuxt has strong conventions — use them:\n```\npages/               # file-based routing\ncomponents/          # auto-imported\ncomposables/         # auto-imported hooks\nserver/api/          # API routes\nserver/utils/\nmiddleware/          # route middleware\nplugins/\n```\n\n### Data fetching\n`useFetch` / `useAsyncData` for SSR-aware fetching. Pinia for shared client state.\n\n## SvelteKit\n\n### Directory structure\n```\nsrc/\n  routes/\n    +page.svelte\n    +page.server.ts      # server-only load\n    api/\n      users/+server.ts\n  lib/\n    components/\n    server/              # server-only code\n```\n\n### Data fetching\n`+page.server.ts` `load` functions for server-side data. Form actions for mutations — simpler than REST for most form posts.\n\n## State management — decision tree\n\n1. Is this data from the server? → Use TanStack Query / Nuxt's useFetch / SvelteKit loaders. **Stop.**\n2. Does this state belong in the URL (filters, pagination, selected tab)? → URL params. **Stop.**\n3. Is this local to one component? → `useState` / `ref`. **Stop.**\n4. Is this shared across a small subtree? → Context / provide-inject. **Stop.**\n5. Truly global, app-wide, non-server client state? → Zustand / Pinia / Svelte store.\n\nMost apps never need step 5.\n\n## Build, bundle, lint\n\n- **ESLint** with the framework's recommended config, plus `eslint-plugin-tailwindcss` if using Tailwind.\n- **Prettier** for formatting. Integrate with your editor so it runs on save.\n- **Type-check in CI**: `tsc --noEmit` as a CI step. Don't let type errors accumulate.\n- **Bundle analysis**: run it before you ship. Next.js has `@next/bundle-analyzer`; Vite has `rollup-plugin-visualizer`. If your entry bundle is >500 KB gzipped, investigate.\n\nFile v1.0.0:references/observability.md\n\n# Observability\n\nHow to know what the app is doing in production — before, during, and after an incident.\n\n## The three pillars (and why they matter)\n\n1. **Logs** — discrete events with context. Answer: \"what happened in this specific request?\"\n2. **Metrics** — aggregated numeric data over time. Answer: \"is the system healthy right now?\"\n3. **Traces** — the path of a request across services. Answer: \"where was the 3 seconds spent?\"\n\nYou don't need all three on day one. Get logs and basic metrics first; add traces when the system spans multiple services or background jobs.\n\n## Logging\n\n### Structured JSON, always\nPlain-text logs that look like `2026-04-01 user \"Foo Bar\" did a thing with id 123` are nearly impossible to query in aggregate. Emit JSON:\n\n```json\n{\n  \"timestamp\": \"2026-04-01T12:34:56.789Z\",\n  \"level\": \"info\",\n  \"message\": \"payment.completed\",\n  \"request_id\": \"req_abc123\",\n  \"user_id\": \"usr_xyz\",\n  \"amount_cents\": 2500,\n  \"currency\": \"USD\",\n  \"duration_ms\": 142\n}\n```\n\n### Fields every log line should have\n- `timestamp` (ISO 8601, UTC)\n- `level` (debug, info, warn, error)\n- `message` (short, semantic, like an event name — not \"the thing happened for user 123\")\n- `request_id` / `trace_id` — correlate across services\n- `user_id` / `tenant_id` when available\n- service-specific context (order_id, job_id, etc.)\n\n### What to log\n- Every inbound HTTP request at info level: method, path, status, duration, user, request ID.\n- Every outbound call to external services: endpoint, status, duration, outcome.\n- Every auth event: login (success/fail), logout, password change, MFA.\n- Every background job: start, end, duration, outcome, attempts.\n- Every error with full stack.\n\n### What NOT to log\n- Passwords, tokens, session IDs, card numbers, SSNs, health records. Even hashed.\n- Full request bodies on endpoints that accept sensitive data.\n- Full response bodies (usually unnecessary, often sensitive).\n\nUse a redaction filter in the logger (e.g., [`pino`](https://github.com/pinojs/pino)'s `redact` option) to strip known-sensitive fields automatically.\n\n### Log levels — when to use which\n- **debug** — development noise, detailed diagnostic. Off in production.\n- **info** — normal operations. Log what happened; future-you will want this.\n- **warn** — something unusual but not broken (fallback triggered, rate limit hit).\n- **error** — something broke. Page someone if it's unexpected.\n\nKeep production at `info`. Turn on `debug` for a single request via a header, not globally.\n\n### Request IDs\nEvery incoming request gets a unique ID. It's logged on every line for that request, and propagated to downstream calls (via `X-Request-Id` header or W3C Trace Context). When a user reports a problem, you can find every log line related to their request.\n\n### Where to send logs\n- **Managed platforms** (Vercel, Fly, Railway) have built-in log viewers for a short retention.\n- **Aggregation**: ship to a log platform — Datadog, New Relic, Grafana Loki, Better Stack, Axiom, Papertrail. Structured JSON makes querying trivial.\n- **Self-hosted**: ELK stack (Elasticsearch, Logstash, Kibana) or Grafana Loki. Operationally heavy; don't start here.\n\n## Error tracking\n\nLogs are for \"everything that happened.\" Error tracking is for the subset: exceptions and errors that need human attention.\n\n### Tooling\n- **Sentry** — standard for JS/Python/Go/etc. Great frontend + backend coverage.\n- **Rollbar**, **Bugsnag** — similar category.\n- **Honeybadger** — Ruby-first but fine elsewhere.\n- Most error trackers have free tiers sufficient for small apps.\n\n### Setup essentials\n- Wire into both frontend and backend.\n- Attach user context (ID, email redacted) on every event.\n- Attach release/version so you can correlate error spikes with deploys.\n- Upload sourcemaps from the frontend build so errors have readable stacks — but don't serve sourcemaps to users.\n- Configure data scrubbing: redact passwords, tokens, card numbers from captured payloads.\n- Set up alerts: new error types, error volume spikes, errors affecting >N users.\n\n### Frontend errors\n- Global `window.onerror` / `unhandledrejection` handler reports to Sentry.\n- React/Vue error boundary that reports and shows a fallback UI.\n- Core Web Vitals (LCP, CLS, INP) — Sentry can capture these; so can Vercel Analytics.\n\n## Metrics\n\n### What to measure — the RED method\nFor every request-handling service, track:\n- **R**ate — requests per second\n- **E**rrors — % of requests failing\n- **D**uration — p50, p95, p99 latency\n\nThis is the absolute minimum. You can make most performance and reliability decisions from these.\n\n### The USE method (for resources)\nFor every resource (CPU, memory, disk, DB connections):\n- **U**tilization — % busy\n- **S**aturation — queue depth / wait time\n- **E**rrors — failures\n\n### Product metrics\nBeyond system health, measure the business:\n- Signups per day\n- Active users (DAU/WAU/MAU)\n- Conversion rates on key flows\n- Revenue\n\nThese tell you if the app is doing its job, not just if it's up.\n\n### Tooling\n- **Managed platform metrics** — start with what's built in (Vercel Analytics, Fly metrics, AWS CloudWatch).\n- **Prometheus + Grafana** — the open source standard. Hosted: Grafana Cloud, AWS Managed Prometheus.\n- **Datadog / New Relic** — paid, but bundle logs + metrics + traces + alerts.\n- **Cloudflare Analytics** — free, good for edge-level request metrics.\n\n### Dashboards\nHave at least one dashboard you look at weekly:\n- Request rate, error rate, p95 latency per service\n- Database: connections, query duration, slow queries\n- Background job queue depth and failure rate\n- Top 10 endpoints by p95 latency\n\nA dashboard nobody looks at is dead. Fewer, more meaningful panels beats a wall of 50.\n\n## Tracing\n\nDistributed tracing shows the path of a request across services — useful when you have multiple services or heavy background processing.\n\n- **OpenTelemetry** is the standard. Instrument once, send to any backend (Jaeger, Honeycomb, Datadog, Grafana Tempo, Sentry's tracing).\n- Start with auto-instrumentation (HTTP libraries, DB drivers) — gets you 80% for free.\n- Add custom spans around critical business operations.\n- Sampling: 1–10% of requests in prod for a busy service; 100% of errors.\n\nFor a single-service Next.js app, tracing is nice-to-have. For a 5-service system, it's essential.\n\n## Alerting\n\n### Alert on symptoms, not causes\n- Good alert: \"error rate >1% for 5 minutes.\" (Symptom.)\n- Bad alert: \"CPU >80%.\" (Cause — and possibly benign.)\n\nHigh CPU is interesting for debugging but doesn't always mean something's wrong. User-facing error rate does.\n\n### Alert fatigue is real\n- Every alert should be actionable. If the response is \"ignore it,\" remove the alert.\n- Tune thresholds after a week of calibration. A hair-trigger alert gets muted.\n- Alert severity: pageable (wake someone) vs. FYI (Slack/email).\n\n### Sensible starting alerts\n- 5xx rate >1% over 5 minutes → page\n- p95 latency >2x baseline over 10 minutes → page\n- Deploy failed → Slack\n- Background job queue depth exceeds threshold → Slack\n- Error tracker: new error type → Slack; >N users affected in an hour → page\n- Uptime monitor (healthcheck failing from external) → page\n- Certificate expiring in <7 days → Slack\n- Disk >80% → Slack; >95% → page\n\n### On-call\nFor anything past hobby status, define who's on-call. PagerDuty, Opsgenie, incident.io. Rotation is weekly, not per-person forever.\n\n## Uptime monitoring\n\nExternal checks (from outside your infrastructure) hitting a `/health` endpoint every 30–60s. If internal monitoring goes down with the app, you'd miss outages. External doesn't.\n\nTools: UptimeRobot, Better Stack, Pingdom, Checkly. Free tiers are fine for small apps.\n\n### The `/health` endpoint\n- Returns 200 when the app can serve traffic.\n- Checks what matters: DB connectivity, external services, cache.\n- Simple implementation: query a trivial `SELECT 1`, check Redis ping, return success.\n- Don't do expensive work in `/health` — it's called constantly.\n\nSeparate `/readiness` and `/liveness` if using Kubernetes:\n- `/liveness` — \"the process is alive.\" Fails → restart the container.\n- `/readiness` — \"the process can serve traffic.\" Fails → remove from load balancer.\n\n## Cost observability\n\nYour observability stack itself will have a bill. Watch it:\n- Logs: storage is usually the driver. Aggressive retention (30 days hot, archive longer if needed) controls cost.\n- Metrics: cardinality is the killer — high-cardinality tags (user_id, request_id) multiply series counts.\n- APM/tracing: per-request. Sampling matters.\n\nReview the monitoring bill quarterly. It's easy for it to become 10% of infra spend.\n\n## Feedback loops — closing the loop\n\nObservability is about closing the loop from \"incident\" back to \"code change.\" Each incident should ask:\n1. What was the signal? Was it fast enough?\n2. What was the root cause?\n3. How do we prevent recurrence or detect faster?\n4. Did the runbook help? If not, update it.\n\nWrite a short post-incident note, even for small incidents. They compound into institutional knowledge.\n\n## Minimum viable observability\n\nFor an app just launched, you need:\n- Structured JSON logs, aggregated somewhere searchable.\n- Sentry (or equivalent) on frontend and backend with sourcemaps + scrubbing.\n- One external uptime check on `/health`.\n- A dashboard: request rate, error rate, p95, DB connections.\n- Alerts: 5xx spike, uptime failure, new Sentry error type.\n\nThat's a weekend of setup for an app of any size. Everything past that is refinement.\n\nFile v1.0.0:references/sdlc-phases.md\n\n# SDLC Phases — Detailed Checklists\n\nThis file expands each SDLC phase with the concrete questions and artifacts that should exist before you move to the next one. Use it as a checklist, not a script.\n\n## 1. Requirements Analysis\n\n### Functional requirements\n- What are the 3–7 core user-facing capabilities? Write them as user stories: \"As a [role], I can [action] so that [outcome].\"\n- What are the explicit non-goals? Write them down — they're the first thing to cite when scope creeps.\n- What's the shortest possible path to a demo? That's your MVP.\n\n### Non-functional requirements\n- **Users & load**: expected DAU/MAU, peak concurrent users, requests/sec\n- **Latency**: acceptable p50, p95, p99 response times\n- **Data**: record counts, growth rate, retention, PII/sensitive data flags\n- **Availability**: is 99% fine, or is this a payments system that needs 99.99%?\n- **Compliance**: GDPR (EU users), HIPAA (health), PCI (cards), SOC 2 (enterprise B2B)\n- **Accessibility**: WCAG 2.1 AA is the default for anything public-facing\n- **Browsers/devices**: modern evergreen only, or IE11, or mobile-first?\n\n### Clarifying questions to ask when requirements are vague\n- \"Who is the primary user, and what's their technical comfort level?\"\n- \"Does this need auth? If yes, public signup or invite-only?\"\n- \"Is there existing data this needs to import from, or does it start empty?\"\n- \"Where will this be deployed, and who's paying for hosting?\"\n- \"What's the one thing that, if missing at launch, would make this not worth shipping?\"\n\n### Output artifact\nA short `REQUIREMENTS.md` or a bulleted section in the chat with: goals, non-goals, users, key flows, constraints. 10–30 lines is usually right.\n\n## 2. Planning\n\n### Scope slicing\n- Write an MVP list — features that MUST ship for v1 to be useful.\n- Write a \"v1.1\" list — things you'd add immediately after.\n- Write a \"someday\" list — everything else. This list is where good ideas go to wait.\n\n### Milestones as vertical slices\nOrder milestones so each one is independently runnable. Bad: \"build the whole database, then the whole API, then the whole frontend.\" Good: \"get a single entity (User) creatable from UI → API → DB, then add the next.\"\n\n### Risk register\nList risks and what you'd do about each:\n- **Third-party dependencies** (Stripe, OpenAI, Twilio): what if they're down or change their API?\n- **Novel tech**: are you using something you've never used before? Prototype the risky bit first.\n- **Unclear requirements**: call these out explicitly — \"we're guessing about X, need confirmation before wiring Y\"\n- **Performance assumptions**: load-test the riskiest path before building around it\n\n### Tech stack decision\nPick now. One line per choice justifying it. See the stack table in `SKILL.md`. Avoid decision paralysis — you can swap a library later; you can't swap a framework later without a rewrite. So spend time on the framework choice and move fast on everything else.\n\n## 3. Design & Architecture\n\n### Data model\n- List entities (User, Post, Order, etc.)\n- List relationships (1:1, 1:N, N:M)\n- List key fields per entity with types\n- Identify indexes you'll need based on query patterns\n- Identify soft-delete, audit, timestamp columns — adding these later is painful\n\nFor SQL: draft `CREATE TABLE` statements.\nFor NoSQL: draft document shapes AND the access patterns they support (DynamoDB in particular is access-pattern-driven).\n\n### API surface\n- REST: list endpoints with method, path, request body, response body, status codes.\n- GraphQL: draft the schema (types, queries, mutations).\n- Identify which endpoints need auth and what roles.\n\n### Frontend architecture\n- List pages/routes.\n- Identify shared components (navigation, forms, modals, tables).\n- Decide state boundaries: server state (React Query/SWR), global UI state (Zustand/Redux/Context), form state (React Hook Form).\n- Decide rendering strategy per page: SSR, SSG, CSR, ISR.\n\n### Infrastructure sketch\nDraw the request flow. Even ASCII is fine:\n\n```\n[Browser] --> [CDN/Vercel] --> [Next.js app]\n                                    |\n                                    +--> [Postgres]\n                                    +--> [S3 / object storage]\n                                    +--> [Stripe API]\n                                    +--> [SendGrid API]\n```\n\nIdentify the trust boundaries — every arrow crossing a boundary is a place that needs auth, validation, and error handling.\n\n### Directory layout\nShow the full tree before creating files. Fix it now — renaming directories later is a chore.\n\n### Output artifact\nA `DESIGN.md` or a design section with: data model, API list, component tree, infra diagram, directory tree.\n\n## 4. Implementation\n\nSee `SKILL.md` for the vertical-slice order. Additional guidance:\n\n### Version control hygiene\n- One commit per logical change, with a clear message.\n- Never commit `.env`, `node_modules`, build artifacts, or credentials.\n- Add a `.gitignore` on day one.\n\n### Code organization\n- **Routes / controllers**: thin — parse input, call a service, return a response.\n- **Services**: business logic. The thing you'd unit-test.\n- **Repositories / models**: database access. Replaceable.\n- **Utilities / lib**: pure functions shared across features.\n\nThis separation pays off around 2,000 lines, not before. Don't prematurely abstract a 200-line project.\n\n### Config & environment\n- `.env` for local secrets (git-ignored)\n- `.env.example` committed, documenting every required variable\n- Config validation on boot — the app should fail fast if a required env var is missing, not 20 minutes later when that code path runs\n\n### Error handling\n- At the API boundary: catch exceptions, return structured error JSON, log the full trace.\n- Inside services: throw domain-specific errors. Don't swallow or rewrap unless you're adding context.\n- On the frontend: one global error boundary, plus per-feature error states for network failures.\n\n### README as you go\nA `README.md` with prerequisites, `clone → install → env → migrate → run` steps. Update it every time the setup changes. A broken README wastes more time than a missing feature.\n\n## 5. Testing\n\nSee `references/testing-strategies.md`.\n\n## 6. Deployment & CI/CD\n\nSee `references/deployment-cicd.md`.\n\n## 7. Maintenance\n\n### Day-1 observability\n- Structured JSON logs with request ID, user ID, timing.\n- Error tracking (Sentry, Rollbar, or equivalent) in both frontend and backend.\n- Uptime check on the health endpoint.\n- Basic dashboard: request rate, error rate, p95 latency, DB connection count.\n\nSee `references/observability.md` for details.\n\n### Operational runbook\nA one-page doc covering:\n- How to deploy\n- How to roll back\n- How to connect to production DB read-replica\n- How to rotate a leaked secret\n- Who to page and how\n- Where to find logs, metrics, errors\n\n### Security review before launch\nWalk through `references/security-checklist.md`. Don't skip. The cost of an auth bug in prod dwarfs the 30 minutes of reviewing.\n\n### Ongoing maintenance\n- Dependency updates: Dependabot / Renovate on a weekly cadence, plus a quarterly major-version review.\n- Backup verification: restore the backup to a staging DB at least quarterly. An untested backup may not be a backup.\n- Tech debt tracking: keep a `TODO.md` or use issues. If something is a known compromise, write it down.\n\nFile v1.0.0:references/security-checklist.md\n\n# Security Checklist\n\nWalk through this before declaring an app production-ready. Most items are quick. The cost of a missed item is often orders of magnitude larger than the cost of checking.\n\n## Authentication & sessions\n- [ ] Passwords hashed with argon2id or bcrypt (cost ≥12). No MD5, SHA-1, SHA-256-alone.\n- [ ] Login failures return a generic error (\"invalid credentials\"), not \"user not found.\"\n- [ ] Rate limit on login, signup, password reset, and any other auth-adjacent endpoint.\n- [ ] MFA available for accounts (TOTP minimum); required for admin accounts.\n- [ ] Sessions expire. Long sessions via refresh tokens, not long-lived access tokens.\n- [ ] Logout actually invalidates the server-side session.\n- [ ] Force logout on password change, email change, and role change.\n- [ ] Suspicious-login notifications (new device/IP) sent to user.\n\n## Authorization\n- [ ] Every endpoint that reads or writes data checks the caller's permissions.\n- [ ] Permission checks happen server-side, not just in the UI.\n- [ ] Multi-tenant apps scope every DB query by tenant — ideally enforced in a single repository layer, not scattered across endpoints.\n- [ ] Admin endpoints are clearly separated (e.g., `/admin/*`) and have stricter auth + logging.\n- [ ] Direct object references (`/orders/{id}`) verify the authed user can access that specific object. (IDOR is the #1 bug class on bug bounty platforms.)\n\n## Input validation & injection\n- [ ] Every request body, query param, path param, and header you trust is validated (Zod, Pydantic, etc.).\n- [ ] All DB queries use parameterized queries / ORM. No string-concatenated SQL. Ever.\n- [ ] HTML output is escaped by default (React/Vue/Svelte do this; `dangerouslySetInnerHTML` is audited).\n- [ ] File uploads: validate MIME and extension, cap size, scan for malware for user-facing files, store outside the webroot (e.g., S3), serve via signed URLs or a handler that enforces access.\n- [ ] User-supplied URLs (avatars, embeds) fetched from the server go through SSRF protection — block RFC1918 IPs, cloud metadata endpoints (169.254.169.254), localhost.\n- [ ] Command execution or `eval`-adjacent functions do NOT take user input. If they must, whitelist with extreme prejudice.\n\n## Secrets management\n- [ ] No secrets in git (including history — scrub if found).\n- [ ] `.env` in `.gitignore`. `.env.example` committed with placeholder values.\n- [ ] Production secrets in a managed store (AWS Secrets Manager, GCP Secret Manager, Vault, Doppler, Infisical).\n- [ ] Dev, staging, prod have different secrets. Rotate on employee offboarding and suspected compromise.\n- [ ] App validates required secrets at boot and fails loud if missing.\n- [ ] Nothing secret is logged (passwords, tokens, card numbers, API keys). Logging middleware redacts known sensitive fields.\n\n## HTTPS & transport\n- [ ] HTTPS everywhere. HTTP redirects to HTTPS.\n- [ ] HSTS header (`Strict-Transport-Security: max-age=31536000; includeSubDomains`) on production.\n- [ ] TLS 1.2 minimum; TLS 1.3 preferred. Weak ciphers disabled.\n- [ ] Cookies marked `Secure` (HTTPS only) and `HttpOnly`.\n- [ ] Cookies have a `SameSite` attribute. Default to `Lax` or `Strict`.\n\n## Web security headers\nSet these at the edge or in middleware:\n- [ ] `Content-Security-Policy` — most impactful. Start strict (`default-src 'self'`), loosen as needed.\n- [ ] `X-Content-Type-Options: nosniff`\n- [ ] `X-Frame-Options: DENY` (or `SAMEORIGIN`) — prevent clickjacking. CSP `frame-ancestors` is the modern equivalent.\n- [ ] `Referrer-Policy: strict-origin-when-cross-origin`\n- [ ] `Permissions-Policy` to opt out of APIs (camera, mic, geolocation) unless needed.\n\nTools like [securityheaders.com](https://securityheaders.com) grade the setup.\n\n## CORS\n- [ ] CORS configured explicitly. Default-deny; allowlist specific origins.\n- [ ] `Access-Control-Allow-Origin: *` only for truly public, non-credentialed APIs.\n- [ ] `Access-Control-Allow-Credentials: true` only when you need to accept cookies from a specific origin — never combined with wildcard.\n\n## CSRF\n- [ ] For cookie-based session auth: CSRF tokens on state-changing endpoints, or rely on `SameSite=Lax/Strict` cookies (which are effective for most modern attacks).\n- [ ] For bearer-token auth (Authorization header): CSRF is not a concern — browsers don't auto-attach Authorization headers.\n\n## Rate limiting & abuse\n- [ ] Per-endpoint rate limits sized to the threat (strict on auth, looser on reads).\n- [ ] Global rate limit as a backstop.\n- [ ] CAPTCHA on signup and password reset for public-facing apps.\n- [ ] WAF in front (Cloudflare, AWS WAF) — not a substitute, a layer.\n\n## Dependency security\n- [ ] Lockfile committed (`package-lock.json`, `poetry.lock`, `go.sum`).\n- [ ] `npm audit` / `pip-audit` / `govulncheck` in CI. Fail on high-severity.\n- [ ] Dependabot or Renovate configured for weekly updates.\n- [ ] Snyk / GitHub Advanced Security / Socket.dev for deeper SCA on sensitive apps.\n- [ ] Pin Docker base images to a specific tag, not `latest`. Rebuild regularly.\n\n## Logs, errors, and data leakage\n- [ ] Error responses don't leak stack traces, SQL, file paths, or internal hostnames to users. Full detail stays in logs.\n- [ ] Error reporting (Sentry) scrubs PII and secrets — configure data scrubbing rules.\n- [ ] Logs stored with access controls; PII in logs minimized or redacted.\n- [ ] Sourcemaps uploaded to error tracker but NOT served to users in prod (or served with restrictive source-map auth).\n\n## Database & backups\n- [ ] Database not exposed publicly — private network or IP allowlist.\n- [ ] Least-privilege DB credentials per service; no using the superuser from the app.\n- [ ] Automated daily backups with PITR (or equivalent) enabled.\n- [ ] Backups encrypted at rest.\n- [ ] Restore tested in the last 90 days.\n- [ ] PII columns identified and handled per compliance needs (encryption at rest, access logs).\n\n## File storage\n- [ ] Uploaded files stored outside the app server (S3, GCS). Not in the webroot.\n- [ ] Served via signed, short-lived URLs — not permanent public links (unless truly public).\n- [ ] Per-file content-type and content-disposition set correctly to prevent browser sniffing attacks.\n- [ ] Antivirus scan for user uploads distributed to other users.\n\n## Third-party integrations\n- [ ] Webhook payloads verified by signature before processing.\n- [ ] OAuth state parameter validated; PKCE used for public clients.\n- [ ] API keys to third parties stored in secrets manager; rotated per vendor recommendation.\n- [ ] Outbound requests have timeouts and circuit breakers — a hung third party must not bring down your app.\n\n## Infrastructure / platform\n- [ ] IAM policies follow least privilege. No wildcard `*` permissions in production roles.\n- [ ] SSH keys, not passwords, for server access. MFA on cloud consoles.\n- [ ] Database encryption at rest enabled.\n- [ ] VPC / private networking for inter-service communication.\n- [ ] DNS, domain registrar, and cloud accounts protected by MFA and account-recovery process.\n\n## Observability for security\n- [ ] Login events logged with IP and user-agent.\n- [ ] Permission-denied events (403s) logged — unusual spikes are interesting.\n- [ ] Admin actions logged to an append-only audit log.\n- [ ] Alerts on anomalies: spike in 5xx, spike in failed logins, new admin account created, IAM policy changed.\n\n## Incident response\n- [ ] Runbook for: compromised credential, data breach, DDoS, rogue dependency.\n- [ ] Known point of contact for security reports (`security@yourapp.com`, security.txt).\n- [ ] Communication plan: status page, customer email template, timeline of who decides what.\n\n## Pre-launch checks\n- [ ] Remove all `console.log`s that might dump secrets or user data.\n- [ ] Disable verbose error pages (Django `DEBUG=False`, no stack traces in prod responses).\n- [ ] Remove dev shortcuts (`/admin/become-user`, test-only endpoints).\n- [ ] Close ports not needed by the app (Postgres not exposed to the internet, etc.).\n- [ ] Scan with something like OWASP ZAP baseline scan, or a commercial scanner, on staging.\n- [ ] Document the data you collect and why — privacy policy reflects reality.\n\n## Compliance quick-reference\nIf any of these apply, the scope of this checklist expands significantly:\n- **GDPR** — any EU user data. Add: data-subject rights (access, deletion, portability), lawful basis for processing, DPA with subprocessors, breach notification within 72h.\n- **HIPAA** — any US health data. BAAs with everyone touching PHI, encryption, access audit logs, strict retention.\n- **PCI-DSS** — handling card data. Use a tokenization provider (Stripe, Adyen) and stay out of PCI scope if at all possible.\n- **SOC 2** — enterprise B2B often asks. Not a one-time audit — it's an operating pattern. Plan months ahead.\n\n## The 80/20 of security\nIf you only had time for ten things, do these:\n1. Use a reputable auth library; don't roll your own.\n2. Parameterize every SQL query.\n3. Validate every input at the boundary.\n4. Check authorization on every endpoint, for the specific resource.\n5. Store secrets in a secrets manager; never in git.\n6. HTTPS everywhere + secure cookies.\n7. Dependency updates automated + audited.\n8. Rate limit auth endpoints.\n9. Centralized error tracking with PII scrubbing.\n10. Backups, tested.\n\nEverything else is marginal improvements on top of these.\n\nFile v1.0.0:references/testing-strategies.md\n\n# Testing Strategies\n\nHow to test a full-stack app — what to write, what to skip, and how to keep the suite fast.\n\n## The testing pyramid\n\n```\n        ▲\n       /─\\      E2E (few, slow, realistic)     ~5%\n      /───\\\n     /─────\\    Integration (DB + API)         ~25%\n    /───────\\\n   /─────────\\  Unit (pure logic, fast)        ~70%\n  ─────────────\n```\n\nRough target ratios. The numbers don't matter; the shape does — lots of fast unit tests, fewer integration tests, very few E2E tests.\n\n### Why the pyramid\n- Unit tests: fast (<1s for thousands), run on every save, catch logic bugs early.\n- Integration tests: medium-speed, catch contract bugs between layers (API ↔ DB, service ↔ external).\n- E2E tests: slow, flaky-prone, but catch things nothing else catches — real browser + real backend + real DB.\n\nInverting the pyramid (mostly E2E, few unit tests) produces test suites that take 20 minutes and fail randomly. Don't.\n\n## Unit tests — what to test\n\n### Test pure logic\n- Domain rules: pricing, permissions, validation, date calculations\n- Transformations: parsers, formatters, mappers between layers\n- Decision functions: \"should this alert fire\", \"can this user see this post\"\n\n### Skip things not worth testing\n- Framework plumbing (routing, middleware registration)\n- Trivial getters/setters or pass-throughs\n- Third-party library behavior (trust it, or test at the integration level)\n\n### Patterns\n\n**Arrange-Act-Assert**:\n```ts\ntest('premium users get free shipping', () => {\n  // Arrange\n  const user = makeUser({ tier: 'premium' });\n  const cart = makeCart({ subtotal: 50 });\n\n  // Act\n  const total = calculateTotal(user, cart);\n\n  // Assert\n  expect(total.shipping).toBe(0);\n});\n```\n\n**Table-driven tests** for similar cases:\n```ts\ntest.each([\n  { tier: 'free', subtotal: 50, expectedShipping: 10 },\n  { tier: 'free', subtotal: 100, expectedShipping: 0 },  // free over $75\n  { tier: 'premium', subtotal: 10, expectedShipping: 0 },\n])('shipping: $tier tier, $$$subtotal cart', ({ tier, subtotal, expectedShipping }) => {\n  const total = calculateTotal(makeUser({ tier }), makeCart({ subtotal }));\n  expect(total.shipping).toBe(expectedShipping);\n});\n```\n\n### What's a \"unit\"?\nA unit is a coherent behavior, not a file or function. One test per public function is fine; one test per private helper is usually noise. Test behavior, not implementation.\n\n### Tools by language\n| Lang | Framework |\n|---|---|\n| JS/TS | **Vitest** (fast, ESM-native, Jest-compatible). Jest still works but is slower. |\n| Python | **pytest** |\n| Go | built-in `testing` + `testify` (optional) |\n| Rust | built-in `#[test]` |\n\n## Integration tests — the API + DB layer\n\nThis is where the most valuable tests live for a typical app. You spin up the app, hit real endpoints, verify the response and DB state.\n\n### Setup pattern (Node/Postgres)\n- Dedicated test database (e.g., `myapp_test`).\n- Migrate schema once before the suite.\n- Each test (or test file) runs in a transaction that rolls back — fast, isolated.\n- Seed minimal data inside each test.\n\n### Example (Fastify + Prisma + Vitest)\n```ts\nimport { buildApp } from '@/server';\nimport { prisma } from '@/lib/db';\n\ndescribe('POST /users', () => {\n  const app = buildApp();\n\n  beforeEach(async () => {\n    await prisma.user.deleteMany();\n  });\n\n  test('creates user with valid input', async () => {\n    const response = await app.inject({\n      method: 'POST',\n      url: '/users',\n      payload: { email: 'test@example.com', name: 'Test' },\n    });\n    expect(response.statusCode).toBe(201);\n    const user = await prisma.user.findUnique({ where: { email: 'test@example.com' } });\n    expect(user).not.toBeNull();\n  });\n\n  test('rejects invalid email', async () => {\n    const response = await app.inject({\n      method: 'POST',\n      url: '/users',\n      payload: { email: 'not-an-email', name: 'Test' },\n    });\n    expect(response.statusCode).toBe(400);\n  });\n});\n```\n\n### Setup pattern (Python/FastAPI)\n```python\nimport pytest\nfrom httpx import AsyncClient\nfrom app.main import app\nfrom app.db import Base, engine, SessionLocal\n\n@pytest.fixture(autouse=True)\ndef db_reset():\n    Base.metadata.drop_all(engine)\n    Base.metadata.create_all(engine)\n    yield\n\n@pytest.mark.asyncio\nasync def test_create_user():\n    async with AsyncClient(app=app, base_url=\"http://test\") as client:\n        response = await client.post(\"/users\", json={\"email\": \"a@b.com\", \"name\": \"A\"})\n        assert response.status_code == 201\n```\n\n## What NOT to mock\n\n**Don't mock your own database.** Integration tests that use a mock DB give you confidence in the mock, not in the code. A changed schema won't break the test. Use a real test database — SQLite in-memory for speed if your app is DB-agnostic, Postgres (Docker, Testcontainers, or local) if you rely on Postgres features.\n\n**Don't mock your own services from other services.** If service A calls service B, and both are in your repo, test them together (or test the contract with consumer-driven contract tests).\n\n**Do mock:**\n- Third-party HTTP APIs (Stripe, OpenAI, SendGrid) — record and replay with [`msw`](https://mswjs.io/), [`vcrpy`](https://vcrpy.readthedocs.io/), or [Prism](https://stoplight.io/open-source/prism).\n- Time and randomness — stub `Date.now()`, UUID generation, etc., with test doubles.\n- Slow or destructive side effects (sending real emails, charging real cards).\n\n### Stripe-specific pattern\nUse Stripe's [test mode](https://docs.stripe.com/testing) for integration tests that hit real Stripe APIs with test keys. For unit tests, mock the Stripe client.\n\n## End-to-end tests\n\nE2E tests drive a real browser against the real app (or a production-like staging env). They catch what nothing else catches, but they're expensive and flaky if overused.\n\n### Tools\n- **Playwright** (recommended): fast, reliable, multi-browser, great debugging.\n- Cypress: still popular, fine. Playwright has overtaken it for most teams.\n- Selenium: only if you need a language or browser matrix Playwright doesn't cover.\n\n### What to E2E test\nPick 3–10 \"critical user journeys,\" the paths where regression would be catastrophic:\n- Signup → email verify → first login\n- Login → do the app's main action → logout\n- Checkout / payment flow\n- Password reset\n\nDon't E2E test every feature. That's what integration tests are for.\n\n### Keeping E2E stable\n- Use `data-testid` attributes for selectors. Don't select by CSS class names — those change.\n- Always wait on real signals (element visibility, network idle), never on arbitrary `sleep(2000)`.\n- Reset test data between tests — a seed function that creates a known user and cleans up.\n- Retry flaky tests automatically (Playwright has `retries: 2` in CI). But: chronic flake = real bug, investigate.\n- Run in CI on a staging deployment, not locally-against-localhost (that's too hermetic).\n\n## Frontend component tests\n\nBetween unit tests and E2E sits component testing — test a React/Vue component in isolation.\n\nTools: **Vitest + React Testing Library** (or Vue Testing Library). Playwright has a component testing mode too.\n\nUseful for:\n- Complex forms (validation states, error display)\n- Stateful components (wizards, multi-step flows)\n- Components with lots of conditional rendering\n\nNot useful for:\n- Pure presentational components (snapshot tests age badly)\n- Things better covered by E2E (checkout flow, multi-page navigation)\n\n## Type checks and linters are tests too\n\n- `tsc --noEmit` or `mypy` or `go vet` in CI — catches a whole class of bugs before they hit the test suite.\n- ESLint / Ruff with reasonable rules — catches bugs and enforces consistency.\n- **Run them on every push.** Make CI fail on lint and type errors, not just test failures.\n\n## Coverage — useful signal, bad target\n\n- Track coverage as a signal of untested code, not a goal to hit.\n- 80% coverage with meaningful assertions is much better than 100% with dumb tests.\n- **Don't** set a coverage gate at 100% — it incentivizes test-shaped noise.\n- **Do** look at coverage before a risky refactor to see what's untested.\n\n## Speed matters\n\nA slow test suite is one you won't run. Optimization targets:\n- Unit suite: <10 seconds.\n- Integration suite: <60 seconds.\n- E2E: <5 minutes per critical-path run.\n\nTechniques:\n- **Parallel test runs** (Vitest, pytest-xdist, Go's `-parallel`).\n- **Skip slow tests in watch mode**; run them in CI and pre-push.\n- **Shared test DB** that only re-migrates when schema changes; transactions for isolation.\n- **Mock external APIs** — a real HTTP call in a unit test suite is a bug.\n\n## CI integration\n\nEvery PR runs:\n1. Install deps\n2. Lint\n3. Typecheck\n4. Unit + integration tests\n5. Build\n6. (Optional) E2E against a preview deployment\n\nAll must pass to merge. No \"just this once.\"\n\n## When tests fail in CI but pass locally\n\nThe usual culprits:\n- **Time zone**: tests hardcode times or assume local TZ. Fix: always set `TZ=UTC` in CI; write tests that work in any TZ.\n- **Order dependence**: test A leaves state test B relies on (or fights against). Fix: randomize test order, clean state between tests.\n- **Flaky due to async race**: awaited wrong thing, or `setTimeout`-based waiting. Fix: wait on real signals.\n- **Env var missing in CI**: tests silently used a local default. Fix: validate env on boot, fail loud.\n\n## Test data — fixtures and factories\n\nPrefer **factories** over static fixtures:\n\n```ts\nfunction makeUser(overrides: Partial<User> = {}): User {\n  return {\n    id: randomUUID(),\n    email: `user-${randomUUID()}@test.com`,\n    name: 'Test User',\n    createdAt: new Date(),\n    ...overrides,\n  };\n}\n```\n\nFactories scale to new fields (new required field = update one place). Fixtures rot as the schema evolves.\n\nLibraries: `fishery` (TS), `factory_boy` (Python), `factory` (Go).\n\n## Property-based / fuzz tests (bonus)\n\nFor tricky pure functions (parsers, validators, state machines), property-based tests generate many inputs and check invariants:\n\n```ts\nimport { fc, test } from '@fast-check/vitest';\n\ntest.prop([fc.integer(), fc.integer()])('add is commutative', (a, b) => {\n  expect(add(a, b)).toBe(add(b, a));\n});\n```\n\nTools: `fast-check` (TS), `hypothesis` (Python), Go's built-in `f.Fuzz`.\n\nNot necessary for most app code, but gold for parsers, domain logic, and anything security-sensitive.","readmeExcerpt":"Skill: FullStack Developer Owner: azeem-akram Summary: Acts as a complete full-stack software developer that designs and builds production applications end-to-end by following the Software Development Lifecycle (... Tags: latest:1.0.0 Version history: v1.0.0 | 2026-04-22T21:15:42.312Z | user Initial release of \"Fullstack Developer\" skill for end-to-end application builds. - Provides a comprehensive, step-by-step SDLC","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"GET    /users                 # list (with query params for filtering/pagination)\nPOST   /users                 # create\nGET    /users/{id}            # read one\nPATCH  /users/{id}            # partial update\nDELETE /users/{id}            # delete\n\nGET    /users/{id}/orders     # sub-resource list"},{"language":"json","snippet":"{\n  \"error\": {\n    \"code\": \"VALIDATION_FAILED\",\n    \"message\": \"Human-readable message.\",\n    \"details\": [\n      { \"field\": \"email\", \"issue\": \"already_taken\" }\n    ]\n  }\n}"},{"language":"text","snippet":"GET /posts?limit=20&cursor=eyJpZCI6MTIzfQ==\nResponse:\n{\n  \"data\": [...],\n  \"next_cursor\": \"eyJpZCI6MTQzfQ==\",\n  \"has_more\": true\n}"},{"language":"text","snippet":"GET /posts?page=2&page_size=20\nResponse:\n{\n  \"data\": [...],\n  \"page\": 2,\n  \"page_size\": 20,\n  \"total\": 847\n}"},{"language":"text","snippet":"POST /payments\nIdempotency-Key: user-session-abc-attempt-1\nBody: { amount: 100, ... }"},{"language":"text","snippet":"X-RateLimit-Limit: 100\nX-RateLimit-Remaining: 47\nX-RateLimit-Reset: 1712345678\nRetry-After: 30"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: fullstack-developer\ndescription: Acts as a complete full-stack software developer that designs and builds production applications end-to-end by following the Software Development Lifecycle (SDLC). Use this skill whenever the user asks to build, scaffold, or design an application, website, SaaS product, CRUD app, dashboard, API service, multi-tier system, or anything that spans frontend + backend + database — even if they don't explicitly say \"full-stack.\" Also trigger for requests like \"build me an app that does X,\" \"create a website for Y,\" \"I need a tool that lets users Z,\" \"turn this idea into working code,\" or any scope that requires coordinated frontend, backend, data, and deployment decisions. Covers React/Next.js/Vue/Svelte, Node/Python/Go/Rust backends, SQL/NoSQL databases, REST/GraphQL APIs, authentication, Docker, CI/CD, cloud deployment, testing, security, and observability.\n---\n\n# Full-Stack Developer\n\nYou are acting as an experienced full-stack engineer. Your job is to take a user's idea — whether a vague sentence or a detailed spec — and move it through the Software Development Lifecycle into a working, deployable application. This skill defines **how** you operate, not just **what** to build.\n\n## Core operating principles\n\n1. **Don't skip the lifecycle.** Jumping straight to code on a non-trivial app produces rework. Even a five-minute requirements pass saves hours of refactoring. Scale the rigor to the size of the project — a weekend prototype doesn't need a formal architecture doc, but it does need at least one sentence about what it must do and who uses it.\n2. **Work in vertical slices.** Build one thin end-to-end path (e.g., a single feature from UI → API → DB → deploy) before broadening. This surfaces integration problems early and gives the user something runnable at every step.\n3. **Pick boring, proven tools by default.** Novel stacks are liabilities for most apps. Deviate only when the user asks, or when the problem genuinely demands it.\n4. **Make the app runnable locally before anything else.** A README with `npm install && npm run dev` (or equivalent) that actually works is worth more than 1000 lines of unused code.\n5. **Security, testing, and observability are not \"later\" tasks.** Wire them in during implementation — bolting them on afterward is how real vulnerabilities ship.\n\n## The SDLC workflow you follow\n\nFor every non-trivial build request, move through these seven phases in order. You may compress phases (a small project might do Requirements + Planning + Design in one short response), but never skip the thinking behind them.\n\n### Phase 1 — Requirements Analysis\n\nBefore writing any code, answer:\n- **Who are the users?** (end users, internal team, public, yourself)\n- **What must the app do?** (3–7 bullet functional requirements)\n- **What must it NOT do?** (explicit non-goals prevent scope creep)\n- **Non-functional requirements**: expected traffic, latency, data volume, compliance (GDPR, HIPAA, PCI), offlin"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn7a8ekj5emmr1j5yeqpb5f4ys85bg9h\",\n  \"slug\": \"claw-fullstack-developer\",\n  \"version\": \"1.0.0\",\n  \"publishedAt\": 1776892542312\n}"},{"path":"references/api-design.md","content":"# API Design\n\nGuidance for designing REST and GraphQL APIs that age well.\n\n## REST vs. GraphQL — how to choose\n\n**Default to REST.** It's simpler, better-cached, easier to debug, and matches HTTP semantics. Most apps need REST.\n\nPick GraphQL when:\n- Multiple clients (web, iOS, Android) have genuinely different data needs from the same backend\n- The app has deeply nested data and REST endpoints are proliferating into N+M mess\n- A team has strong GraphQL experience already\n\nDon't pick GraphQL for:\n- A public API (the resolver N+1 problem and caching story are hard)\n- A small app with one frontend (overkill — REST is faster to build)\n\ntRPC is a third option for monorepos where frontend and backend share types. It's fantastic for this case — you get end-to-end type safety without the GraphQL overhead.\n\n## REST design\n\n### URL structure\n- Resources are **nouns, plural**: `/users`, `/orders`, not `/getUsers` or `/user`.\n- Use HTTP methods correctly: `GET` (read, idempotent, cacheable), `POST` (create), `PUT` (full replace), `PATCH` (partial update), `DELETE` (remove).\n- Nest when there's a true parent-child: `/orders/{id}/items`. Don't nest three levels deep — `/orgs/{oid}/projects/{pid}/tasks/{tid}` is a maintenance burden. Prefer `/tasks/{tid}` with scope enforced by auth.\n\n### Path patterns\n```\nGET    /users                 # list (with query params for filtering/pagination)\nPOST   /users                 # create\nGET    /users/{id}            # read one\nPATCH  /users/{id}            # partial update\nDELETE /users/{id}            # delete\n\nGET    /users/{id}/orders     # sub-resource list\n```\n\n### Status codes — use them correctly\n- **200** OK — successful read or update with body returned\n- **201** Created — successful creation; include the new resource in the body and a `Location` header\n- **204** No Content — successful operation with no body (e.g., DELETE)\n- **400** Bad Request — malformed request or validation failure\n- **401** Unauthorized — not authenticated\n- **403** Forbidden — authenticated but not allowed\n- **404** Not Found — resource doesn't exist (or authed user can't see it — don't leak existence)\n- **409** Conflict — state conflict (duplicate email, version mismatch)\n- **422** Unprocessable Entity — validation failure (some APIs prefer this over 400)\n- **429** Too Many Requests — rate limited\n- **500** Internal Server Error — server bug (log it, page oncall)\n- **503** Service Unavailable — temporarily down\n\nDon't return 200 with `{\"error\": \"...\"}`. Use the HTTP status. Clients rely on it for retry logic and error handling.\n\n### Error response shape\nPick one shape and stick to it across every endpoint:\n```json\n{\n  \"error\": {\n    \"code\": \"VALIDATION_FAILED\",\n    \"message\": \"Human-readable message.\",\n    \"details\": [\n      { \"field\": \"email\", \"issue\": \"already_taken\" }\n    ]\n  }\n}\n```\n\nThe `code` is machine-readable (clients switch on it). The `message` is for humans/logs. `details` is optional structured info.\n\n### Pagination\nTwo styles"},{"path":"references/authentication.md","content":"# Authentication & Authorization\n\nAuth is where apps get compromised. Default to proven libraries and infrastructure; roll your own only when you have to.\n\n## Use a library. Seriously.\n\nBad: writing your own password hashing, session management, or OAuth flow.\nGood: using one of:\n\n| Option | Best for |\n|---|---|\n| **Clerk** | Fastest to ship. Good UI components. Paid after free tier. |\n| **Auth.js (NextAuth)** | Open source, flexible, works with Next.js natively. DIY UI. |\n| **Supabase Auth** | Bundled with Supabase DB. Good if you're already on Supabase. |\n| **Auth0 / Okta** | Enterprise, SSO-heavy, compliance-heavy use cases. |\n| **Lucia** | Lightweight, library-style, good if you want control without reinventing crypto. |\n| **Passport.js** | Node ecosystem standard, lots of strategies. Lower-level. |\n| **FusionAuth / Keycloak** | Self-hosted, full-featured, operationally heavier. |\n\nPick based on constraints:\n- **Hosted or self-hosted?** Hosted (Clerk/Auth0) is faster; self-hosted (Lucia, Keycloak) gives you full control of user data.\n- **Does the user data need to live in your DB?** If yes → Lucia / Auth.js / Supabase. If no → Clerk / Auth0 are fine.\n- **Do you need SSO/SAML for enterprise customers?** Auth0 / WorkOS / Clerk's enterprise tier.\n\n## Authentication flows\n\n### Username + password\nStill the most common. Must include:\n- **Strong password hashing**: argon2id (preferred), or bcrypt with cost factor 12+. Never MD5, SHA-1, SHA-256 alone, or anything custom.\n- **Email verification** before allowing login for sensitive apps.\n- **Password reset**: email-delivered time-limited one-time token. Token expires in 15–60 min, single-use, invalidates on use.\n- **Breach checks**: integrate with Have I Been Pwned API or similar to reject known-breached passwords at signup.\n- **Rate limiting** on login and password reset endpoints.\n\n### OAuth / Social login\n\"Sign in with Google/GitHub/Apple.\" Use a library — the flow has too many security-critical details (PKCE, state, nonce) to get right manually.\n- **Always validate the state parameter** to prevent CSRF.\n- **Use PKCE** for public clients (SPAs, mobile).\n- **Account linking**: decide how you handle a user who signs up with email, then later tries to log in with Google using the same email. (Usually: link automatically if email is verified on both sides, or prompt the user.)\n\n### Magic links (passwordless email)\nEasy to implement, reduces password fatigue. Downsides: dependent on email delivery, no offline access, more friction per login than a saved password.\n- **Tokens are short-lived** (15 min) and single-use.\n- **Rate limit** link requests per email.\n\n### Passkeys / WebAuthn\nThe future of auth. Native support in all modern browsers. Libraries (SimpleWebAuthn, Clerk, Supabase) make this straightforward.\n\n### SSO (SAML, OIDC)\nFor enterprise customers. Use WorkOS, Auth0, or Keycloak. Don't implement SAML from scratch — the spec is a minefield.\n\n### Multi-factor authentication (MFA)\n- **TOTP** (Goog"},{"path":"references/backend-stacks.md","content":"# Backend Stacks\n\nPatterns and defaults for the major backend runtimes.\n\n## Choosing a backend\n\n| If you need... | Pick |\n|---|---|\n| Fast iteration, same-repo as Next.js, moderate load | **Next.js route handlers / API routes** |\n| Standalone Node service, serious throughput | **Fastify** or **NestJS** |\n| Python ecosystem (ML, data, scientific) | **FastAPI** |\n| Full-featured framework with ORM and admin | **Django** or **Ruby on Rails** |\n| High concurrency, low memory, strict typing | **Go** (stdlib + chi or Gin) |\n| Maximum performance, strong type safety | **Rust** (axum or actix-web) |\n| Real-time / WebSocket-heavy | Node with Socket.IO, or Elixir/Phoenix for truly massive scale |\n\nDefault: **Next.js route handlers** for small/medium apps (frontend + backend in one repo), **Fastify** or **FastAPI** for standalone services.\n\n## Universal backend principles\n\n- **Input validation at the boundary.** Every request body, query param, and path param gets validated before it touches your business logic. Use Zod (Node/TS), Pydantic (Python), or struct tags + validator (Go).\n- **Structured errors.** Return JSON like `{\"error\": {\"code\": \"USER_NOT_FOUND\", \"message\": \"...\"}}`. Never leak stack traces or raw DB errors to clients.\n- **Don't put business logic in the route handler.** Route handler parses input → calls a service function → formats the response. The service is what you unit-test.\n- **Database connection pooling.** Instantiate the pool once; never `new Client()` per request.\n- **Transactions around multi-step writes.** Partial writes cause data corruption nightmares.\n- **Idempotency for destructive or billable operations.** Use idempotency keys on payment creation, emails, etc.\n- **Rate limiting** on auth endpoints at minimum. `express-rate-limit`, `@fastify/rate-limit`, `slowapi` for FastAPI, or a reverse proxy (Cloudflare, nginx).\n- **CORS** configured explicitly. Default-deny, allow specific origins.\n- **Secrets via environment variables**, loaded through a validated config module. The config module crashes the app on missing secrets — no silent fallbacks.\n\n## Node.js — Fastify (recommended for standalone)\n\n### Why Fastify over Express\n- 2–3× faster under load\n- Native schema validation (no extra middleware)\n- Better TypeScript support\n- Plugin-based architecture that scales to large codebases\n- Active maintenance\n\nExpress is fine for legacy reasons but don't start new projects with it in 2026.\n\n### Project structure\n```\nsrc/\n  server.ts              # Fastify instance, register plugins\n  config.ts              # env var validation (Zod)\n  plugins/               # auth, DB, rate limiting\n  modules/\n    users/\n      users.routes.ts    # HTTP layer\n      users.service.ts   # business logic\n      users.repo.ts      # DB access\n      users.schema.ts    # Zod schemas\n      users.test.ts\n    orders/\n      ...\n  lib/\n    db.ts                # Prisma or Drizzle client singleton\n    logger.ts            # pino instance\n```\n\n### Example route (Fast"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"Acts as a complete full-stack software developer that designs and builds production applications end-to-end by following the Software Development Lifecycle (... Skill: FullStack Developer Owner: azeem-akram Summary: Acts as a complete full-stack software developer that designs and builds production applications end-to-end by following the Software Development Lifecycle (... Tags: latest:1.0.0 Version history: v1.0.0 | 2026-04-22T21:15:42.312Z | user Initial release of \"Fullstack Developer\" skill for end-to-end application builds. - Provides a comprehensive, step-by-step SDLC","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":2038,"uniquenessScore":53,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-11T15:14:39.526Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-11T15:14:39.526Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-11T17:41:15.927Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}