[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M797H4YHZ8CMS08EZR3G8N2V":3,"skill-same:01M797H4YHZ8CMS08EZR3G8N2V":92},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":6,"ownerHtmlUrl":42,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":43,"install":44,"resources":57},"01M797H4YHZ8CMS08EZR3G8N2V","fullstack-dev",null,"Full-stack backend architecture and frontend-backend integration guide.\nTRIGGER when: building a full-stack app, creating REST API with frontend, scaffolding backend service,\nbuilding todo app, building CRUD app, building real-time app, building chat app,\nExpress + React, Next.js API, Node.js backend, Python backend, Go backend,\ndesigning service layers, implementing error handling, managing config\u002Fauth,\nsetting up API clients, implementing auth flows, handling file uploads,\nadding real-time features (SSE\u002FWebSocket), hardening for production.\nDO NOT TRIGGER when: pure frontend UI work, pure CSS\u002Fstyling, database schema only.","ahang1598\u002Fdoubao-workbuddy-qwenwork-skills","ahang1598","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F29569469?v=4","01M787BTDDPJN7G0C9TC9SQ85J","01M787BTE3YMSPS4EBYF2MCE1Z",98,"MIT","https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fexperts\u002Fsenior-developer\u002Fskills\u002Ffullstack-dev\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\r\nname: fullstack-dev\r\ndescription: |\r\n  Full-stack backend architecture and frontend-backend integration guide.\r\n  TRIGGER when: building a full-stack app, creating REST API with frontend, scaffolding backend service,\r\n  building todo app, building CRUD app, building real-time app, building chat app,\r\n  Express + React, Next.js API, Node.js backend, Python backend, Go backend,\r\n  designing service layers, implementing error handling, managing config\u002Fauth,\r\n  setting up API clients, implementing auth flows, handling file uploads,\r\n  adding real-time features (SSE\u002FWebSocket), hardening for production.\r\n  DO NOT TRIGGER when: pure frontend UI work, pure CSS\u002Fstyling, database schema only.\r\ndescription_zh: \"全栈应用架构与开发指南\"\r\ndescription_en: \"Full-stack architecture guide (REST API, Express, React, Next.js)\"\r\nlicense: MIT\r\nmetadata:\r\n  category: full-stack\r\n  version: \"1.0.0\"\r\n  sources:\r\n    - The Twelve-Factor App (12factor.net)\r\n    - Clean Architecture (Robert C. Martin)\r\n    - Domain-Driven Design (Eric Evans)\r\n    - Patterns of Enterprise Application Architecture (Martin Fowler)\r\n    - Martin Fowler (Testing Pyramid, Contract Tests)\r\n    - Google SRE Handbook (Release Engineering)\r\n    - ThoughtWorks Technology Radar\r\n---\r\n\r\n# Full-Stack Development Practices\r\n\r\n## MANDATORY WORKFLOW — Follow These Steps In Order\r\n\r\n**When this skill is triggered, you MUST follow this workflow before writing any code.**\r\n\r\n### Step 0: Gather Requirements\r\n\r\nBefore scaffolding anything, ask the user to clarify (or infer from context):\r\n\r\n1. **Stack**: Language\u002Fframework for backend and frontend (e.g., Express + React, Django + Vue, Go + HTMX)\r\n2. **Service type**: API-only, full-stack monolith, or microservice?\r\n3. **Database**: SQL (PostgreSQL, SQLite, MySQL) or NoSQL (MongoDB, Redis)?\r\n4. **Integration**: REST, GraphQL, tRPC, or gRPC?\r\n5. **Real-time**: Needed? If yes — SSE, WebSocket, or polling?\r\n6. **Auth**: Needed? If yes — JWT, session, OAuth, or third-party (Clerk, Auth.js)?\r\n\r\nIf the user has already specified these in their request, skip asking and proceed.\r\n\r\n### Step 1: Architectural Decisions\r\n\r\nBased on requirements, make and state these decisions before coding:\r\n\r\n| Decision | Options | Reference |\r\n|----------|---------|-----------|\r\n| Project structure | Feature-first (recommended) vs layer-first | [Section 1](#1-project-structure--layering-critical) |\r\n| API client approach | Typed fetch \u002F React Query \u002F tRPC \u002F OpenAPI codegen | [Section 5](#5-api-client-patterns-medium) |\r\n| Auth strategy | JWT + refresh \u002F session \u002F third-party | [Section 6](#6-authentication--middleware-high) |\r\n| Real-time method | Polling \u002F SSE \u002F WebSocket | [Section 11](#11-real-time-patterns-medium) |\r\n| Error handling | Typed error hierarchy + global handler | [Section 3](#3-error-handling--resilience-high) |\r\n\r\nBriefly explain each choice (1 sentence per decision).\r\n\r\n### Step 2: Scaffold with Checklist\r\n\r\nUse the appropriate checklist below. Ensure ALL checked items are implemented — do not skip any.\r\n\r\n### Step 3: Implement Following Patterns\r\n\r\nWrite code following the patterns in this document. Reference specific sections as you implement each part.\r\n\r\n### Step 4: Test & Verify\r\n\r\nAfter implementation, run these checks before claiming completion:\r\n\r\n1. **Build check**: Ensure both backend and frontend compile without errors\r\n   ```bash\r\n   # Backend\r\n   cd server && npm run build\r\n   # Frontend\r\n   cd client && npm run build\r\n   ```\r\n2. **Start & smoke test**: Start the server, verify key endpoints return expected responses\r\n   ```bash\r\n   # Start server, then test\r\n   curl http:\u002F\u002Flocalhost:3000\u002Fhealth\r\n   curl http:\u002F\u002Flocalhost:3000\u002Fapi\u002F\u003Cresource>\r\n   ```\r\n3. **Integration check**: Verify frontend can connect to backend (CORS, API base URL, auth flow)\r\n4. **Real-time check** (if applicable): Open two browser tabs, verify changes sync\r\n\r\nIf any check fails, fix the issue before proceeding.\r\n\r\n### Step 5: Handoff Summary\r\n\r\nProvide a brief summary to the user:\r\n\r\n- **What was built**: List of implemented features and endpoints\r\n- **How to run**: Exact commands to start backend and frontend\r\n- **What's missing \u002F next steps**: Any deferred items, known limitations, or recommended improvements\r\n- **Key files**: List the most important files the user should know about\r\n\r\n---\r\n\r\n## Scope\r\n\r\n**USE this skill when:**\r\n- Building a full-stack application (backend + frontend)\r\n- Scaffolding a new backend service or API\r\n- Designing service layers and module boundaries\r\n- Implementing database access, caching, or background jobs\r\n- Writing error handling, logging, or configuration management\r\n- Reviewing backend code for architectural issues\r\n- Hardening for production\r\n- Setting up API clients, auth flows, file uploads, or real-time features\r\n\r\n**NOT for:**\r\n- Pure frontend\u002FUI concerns (use your frontend framework's docs)\r\n- Pure database schema design without backend context\r\n\r\n---\r\n\r\n## Quick Start — New Backend Service Checklist\r\n\r\n- [ ] Project scaffolded with **feature-first** structure\r\n- [ ] Configuration **centralized**, env vars **validated at startup** (fail fast)\r\n- [ ] **Typed error hierarchy** defined (not generic `Error`)\r\n- [ ] **Global error handler** middleware\r\n- [ ] **Structured JSON logging** with request ID propagation\r\n- [ ] Database: **migrations** set up, **connection pooling** configured\r\n- [ ] **Input validation** on all endpoints (Zod \u002F Pydantic \u002F Go validator)\r\n- [ ] **Authentication middleware** in place\r\n- [ ] **Health check** endpoints (`\u002Fhealth`, `\u002Fready`)\r\n- [ ] **Graceful shutdown** handling (SIGTERM)\r\n- [ ] **CORS** configured (explicit origins, not `*`)\r\n- [ ] **Security headers** (helmet or equivalent)\r\n- [ ] `.env.example` committed (no real secrets)\r\n\r\n## Quick Start — Frontend-Backend Integration Checklist\r\n\r\n- [ ] **API client** configured (typed fetch wrapper, React Query, tRPC, or OpenAPI generated)\r\n- [ ] **Base URL** from environment variable (not hardcoded)\r\n- [ ] **Auth token** attached to requests automatically (interceptor \u002F middleware)\r\n- [ ] **Error handling** — API errors mapped to user-facing messages\r\n- [ ] **Loading states** handled (skeleton\u002Fspinner, not blank screen)\r\n- [ ] **Type safety** across the boundary (shared types, OpenAPI, or tRPC)\r\n- [ ] **CORS** configured with explicit origins (not `*` in production)\r\n- [ ] **Refresh token** flow implemented (httpOnly cookie + transparent retry on 401)\r\n\r\n---\r\n\r\n## Quick Navigation\r\n\r\n| Need to… | Jump to |\r\n|----------|---------|\r\n| Organize project folders | [1. Project Structure](#1-project-structure--layering-critical) |\r\n| Manage config + secrets | [2. Configuration](#2-configuration--environment-critical) |\r\n| Handle errors properly | [3. Error Handling](#3-error-handling--resilience-high) |\r\n| Write database code | [4. Database Access Patterns](#4-database-access-patterns-high) |\r\n| Set up API client from frontend | [5. API Client Patterns](#5-api-client-patterns-medium) |\r\n| Add auth middleware | [6. Auth & Middleware](#6-authentication--middleware-high) |\r\n| Set up logging | [7. Logging & Observability](#7-logging--observability-medium-high) |\r\n| Add background jobs | [8. Background Jobs](#8-background-jobs--async-medium) |\r\n| Implement caching | [9. Caching](#9-caching-patterns-medium) |\r\n| Upload files (presigned URL, multipart) | [10. File Upload Patterns](#10-file-upload-patterns-medium) |\r\n| Add real-time features (SSE, WebSocket) | [11. Real-Time Patterns](#11-real-time-patterns-medium) |\r\n| Handle API errors in frontend UI | [12. Cross-Boundary Error Handling](#12-cross-boundary-error-handling-medium) |\r\n| Harden for production | [13. Production Hardening](#13-production-hardening-medium) |\r\n| Design API endpoints | [API Design](references\u002Fapi-design.md) |\r\n| Design database schema | [Database Schema](references\u002Fdb-schema.md) |\r\n| Auth flow (JWT, refresh, Next.js SSR, RBAC) | [references\u002Fauth-flow.md](references\u002Fauth-flow.md) |\r\n| CORS, env vars, environment management | [references\u002Fenvironment-management.md](references\u002Fenvironment-management.md) |\r\n\r\n---\r\n\r\n## Core Principles (7 Iron Rules)\r\n\r\n```\r\n1. ✅ Organize by FEATURE, not by technical layer\r\n2. ✅ Controllers never contain business logic\r\n3. ✅ Services never import HTTP request\u002Fresponse types\r\n4. ✅ All config from env vars, validated at startup, fail fast\r\n5. ✅ Every error is typed, logged, and returns consistent format\r\n6. ✅ All input validated at the boundary — trust nothing from client\r\n7. ✅ Structured JSON logging with request ID — not console.log\r\n```\r\n\r\n---\r\n\r\n## 1. Project Structure & Layering (CRITICAL)\r\n\r\n### Feature-First Organization\r\n\r\n```\r\n✅ Feature-first                    ❌ Layer-first\r\nsrc\u002F                                src\u002F\r\n  orders\u002F                             controllers\u002F\r\n    order.controller.ts                 order.controller.ts\r\n    order.service.ts                    user.controller.ts\r\n    order.repository.ts               services\u002F\r\n    order.dto.ts                        order.service.ts\r\n    order.test.ts                       user.service.ts\r\n  users\u002F                              repositories\u002F\r\n    user.controller.ts                  ...\r\n    user.service.ts\r\n  shared\u002F\r\n    database\u002F\r\n    middleware\u002F\r\n```\r\n\r\n### Three-Layer Architecture\r\n\r\n```\r\nController (HTTP) → Service (Business Logic) → Repository (Data Access)\r\n```\r\n\r\n| Layer | Responsibility | ❌ Never |\r\n|-------|---------------|---------|\r\n| Controller | Parse request, validate, call service, format response | Business logic, DB queries |\r\n| Service | Business rules, orchestration, transaction mgmt | HTTP types (req\u002Fres), direct DB |\r\n| Repository | Database queries, external API calls | Business logic, HTTP types |\r\n\r\n### Dependency Injection (All Languages)\r\n\r\n**TypeScript:**\r\n```typescript\r\nclass OrderService {\r\n  constructor(\r\n    private readonly orderRepo: OrderRepository,    \u002F\u002F ✅ injected interface\r\n    private readonly emailService: EmailService,\r\n  ) {}\r\n}\r\n```\r\n\r\n**Python:**\r\n```python\r\nclass OrderService:\r\n    def __init__(self, order_repo: OrderRepository, email_service: EmailService):\r\n        self.order_repo = order_repo                 # ✅ injected\r\n        self.email_service = email_service\r\n```\r\n\r\n**Go:**\r\n```go\r\ntype OrderService struct {\r\n    orderRepo    OrderRepository                      \u002F\u002F ✅ interface\r\n    emailService EmailService\r\n}\r\n\r\nfunc NewOrderService(repo OrderRepository, email EmailService) *OrderService {\r\n    return &OrderService{orderRepo: repo, emailService: email}\r\n}\r\n```\r\n\r\n---\r\n\r\n## 2. Configuration & Environment (CRITICAL)\r\n\r\n### Centralized, Typed, Fail-Fast\r\n\r\n**TypeScript:**\r\n```typescript\r\nconst config = {\r\n  port: parseInt(process.env.PORT || '3000', 10),\r\n  database: { url: requiredEnv('DATABASE_URL'), poolSize: intEnv('DB_POOL_SIZE', 10) },\r\n  auth: { jwtSecret: requiredEnv('JWT_SECRET'), expiresIn: process.env.JWT_EXPIRES_IN || '1h' },\r\n} as const;\r\n\r\nfunction requiredEnv(name: string): string {\r\n  const value = process.env[name];\r\n  if (!value) throw new Error(`Missing required env var: ${name}`);  \u002F\u002F fail fast\r\n  return value;\r\n}\r\n```\r\n\r\n**Python:**\r\n```python\r\nfrom pydantic_settings import BaseSettings\r\n\r\nclass Settings(BaseSettings):\r\n    database_url: str                        # required — app won't start without it\r\n    jwt_secret: str                          # required\r\n    port: int = 3000                         # optional with default\r\n    db_pool_size: int = 10\r\n    class Config:\r\n        env_file = \".env\"\r\n\r\nsettings = Settings()                        # fails fast if DATABASE_URL missing\r\n```\r\n\r\n### Rules\r\n\r\n```\r\n✅ All config via environment variables (Twelve-Factor)\r\n✅ Validate required vars at startup — fail fast\r\n✅ Type-cast at config layer, not at usage sites\r\n✅ Commit .env.example with dummy values\r\n\r\n❌ Never hardcode secrets, URLs, or credentials\r\n❌ Never commit .env files\r\n❌ Never scatter process.env \u002F os.environ throughout code\r\n```\r\n\r\n---\r\n\r\n## 3. Error Handling & Resilience (HIGH)\r\n\r\n### Typed Error Hierarchy\r\n\r\n```typescript\r\n\u002F\u002F Base (TypeScript)\r\nclass AppError extends Error {\r\n  constructor(\r\n    message: string,\r\n    public readonly code: string,\r\n    public readonly statusCode: number,\r\n    public readonly isOperational: boolean = true,\r\n  ) { super(message); }\r\n}\r\nclass NotFoundError extends AppError {\r\n  constructor(resource: string, id: string) {\r\n    super(`${resource} not found: ${id}`, 'NOT_FOUND', 404);\r\n  }\r\n}\r\nclass ValidationError extends AppError {\r\n  constructor(public readonly errors: FieldError[]) {\r\n    super('Validation failed', 'VALIDATION_ERROR', 422);\r\n  }\r\n}\r\n```\r\n\r\n```python\r\n# Base (Python)\r\nclass AppError(Exception):\r\n    def __init__(self, message: str, code: str, status_code: int):\r\n        self.message, self.code, self.status_code = message, code, status_code\r\n\r\nclass NotFoundError(AppError):\r\n    def __init__(self, resource: str, id: str):\r\n        super().__init__(f\"{resource} not found: {id}\", \"NOT_FOUND\", 404)\r\n```\r\n\r\n### Global Error Handler\r\n\r\n```typescript\r\n\u002F\u002F TypeScript (Express)\r\napp.use((err, req, res, next) => {\r\n  if (err instanceof AppError && err.isOperational) {\r\n    return res.status(err.statusCode).json({\r\n      title: err.code, status: err.statusCode,\r\n      detail: err.message, request_id: req.id,\r\n    });\r\n  }\r\n  logger.error('Unexpected error', { error: err.message, stack: err.stack, request_id: req.id });\r\n  res.status(500).json({ title: 'Internal Error', status: 500, request_id: req.id });\r\n});\r\n```\r\n\r\n### Rules\r\n\r\n```\r\n✅ Typed, domain-specific error classes\r\n✅ Global error handler catches everything\r\n✅ Operational errors → structured response\r\n✅ Programming errors → log + generic 500\r\n✅ Retry transient failures with exponential backoff\r\n\r\n❌ Never catch and ignore errors silently\r\n❌ Never return stack traces to client\r\n❌ Never throw generic Error('something')\r\n```\r\n\r\n---\r\n\r\n## 4. Database Access Patterns (HIGH)\r\n\r\n### Migrations Always\r\n\r\n```bash\r\n# TypeScript (Prisma)           # Python (Alembic)              # Go (golang-migrate)\r\nnpx prisma migrate dev          alembic revision --autogenerate  migrate -source file:\u002F\u002Fmigrations\r\nnpx prisma migrate deploy       alembic upgrade head             migrate -database $DB up\r\n```\r\n\r\n```\r\n✅ Schema changes via migrations, never manual SQL\r\n✅ Migrations must be reversible\r\n✅ Review migration SQL before production\r\n❌ Never modify production schema manually\r\n```\r\n\r\n### N+1 Prevention\r\n\r\n```typescript\r\n\u002F\u002F ❌ N+1: 1 query + N queries\r\nconst orders = await db.order.findMany();\r\nfor (const o of orders) { o.items = await db.item.findMany({ where: { orderId: o.id } }); }\r\n\r\n\u002F\u002F ✅ Single JOIN query\r\nconst orders = await db.order.findMany({ include: { items: true } });\r\n```\r\n\r\n### Transactions for Multi-Step Writes\r\n\r\n```typescript\r\nawait db.$transaction(async (tx) => {\r\n  const order = await tx.order.create({ data: orderData });\r\n  await tx.inventory.decrement({ productId, quantity });\r\n  await tx.payment.create({ orderId: order.id, amount });\r\n});\r\n```\r\n\r\n### Connection Pooling\r\n\r\nPool size = `(CPU cores × 2) + spindle_count` (start with 10-20). Always set connection timeout. Use PgBouncer for serverless.\r\n\r\n---\r\n\r\n## 5. API Client Patterns (MEDIUM)\r\n\r\nThe \"glue layer\" between frontend and backend. Choose the approach that fits your team and stack.\r\n\r\n### Option A: Typed Fetch Wrapper (Simple, No Dependencies)\r\n\r\n```typescript\r\n\u002F\u002F lib\u002Fapi-client.ts\r\nconst BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http:\u002F\u002Flocalhost:3001';\r\n\r\nclass ApiError extends Error {\r\n  constructor(public status: number, public body: any) {\r\n    super(body?.detail || body?.message || `API error ${status}`);\r\n  }\r\n}\r\n\r\nasync function api\u003CT>(path: string, options: RequestInit = {}): Promise\u003CT> {\r\n  const token = getAuthToken();  \u002F\u002F from cookie \u002F memory \u002F context\r\n\r\n  const res = await fetch(`${BASE_URL}${path}`, {\r\n    ...options,\r\n    headers: {\r\n      'Content-Type': 'application\u002Fjson',\r\n      ...(token ? { Authorization: `Bearer ${token}` } : {}),\r\n      ...options.headers,\r\n    },\r\n  });\r\n\r\n  if (!res.ok) {\r\n    const body = await res.json().catch(() => null);\r\n    throw new ApiError(res.status, body);\r\n  }\r\n\r\n  if (res.status === 204) return undefined as T;\r\n  return res.json();\r\n}\r\n\r\nexport const apiClient = {\r\n  get: \u003CT>(path: string) => api\u003CT>(path),\r\n  post: \u003CT>(path: string, data: unknown) => api\u003CT>(path, { method: 'POST', body: JSON.stringify(data) }),\r\n  put: \u003CT>(path: string, data: unknown) => api\u003CT>(path, { method: 'PUT', body: JSON.stringify(data) }),\r\n  patch: \u003CT>(path: string, data: unknown) => api\u003CT>(path, { method: 'PATCH', body: JSON.stringify(data) }),\r\n  delete: \u003CT>(path: string) => api\u003CT>(path, { method: 'DELETE' }),\r\n};\r\n```\r\n\r\n### Option B: React Query + Typed Client (Recommended for React)\r\n\r\n```typescript\r\n\u002F\u002F hooks\u002Fuse-orders.ts\r\nimport { useQuery, useMutation, useQueryClient } from '@tanstack\u002Freact-query';\r\nimport { apiClient } from '@\u002Flib\u002Fapi-client';\r\n\r\ninterface Order { id: string; total: number; status: string; }\r\ninterface CreateOrderInput { items: { productId: string; quantity: number }[] }\r\n\r\nexport function useOrders() {\r\n  return useQuery({\r\n    queryKey: ['orders'],\r\n    queryFn: () => apiClient.get\u003C{ data: Order[] }>('\u002Fapi\u002Forders'),\r\n    staleTime: 1000 * 60,  \u002F\u002F 1 min\r\n  });\r\n}\r\n\r\nexport function useCreateOrder() {\r\n  const queryClient = useQueryClient();\r\n  return useMutation({\r\n    mutationFn: (data: CreateOrderInput) =>\r\n      apiClient.post\u003C{ data: Order }>('\u002Fapi\u002Forders', data),\r\n    onSuccess: () => {\r\n      queryClient.invalidateQueries({ queryKey: ['orders'] });\r\n    },\r\n  });\r\n}\r\n\r\n\u002F\u002F Usage in component:\r\nfunction OrdersPage() {\r\n  const { data, isLoading, error } = useOrders();\r\n  const createOrder = useCreateOrder();\r\n  if (isLoading) return \u003CSkeleton \u002F>;\r\n  if (error) return \u003CErrorBanner error={error} \u002F>;\r\n  \u002F\u002F ...\r\n}\r\n```\r\n\r\n### Option C: tRPC (Same Team Owns Both Sides)\r\n\r\n```typescript\r\n\u002F\u002F server: trpc\u002Frouter.ts\r\nexport const appRouter = router({\r\n  orders: router({\r\n    list: publicProcedure.query(async () => {\r\n      return db.order.findMany({ include: { items: true } });\r\n    }),\r\n    create: protectedProcedure\r\n      .input(z.object({ items: z.array(orderItemSchema) }))\r\n      .mutation(async ({ input, ctx }) => {\r\n        return orderService.create(ctx.user.id, input);\r\n      }),\r\n  }),\r\n});\r\nexport type AppRouter = typeof appRouter;\r\n\r\n\u002F\u002F client: automatic type safety, no code generation\r\nconst { data } = trpc.orders.list.useQuery();\r\nconst createOrder = trpc.orders.create.useMutation();\r\n```\r\n\r\n### Option D: OpenAPI Generated Client (Public \u002F Multi-Consumer APIs)\r\n\r\n```bash\r\nnpx openapi-typescript-codegen \\\r\n  --input http:\u002F\u002Flocalhost:3001\u002Fapi\u002Fopenapi.json \\\r\n  --output src\u002Fgenerated\u002Fapi \\\r\n  --client axios\r\n```\r\n\r\n### Decision: Which API Client?\r\n\r\n| Approach | When | Type Safety | Effort |\r\n|----------|------|-------------|--------|\r\n| Typed fetch wrapper | Simple apps, small teams | Manual types | Low |\r\n| React Query + fetch | React apps, server state | Manual types | Medium |\r\n| tRPC | Same team, TypeScript both sides | Automatic | Low |\r\n| OpenAPI generated | Public API, multi-consumer | Automatic | Medium |\r\n| GraphQL codegen | GraphQL APIs | Automatic | Medium |\r\n\r\n---\r\n\r\n## 6. Authentication & Middleware (HIGH)\r\n\r\n> **Full reference:** [references\u002Fauth-flow.md](references\u002Fauth-flow.md) — JWT bearer flow, automatic token refresh, Next.js server-side auth, RBAC pattern, backend middleware order.\r\n\r\n### Standard Middleware Order\r\n\r\n```\r\nRequest → 1.RequestID → 2.Logging → 3.CORS → 4.RateLimit → 5.BodyParse\r\n       → 6.Auth → 7.Authz → 8.Validation → 9.Handler → 10.ErrorHandler → Response\r\n```\r\n\r\n### JWT Rules\r\n\r\n```\r\n✅ Short expiry access token (15min) + refresh token (server-stored)\r\n✅ Minimal claims: userId, roles (not entire user object)\r\n✅ Rotate signing keys periodically\r\n\r\n❌ Never store tokens in localStorage (XSS risk)\r\n❌ Never pass tokens in URL query params\r\n```\r\n\r\n### RBAC Pattern\r\n\r\n```typescript\r\nfunction authorize(...roles: Role[]) {\r\n  return (req, res, next) => {\r\n    if (!req.user) throw new UnauthorizedError();\r\n    if (!roles.some(r => req.user.roles.includes(r))) throw new ForbiddenError();\r\n    next();\r\n  };\r\n}\r\nrouter.delete('\u002Fusers\u002F:id', authenticate, authorize('admin'), deleteUser);\r\n```\r\n\r\n### Auth Token Automatic Refresh\r\n\r\n```typescript\r\n\u002F\u002F lib\u002Fapi-client.ts — transparent refresh on 401\r\nasync function apiWithRefresh\u003CT>(path: string, options: RequestInit = {}): Promise\u003CT> {\r\n  try {\r\n    return await api\u003CT>(path, options);\r\n  } catch (err) {\r\n    if (err instanceof ApiError && err.status === 401) {\r\n      const refreshed = await api\u003C{ accessToken: string }>('\u002Fapi\u002Fauth\u002Frefresh', {\r\n        method: 'POST',\r\n        credentials: 'include',  \u002F\u002F send httpOnly cookie\r\n      });\r\n      setAuthToken(refreshed.accessToken);\r\n      return api\u003CT>(path, options);  \u002F\u002F retry\r\n    }\r\n    throw err;\r\n  }\r\n}\r\n```\r\n\r\n---\r\n\r\n## 7. Logging & Observability (MEDIUM-HIGH)\r\n\r\n### Structured JSON Logging\r\n\r\n```typescript\r\n\u002F\u002F ✅ Structured — parseable, filterable, alertable\r\nlogger.info('Order created', {\r\n  orderId: order.id, userId: user.id, total: order.total,\r\n  items: order.items.length, duration_ms: Date.now() - startTime,\r\n});\r\n\u002F\u002F Output: {\"level\":\"info\",\"msg\":\"Order created\",\"orderId\":\"ord_123\",...}\r\n\r\n\u002F\u002F ❌ Unstructured — useless at scale\r\nconsole.log(`Order created for user ${user.id} with total ${order.total}`);\r\n```\r\n\r\n### Log Levels\r\n\r\n| Level | When | Production? |\r\n|-------|------|------------|\r\n| error | Requires immediate attention | ✅ Always |\r\n| warn | Unexpected but handled | ✅ Always |\r\n| info | Normal operations, audit trail | ✅ Always |\r\n| debug | Dev troubleshooting | ❌ Dev only |\r\n\r\n### Rules\r\n\r\n```\r\n✅ Request ID in every log entry (propagated via middleware)\r\n✅ Log at layer boundaries (request in, response out, external call)\r\n❌ Never log passwords, tokens, PII, or secrets\r\n❌ Never use console.log in production code\r\n```\r\n\r\n---\r\n\r\n## 8. Background Jobs & Async (MEDIUM)\r\n\r\n### Rules\r\n\r\n```\r\n✅ All jobs must be IDEMPOTENT (same job running twice = same result)\r\n✅ Failed jobs → retry (max 3) → dead letter queue → alert\r\n✅ Workers run as SEPARATE processes (not threads in API server)\r\n\r\n❌ Never put long-running tasks in request handlers\r\n❌ Never assume job runs exactly once\r\n```\r\n\r\n### Idempotent Job Pattern\r\n\r\n```typescript\r\nasync function processPayment(data: { orderId: string }) {\r\n  const order = await orderRepo.findById(data.orderId);\r\n  if (order.paymentStatus === 'completed') return;  \u002F\u002F already processed\r\n  await paymentGateway.charge(order);\r\n  await orderRepo.updatePaymentStatus(order.id, 'completed');\r\n}\r\n```\r\n\r\n---\r\n\r\n## 9. Caching Patterns (MEDIUM)\r\n\r\n### Cache-Aside (Lazy Loading)\r\n\r\n```typescript\r\nasync function getUser(id: string): Promise\u003CUser> {\r\n  const cached = await redis.get(`user:${id}`);\r\n  if (cached) return JSON.parse(cached);\r\n\r\n  const user = await userRepo.findById(id);\r\n  if (!user) throw new NotFoundError('User', id);\r\n\r\n  await redis.set(`user:${id}`, JSON.stringify(user), 'EX', 900);  \u002F\u002F 15min TTL\r\n  return user;\r\n}\r\n```\r\n\r\n### Rules\r\n\r\n```\r\n✅ ALWAYS set TTL — never cache without expiry\r\n✅ Invalidate on write (delete cache key after update)\r\n✅ Use cache for reads, never for authoritative state\r\n\r\n❌ Never cache without TTL (stale data is worse than slow data)\r\n```\r\n\r\n| Data Type | Suggested TTL |\r\n|-----------|---------------|\r\n| User profile | 5-15 min |\r\n| Product catalog | 1-5 min |\r\n| Config \u002F feature flags | 30-60 sec |\r\n| Session | Match session duration |\r\n\r\n---\r\n\r\n## 10. File Upload Patterns (MEDIUM)\r\n\r\n### Option A: Presigned URL (Recommended for Large Files)\r\n\r\n```\r\nClient → GET \u002Fapi\u002Fuploads\u002Fpresign?filename=photo.jpg&type=image\u002Fjpeg\r\nServer → { uploadUrl: \"https:\u002F\u002Fs3...\u002Fpresigned\", fileKey: \"uploads\u002Fabc123.jpg\" }\r\nClient → PUT uploadUrl (direct to S3, bypasses your server)\r\nClient → POST \u002Fapi\u002Fphotos { fileKey: \"uploads\u002Fabc123.jpg\" }  (save reference)\r\n```\r\n\r\n**Backend:**\r\n```typescript\r\napp.get('\u002Fapi\u002Fuploads\u002Fpresign', authenticate, async (req, res) => {\r\n  const { filename, type } = req.query;\r\n  const key = `uploads\u002F${crypto.randomUUID()}-${filename}`;\r\n  const url = await s3.getSignedUrl('putObject', {\r\n    Bucket: process.env.S3_BUCKET, Key: key,\r\n    ContentType: type, Expires: 300,  \u002F\u002F 5 min\r\n  });\r\n  res.json({ uploadUrl: url, fileKey: key });\r\n});\r\n```\r\n\r\n**Frontend:**\r\n```typescript\r\nasync function uploadFile(file: File) {\r\n  const { uploadUrl, fileKey } = await apiClient.get\u003CPresignResponse>(\r\n    `\u002Fapi\u002Fuploads\u002Fpresign?filename=${file.name}&type=${file.type}`\r\n  );\r\n  await fetch(uploadUrl, { method: 'PUT', body: file, headers: { 'Content-Type': file.type } });\r\n  return apiClient.post('\u002Fapi\u002Fphotos', { fileKey });\r\n}\r\n```\r\n\r\n### Option B: Multipart (Small Files \u003C 10MB)\r\n\r\n```typescript\r\n\u002F\u002F Frontend\r\nconst formData = new FormData();\r\nformData.append('file', file);\r\nformData.append('description', 'Profile photo');\r\nconst res = await fetch('\u002Fapi\u002Fupload', { method: 'POST', body: formData });\r\n\u002F\u002F Note: do NOT set Content-Type header — browser sets boundary automatically\r\n```\r\n\r\n### Decision\r\n\r\n| Method | File Size | Server Load | Complexity |\r\n|--------|-----------|-------------|------------|\r\n| Presigned URL | Any (recommended > 5MB) | None (direct to storage) | Medium |\r\n| Multipart | \u003C 10MB | High (streams through server) | Low |\r\n| Chunked \u002F Resumable | > 100MB | Medium | High |\r\n\r\n---\r\n\r\n## 11. Real-Time Patterns (MEDIUM)\r\n\r\n### Option A: Server-Sent Events (SSE) — One-Way Server → Client\r\n\r\nBest for: notifications, live feeds, streaming AI responses.\r\n\r\n**Backend (Express):**\r\n```typescript\r\napp.get('\u002Fapi\u002Fevents', authenticate, (req, res) => {\r\n  res.writeHead(200, {\r\n    'Content-Type': 'text\u002Fevent-stream',\r\n    'Cache-Control': 'no-cache',\r\n    Connection: 'keep-alive',\r\n  });\r\n  const send = (event: string, data: unknown) => {\r\n    res.write(`event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`);\r\n  };\r\n  const unsubscribe = eventBus.subscribe(req.user.id, (event) => {\r\n    send(event.type, event.payload);\r\n  });\r\n  req.on('close', () => unsubscribe());\r\n});\r\n```\r\n\r\n**Frontend:**\r\n```typescript\r\nfunction useServerEvents(userId: string) {\r\n  useEffect(() => {\r\n    const source = new EventSource(`\u002Fapi\u002Fevents?userId=${userId}`);\r\n    source.addEventListener('notification', (e) => {\r\n      showToast(JSON.parse(e.data).message);\r\n    });\r\n    source.onerror = () => { source.close(); setTimeout(() => \u002F* reconnect *\u002F, 3000); };\r\n    return () => source.close();\r\n  }, [userId]);\r\n}\r\n```\r\n\r\n### Option B: WebSocket — Bidirectional\r\n\r\nBest for: chat, collaborative editing, gaming.\r\n\r\n**Backend (ws library):**\r\n```typescript\r\nimport { WebSocketServer } from 'ws';\r\nconst wss = new WebSocketServer({ server: httpServer, path: '\u002Fws' });\r\nwss.on('connection', (ws, req) => {\r\n  const userId = authenticateWs(req);\r\n  if (!userId) { ws.close(4001, 'Unauthorized'); return; }\r\n  ws.on('message', (raw) => handleMessage(userId, JSON.parse(raw.toString())));\r\n  ws.on('close', () => cleanupUser(userId));\r\n  const interval = setInterval(() => ws.ping(), 30000);\r\n  ws.on('pong', () => { \u002F* alive *\u002F });\r\n  ws.on('close', () => clearInterval(interval));\r\n});\r\n```\r\n\r\n**Frontend:**\r\n```typescript\r\nfunction useWebSocket(url: string) {\r\n  const [ws, setWs] = useState\u003CWebSocket | null>(null);\r\n  useEffect(() => {\r\n    const socket = new WebSocket(url);\r\n    socket.onopen = () => setWs(socket);\r\n    socket.onclose = () => setTimeout(() => \u002F* reconnect *\u002F, 3000);\r\n    return () => socket.close();\r\n  }, [url]);\r\n  const send = useCallback((data: unknown) => ws?.send(JSON.stringify(data)), [ws]);\r\n  return { ws, send };\r\n}\r\n```\r\n\r\n### Option C: Polling (Simplest, No Infrastructure)\r\n\r\n```typescript\r\nfunction useOrderStatus(orderId: string) {\r\n  return useQuery({\r\n    queryKey: ['order-status', orderId],\r\n    queryFn: () => apiClient.get\u003COrder>(`\u002Fapi\u002Forders\u002F${orderId}`),\r\n    refetchInterval: (query) => {\r\n      if (query.state.data?.status === 'completed') return false;\r\n      return 5000;\r\n    },\r\n  });\r\n}\r\n```\r\n\r\n### Decision\r\n\r\n| Method | Direction | Complexity | When |\r\n|--------|-----------|------------|------|\r\n| Polling | Client → Server | Low | Simple status checks, \u003C 10 clients |\r\n| SSE | Server → Client | Medium | Notifications, feeds, AI streaming |\r\n| WebSocket | Bidirectional | High | Chat, collaboration, gaming |\r\n\r\n---\r\n\r\n## 12. Cross-Boundary Error Handling (MEDIUM)\r\n\r\n### API Error → User-Facing Message\r\n\r\n```typescript\r\n\u002F\u002F lib\u002Ferror-handler.ts\r\nexport function getErrorMessage(error: unknown): string {\r\n  if (error instanceof ApiError) {\r\n    switch (error.status) {\r\n      case 401: return 'Please log in to continue.';\r\n      case 403: return 'You don\\'t have permission to do this.';\r\n      case 404: return 'The item you\\'re looking for doesn\\'t exist.';\r\n      case 409: return 'This conflicts with an existing item.';\r\n      case 422:\r\n        const fields = error.body?.errors;\r\n        if (fields?.length) return fields.map((f: any) => f.message).join('. ');\r\n        return 'Please check your input.';\r\n      case 429: return 'Too many requests. Please wait a moment.';\r\n      default: return 'Something went wrong. Please try again.';\r\n    }\r\n  }\r\n  if (error instanceof TypeError && error.message === 'Failed to fetch') {\r\n    return 'Cannot connect to server. Check your internet connection.';\r\n  }\r\n  return 'An unexpected error occurred.';\r\n}\r\n```\r\n\r\n### React Query Global Error Handler\r\n\r\n```typescript\r\nconst queryClient = new QueryClient({\r\n  defaultOptions: {\r\n    mutations: { onError: (error) => toast.error(getErrorMessage(error)) },\r\n    queries: {\r\n      retry: (failureCount, error) => {\r\n        if (error instanceof ApiError && error.status \u003C 500) return false;\r\n        return failureCount \u003C 3;\r\n      },\r\n    },\r\n  },\r\n});\r\n```\r\n\r\n### Rules\r\n\r\n```\r\n✅ Map every API error code to a human-readable message\r\n✅ Show field-level validation errors next to form inputs\r\n✅ Auto-retry on 5xx (max 3, with backoff), never on 4xx\r\n✅ Redirect to login on 401 (after refresh attempt fails)\r\n✅ Show \"offline\" banner when fetch fails with TypeError\r\n\r\n❌ Never show raw API error messages to users (\"NullPointerException\")\r\n❌ Never silently swallow errors (show toast or log)\r\n❌ Never retry 4xx errors (client is wrong, retrying won't help)\r\n```\r\n\r\n### Integration Decision Tree\r\n\r\n```\r\nSame team owns frontend + backend?\r\n│\r\n├─ YES, both TypeScript\r\n│   └─ tRPC (end-to-end type safety, zero codegen)\r\n│\r\n├─ YES, different languages\r\n│   └─ OpenAPI spec → generated client (type safety via codegen)\r\n│\r\n├─ NO, public API\r\n│   └─ REST + OpenAPI → generated SDKs for consumers\r\n│\r\n└─ Complex data needs, multiple frontends\r\n    └─ GraphQL + codegen (flexible queries per client)\r\n\r\nReal-time needed?\r\n│\r\n├─ Server → Client only (notifications, feeds, AI streaming)\r\n│   └─ SSE (simplest, auto-reconnect, works through proxies)\r\n│\r\n├─ Bidirectional (chat, collaboration)\r\n│   └─ WebSocket (need heartbeat + reconnection logic)\r\n│\r\n└─ Simple status polling (\u003C 10 clients)\r\n    └─ React Query refetchInterval (no infrastructure needed)\r\n```\r\n\r\n---\r\n\r\n## 13. Production Hardening (MEDIUM)\r\n\r\n### Health Checks\r\n\r\n```typescript\r\napp.get('\u002Fhealth', (req, res) => res.json({ status: 'ok' }));           \u002F\u002F liveness\r\napp.get('\u002Fready', async (req, res) => {                                   \u002F\u002F readiness\r\n  const checks = {\r\n    database: await checkDb(), redis: await checkRedis(), \r\n  };\r\n  const ok = Object.values(checks).every(c => c.status === 'ok');\r\n  res.status(ok ? 200 : 503).json({ status: ok ? 'ok' : 'degraded', checks });\r\n});\r\n```\r\n\r\n### Graceful Shutdown\r\n\r\n```typescript\r\nprocess.on('SIGTERM', async () => {\r\n  logger.info('SIGTERM received');\r\n  server.close();              \u002F\u002F stop new connections\r\n  await drainConnections();    \u002F\u002F finish in-flight\r\n  await closeDatabase();\r\n  process.exit(0);\r\n});\r\n```\r\n\r\n### Security Checklist\r\n\r\n```\r\n✅ CORS: explicit origins (never '*' in production)\r\n✅ Security headers (helmet \u002F equivalent)\r\n✅ Rate limiting on public endpoints\r\n✅ Input validation on ALL endpoints (trust nothing)\r\n✅ HTTPS enforced\r\n❌ Never expose internal errors to clients\r\n```\r\n\r\n---\r\n\r\n## Anti-Patterns\r\n\r\n| # | ❌ Don't | ✅ Do Instead |\r\n|---|---------|--------------|\r\n| 1 | Business logic in routes\u002Fcontrollers | Move to service layer |\r\n| 2 | `process.env` scattered everywhere | Centralized typed config |\r\n| 3 | `console.log` for logging | Structured JSON logger |\r\n| 4 | Generic `Error('oops')` | Typed error hierarchy |\r\n| 5 | Direct DB calls in controllers | Repository pattern |\r\n| 6 | No input validation | Validate at boundary (Zod\u002FPydantic) |\r\n| 7 | Catching errors silently | Log + rethrow or return error |\r\n| 8 | No health check endpoints | `\u002Fhealth` + `\u002Fready` |\r\n| 9 | Hardcoded config\u002Fsecrets | Environment variables |\r\n| 10 | No graceful shutdown | Handle SIGTERM properly |\r\n| 11 | Hardcode API URL in frontend | Environment variable (`NEXT_PUBLIC_API_URL`) |\r\n| 12 | Store JWT in localStorage | Memory + httpOnly refresh cookie |\r\n| 13 | Show raw API errors to users | Map to human-readable messages |\r\n| 14 | Retry 4xx errors | Only retry 5xx (server failures) |\r\n| 15 | Skip loading states | Skeleton\u002Fspinner while fetching |\r\n| 16 | Upload large files through API server | Presigned URL → direct to S3 |\r\n| 17 | Poll for real-time data | SSE or WebSocket |\r\n| 18 | Duplicate types frontend + backend | Shared types, tRPC, or OpenAPI codegen |\r\n\r\n---\r\n\r\n## Common Issues\r\n\r\n### Issue 1: \"Where does this business rule go?\"\r\n\r\n**Rule:** If it involves HTTP (request parsing, status codes, headers) → controller. If it involves business decisions (pricing, permissions, rules) → service. If it touches the database → repository.\r\n\r\n### Issue 2: \"Service is getting too big\"\r\n\r\n**Symptom:** One service file > 500 lines with 20+ methods.\r\n\r\n**Fix:** Split by sub-domain. `OrderService` → `OrderCreationService` + `OrderFulfillmentService` + `OrderQueryService`. Each focused on one workflow.\r\n\r\n### Issue 3: \"Tests are slow because they hit the database\"\r\n\r\n**Fix:** Unit tests mock the repository layer (fast). Integration tests use test containers or transaction rollback (real DB, still fast). Never mock the service layer in integration tests.\r\n\r\n---\r\n\r\n## Reference Documents\r\n\r\nThis skill includes deep-dive references for specialized topics. Read the relevant reference when you need detailed guidance.\r\n\r\n| Need to… | Reference |\r\n|----------|-----------|\r\n| Write backend tests (unit, integration, e2e, contract, performance) | [references\u002Ftesting-strategy.md](references\u002Ftesting-strategy.md) |\r\n| Validate a release before deployment (6-gate checklist) | [references\u002Frelease-checklist.md](references\u002Frelease-checklist.md) |\r\n| Choose a tech stack (language, framework, database, infra) | [references\u002Ftechnology-selection.md](references\u002Ftechnology-selection.md) |\r\n| Build with Django \u002F DRF (models, views, serializers, admin) | [references\u002Fdjango-best-practices.md](references\u002Fdjango-best-practices.md) |\r\n| Design REST\u002FGraphQL\u002FgRPC endpoints (URLs, status codes, pagination) | [references\u002Fapi-design.md](references\u002Fapi-design.md) |\r\n| Design database schema, indexes, migrations, multi-tenancy | [references\u002Fdb-schema.md](references\u002Fdb-schema.md) |\r\n| Auth flow (JWT bearer, token refresh, Next.js SSR, RBAC, middleware order) | [references\u002Fauth-flow.md](references\u002Fauth-flow.md) |\r\n| CORS config, env vars per environment, common CORS issues | [references\u002Fenvironment-management.md](references\u002Fenvironment-management.md) |\r\n","# Full-Stack Development Practices\r\n\r\n## MANDATORY WORKFLOW — Follow These Steps In Order\r\n\r\n**When this skill is triggered, you MUST follow this workflow before writing any code.**\r\n\r\n### Step 0: Gather Requirements\r\n\r\nBefore scaffolding anything, ask the user to clarify (or infer from context):\r\n\r\n1. **Stack**: Language\u002Fframework for backend and frontend (e.g., Express + React, Django + Vue, Go + HTMX)\r\n2. **Service type**: API-only, full-stack monolith, or microservice?\r\n3. **Database**: SQL (PostgreSQL, SQLite, MySQL) or NoSQL (MongoDB, Redis)?\r\n4. **Integration**: REST, GraphQL, tRPC, or gRPC?\r\n5. **Real-time**: Needed? If yes — SSE, WebSocket, or polling?\r\n6. **Auth**: Needed? If yes — JWT, session, OAuth, or third-party (Clerk, Auth.js)?\r\n\r\nIf the user has already specified these in their request, skip asking and proceed.\r\n\r\n### Step 1: Architectural Decisions\r\n\r\nBased on requirements, make and state these decisions before coding:\r\n\r\n| Decision | Options | Reference |\r\n|----------|---------|-----------|\r\n| Project structure | Feature-first (recommended) vs layer-first | [Section 1](#1-project-structure--layering-critical) |\r\n| API client approach | Typed fetch \u002F React Query \u002F tRPC \u002F OpenAPI codegen | [Section 5](#5-api-client-patterns-medium) |\r\n| Auth strategy | JWT + refresh \u002F session \u002F third-party | [Section 6](#6-authentication--middleware-high) |\r\n| Real-time method | Polling \u002F SSE \u002F WebSocket | [Section 11](#11-real-time-patterns-medium) |\r\n| Error handling | Typed error hierarchy + global handler | [Section 3](#3-error-handling--resilience-high) |\r\n\r\nBriefly explain each choice (1 sentence per decision).\r\n\r\n### Step 2: Scaffold with Checklist\r\n\r\nUse the appropriate checklist below. Ensure ALL checked items are implemented — do not skip any.\r\n\r\n### Step 3: Implement Following Patterns\r\n\r\nWrite code following the patterns in this document. Reference specific sections as you implement each part.\r\n\r\n### Step 4: Test & Verify\r\n\r\nAfter implementation, run these checks before claiming completion:\r\n\r\n1. **Build check**: Ensure both backend and frontend compile without errors\r\n   ```bash\r\n   # Backend\r\n   cd server && npm run build\r\n   # Frontend\r\n   cd client && npm run build\r\n   ```\r\n2. **Start & smoke test**: Start the server, verify key endpoints return expected responses\r\n   ```bash\r\n   # Start server, then test\r\n   curl http:\u002F\u002Flocalhost:3000\u002Fhealth\r\n   curl http:\u002F\u002Flocalhost:3000\u002Fapi\u002F\u003Cresource>\r\n   ```\r\n3. **Integration check**: Verify frontend can connect to backend (CORS, API base URL, auth flow)\r\n4. **Real-time check** (if applicable): Open two browser tabs, verify changes sync\r\n\r\nIf any check fails, fix the issue before proceeding.\r\n\r\n### Step 5: Handoff Summary\r\n\r\nProvide a brief summary to the user:\r\n\r\n- **What was built**: List of implemented features and endpoints\r\n- **How to run**: Exact commands to start backend and frontend\r\n- **What's missing \u002F next steps**: Any deferred items, known limitations, or recommended improvements\r\n- **Key files**: List the most important files the user should know about\r\n\r\n---\r\n\r\n## Scope\r\n\r\n**USE this skill when:**\r\n- Building a full-stack application (backend + frontend)\r\n- Scaffolding a new backend service or API\r\n- Designing service layers and module boundaries\r\n- Implementing database access, caching, or background jobs\r\n- Writing error handling, logging, or configuration management\r\n- Reviewing backend code for architectural issues\r\n- Hardening for production\r\n- Setting up API clients, auth flows, file uploads, or real-time features\r\n\r\n**NOT for:**\r\n- Pure frontend\u002FUI concerns (use your frontend framework's docs)\r\n- Pure database schema design without backend context\r\n\r\n---\r\n\r\n## Quick Start — New Backend Service Checklist\r\n\r\n- [ ] Project scaffolded with **feature-first** structure\r\n- [ ] Configuration **centralized**, env vars **validated at startup** (fail fast)\r\n- [ ] **Typed error hierarchy** defined (not generic `Error`)\r\n- [ ] **Global error handler** middleware\r\n- [ ] **Structured JSON logging** with request ID propagation\r\n- [ ] Database: **migrations** set up, **connection pooling** configured\r\n- [ ] **Input validation** on all endpoints (Zod \u002F Pydantic \u002F Go validator)\r\n- [ ] **Authentication middleware** in place\r\n- [ ] **Health check** endpoints (`\u002Fhealth`, `\u002Fready`)\r\n- [ ] **Graceful shutdown** handling (SIGTERM)\r\n- [ ] **CORS** configured (explicit origins, not `*`)\r\n- [ ] **Security headers** (helmet or equivalent)\r\n- [ ] `.env.example` committed (no real secrets)\r\n\r\n## Quick Start — Frontend-Backend Integration Checklist\r\n\r\n- [ ] **API client** configured (typed fetch wrapper, React Query, tRPC, or OpenAPI generated)\r\n- [ ] **Base URL** from environment variable (not hardcoded)\r\n- [ ] **Auth token** attached to requests automatically (interceptor \u002F middleware)\r\n- [ ] **Error handling** — API errors mapped to user-facing messages\r\n- [ ] **Loading states** handled (skeleton\u002Fspinner, not blank screen)\r\n- [ ] **Type safety** across the boundary (shared types, OpenAPI, or tRPC)\r\n- [ ] **CORS** configured with explicit origins (not `*` in production)\r\n- [ ] **Refresh token** flow implemented (httpOnly cookie + transparent retry on 401)\r\n\r\n---\r\n\r\n## Quick Navigation\r\n\r\n| Need to… | Jump to |\r\n|----------|---------|\r\n| Organize project folders | [1. Project Structure](#1-project-structure--layering-critical) |\r\n| Manage config + secrets | [2. Configuration](#2-configuration--environment-critical) |\r\n| Handle errors properly | [3. Error Handling](#3-error-handling--resilience-high) |\r\n| Write database code | [4. Database Access Patterns](#4-database-access-patterns-high) |\r\n| Set up API client from frontend | [5. API Client Patterns](#5-api-client-patterns-medium) |\r\n| Add auth middleware | [6. Auth & Middleware](#6-authentication--middleware-high) |\r\n| Set up logging | [7. Logging & Observability](#7-logging--observability-medium-high) |\r\n| Add background jobs | [8. Background Jobs](#8-background-jobs--async-medium) |\r\n| Implement caching | [9. Caching](#9-caching-patterns-medium) |\r\n| Upload files (presigned URL, multipart) | [10. File Upload Patterns](#10-file-upload-patterns-medium) |\r\n| Add real-time features (SSE, WebSocket) | [11. Real-Time Patterns](#11-real-time-patterns-medium) |\r\n| Handle API errors in frontend UI | [12. Cross-Boundary Error Handling](#12-cross-boundary-error-handling-medium) |\r\n| Harden for production | [13. Production Hardening](#13-production-hardening-medium) |\r\n| Design API endpoints | [API Design](references\u002Fapi-design.md) |\r\n| Design database schema | [Database Schema](references\u002Fdb-schema.md) |\r\n| Auth flow (JWT, refresh, Next.js SSR, RBAC) | [references\u002Fauth-flow.md](references\u002Fauth-flow.md) |\r\n| CORS, env vars, environment management | [references\u002Fenvironment-management.md](references\u002Fenvironment-management.md) |\r\n\r\n---\r\n\r\n## Core Principles (7 Iron Rules)\r\n\r\n```\r\n1. ✅ Organize by FEATURE, not by technical layer\r\n2. ✅ Controllers never contain business logic\r\n3. ✅ Services never import HTTP request\u002Fresponse types\r\n4. ✅ All config from env vars, validated at startup, fail fast\r\n5. ✅ Every error is typed, logged, and returns consistent format\r\n6. ✅ All input validated at the boundary — trust nothing from client\r\n7. ✅ Structured JSON logging with request ID — not console.log\r\n```\r\n\r\n---\r\n\r\n## 1. Project Structure & Layering (CRITICAL)\r\n\r\n### Feature-First Organization\r\n\r\n```\r\n✅ Feature-first                    ❌ Layer-first\r\nsrc\u002F                                src\u002F\r\n  orders\u002F                             controllers\u002F\r\n    order.controller.ts                 order.controller.ts\r\n    order.service.ts                    user.controller.ts\r\n    order.repository.ts               services\u002F\r\n    order.dto.ts                        order.service.ts\r\n    order.test.ts                       user.service.ts\r\n  users\u002F                              repositories\u002F\r\n    user.controller.ts                  ...\r\n    user.service.ts\r\n  shared\u002F\r\n    database\u002F\r\n    middleware\u002F\r\n```\r\n\r\n### Three-Layer Architecture\r\n\r\n```\r\nController (HTTP) → Service (Business Logic) → Repository (Data Access)\r\n```\r\n\r\n| Layer | Responsibility | ❌ Never |\r\n|-------|---------------|---------|\r\n| Controller | Parse request, validate, call service, format response | Business logic, DB queries |\r\n| Service | Business rules, orchestration, transaction mgmt | HTTP types (req\u002Fres), direct DB |\r\n| Repository | Database queries, external API calls | Business logic, HTTP types |\r\n\r\n### Dependency Injection (All Languages)\r\n\r\n**TypeScript:**\r\n```typescript\r\nclass OrderService {\r\n  constructor(\r\n    private readonly orderRepo: OrderRepository,    \u002F\u002F ✅ injected interface\r\n    private readonly emailService: EmailService,\r\n  ) {}\r\n}\r\n```\r\n\r\n**Python:**\r\n```python\r\nclass OrderService:\r\n    def __init__(self, order_repo: OrderRepository, email_service: EmailService):\r\n        self.order_repo = order_repo                 # ✅ injected\r\n        self.email_service = email_service\r\n```\r\n\r\n**Go:**\r\n```go\r\ntype OrderService struct {\r\n    orderRepo    OrderRepository                      \u002F\u002F ✅ interface\r\n    emailService EmailService\r\n}\r\n\r\nfunc NewOrderService(repo OrderRepository, email EmailService) *OrderService {\r\n    return &OrderService{orderRepo: repo, emailService: email}\r\n}\r\n```\r\n\r\n---\r\n\r\n## 2. Configuration & Environment (CRITICAL)\r\n\r\n### Centralized, Typed, Fail-Fast\r\n\r\n**TypeScript:**\r\n```typescript\r\nconst config = {\r\n  port: parseInt(process.env.PORT || '3000', 10),\r\n  database: { url: requiredEnv('DATABASE_URL'), poolSize: intEnv('DB_POOL_SIZE', 10) },\r\n  auth: { jwtSecret: requiredEnv('JWT_SECRET'), expiresIn: process.env.JWT_EXPIRES_IN || '1h' },\r\n} as const;\r\n\r\nfunction requiredEnv(name: string): string {\r\n  const value = process.env[name];\r\n  if (!value) throw new Error(`Missing required env var: ${name}`);  \u002F\u002F fail fast\r\n  return value;\r\n}\r\n```\r\n\r\n**Python:**\r\n```python\r\nfrom pydantic_settings import BaseSettings\r\n\r\nclass Settings(BaseSettings):\r\n    database_url: str                        # required — app won't start without it\r\n    jwt_secret: str                          # required\r\n    port: int = 3000                         # optional with default\r\n    db_pool_size: int = 10\r\n    class Config:\r\n        env_file = \".env\"\r\n\r\nsettings = Settings()                        # fails fast if DATABASE_URL missing\r\n```\r\n\r\n### Rules\r\n\r\n```\r\n✅ All config via environment variables (Twelve-Factor)\r\n✅ Validate required vars at startup — fail fast\r\n✅ Type-cast at config layer, not at usage sites\r\n✅ Commit .env.example with dummy values\r\n\r\n❌ Never hardcode secrets, URLs, or credentials\r\n❌ Never commit .env files\r\n❌ Never scatter process.env \u002F os.environ throughout code\r\n```\r\n\r\n---\r\n\r\n## 3. Error Handling & Resilience (HIGH)\r\n\r\n### Typed Error Hierarchy\r\n\r\n```typescript\r\n\u002F\u002F Base (TypeScript)\r\nclass AppError extends Error {\r\n  constructor(\r\n    message: string,\r\n    public readonly code: string,\r\n    public readonly statusCode: number,\r\n    public readonly isOperational: boolean = true,\r\n  ) { super(message); }\r\n}\r\nclass NotFoundError extends AppError {\r\n  constructor(resource: string, id: string) {\r\n    super(`${resource} not found: ${id}`, 'NOT_FOUND', 404);\r\n  }\r\n}\r\nclass ValidationError extends AppError {\r\n  constructor(public readonly errors: FieldError[]) {\r\n    super('Validation failed', 'VALIDATION_ERROR', 422);\r\n  }\r\n}\r\n```\r\n\r\n```python\r\n# Base (Python)\r\nclass AppError(Exception):\r\n    def __init__(self, message: str, code: str, status_code: int):\r\n        self.message, self.code, self.status_code = message, code, status_code\r\n\r\nclass NotFoundError(AppError):\r\n    def __init__(self, resource: str, id: str):\r\n        super().__init__(f\"{resource} not found: {id}\", \"NOT_FOUND\", 404)\r\n```\r\n\r\n### Global Error Handler\r\n\r\n```typescript\r\n\u002F\u002F TypeScript (Express)\r\napp.use((err, req, res, next) => {\r\n  if (err instanceof AppError && err.isOperational) {\r\n    return res.status(err.statusCode).json({\r\n      title: err.code, status: err.statusCode,\r\n      detail: err.message, request_id: req.id,\r\n    });\r\n  }\r\n  logger.error('Unexpected error', { error: err.message, stack: err.stack, request_id: req.id });\r\n  res.status(500).json({ title: 'Internal Error', status: 500, request_id: req.id });\r\n});\r\n```\r\n\r\n### Rules\r\n\r\n```\r\n✅ Typed, domain-specific error classes\r\n✅ Global error handler catches everything\r\n✅ Operational errors → structured response\r\n✅ Programming errors → log + generic 500\r\n✅ Retry transient failures with exponential backoff\r\n\r\n❌ Never catch and ignore errors silently\r\n❌ Never return stack traces to client\r\n❌ Never throw generic Error('something')\r\n```\r\n\r\n---\r\n\r\n## 4. Database Access Patterns (HIGH)\r\n\r\n### Migrations Always\r\n\r\n```bash\r\n# TypeScript (Prisma)           # Python (Alembic)              # Go (golang-migrate)\r\nnpx prisma migrate dev          alembic revision --autogenerate  migrate -source file:\u002F\u002Fmigrations\r\nnpx prisma migrate deploy       alembic upgrade head             migrate -database $DB up\r\n```\r\n\r\n```\r\n✅ Schema changes via migrations, never manual SQL\r\n✅ Migrations must be reversible\r\n✅ Review migration SQL before production\r\n❌ Never modify production schema manually\r\n```\r\n\r\n### N+1 Prevention\r\n\r\n```typescript\r\n\u002F\u002F ❌ N+1: 1 query + N queries\r\nconst orders = await db.order.findMany();\r\nfor (const o of orders) { o.items = await db.item.findMany({ where: { orderId: o.id } }); }\r\n\r\n\u002F\u002F ✅ Single JOIN query\r\nconst orders = await db.order.findMany({ include: { items: true } });\r\n```\r\n\r\n### Transactions for Multi-Step Writes\r\n\r\n```typescript\r\nawait db.$transaction(async (tx) => {\r\n  const order = await tx.order.create({ data: orderData });\r\n  await tx.inventory.decrement({ productId, quantity });\r\n  await tx.payment.create({ orderId: order.id, amount });\r\n});\r\n```\r\n\r\n### Connection Pooling\r\n\r\nPool size = `(CPU cores × 2) + spindle_count` (start with 10-20). Always set connection timeout. Use PgBouncer for serverless.\r\n\r\n---\r\n\r\n## 5. API Client Patterns (MEDIUM)\r\n\r\nThe \"glue layer\" between frontend and backend. Choose the approach that fits your team and stack.\r\n\r\n### Option A: Typed Fetch Wrapper (Simple, No Dependencies)\r\n\r\n```typescript\r\n\u002F\u002F lib\u002Fapi-client.ts\r\nconst BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http:\u002F\u002Flocalhost:3001';\r\n\r\nclass ApiError extends Error {\r\n  constructor(public status: number, public body: any) {\r\n    super(body?.detail || body?.message || `API error ${status}`);\r\n  }\r\n}\r\n\r\nasync function api\u003CT>(path: string, options: RequestInit = {}): Promise\u003CT> {\r\n  const token = getAuthToken();  \u002F\u002F from cookie \u002F memory \u002F context\r\n\r\n  const res = await fetch(`${BASE_URL}${path}`, {\r\n    ...options,\r\n    headers: {\r\n      'Content-Type': 'application\u002Fjson',\r\n      ...(token ? { Authorization: `Bearer ${token}` } : {}),\r\n      ...options.headers,\r\n    },\r\n  });\r\n\r\n  if (!res.ok) {\r\n    const body = await res.json().catch(() => null);\r\n    throw new ApiError(res.status, body);\r\n  }\r\n\r\n  if (res.status === 204) return undefined as T;\r\n  return res.json();\r\n}\r\n\r\nexport const apiClient = {\r\n  get: \u003CT>(path: string) => api\u003CT>(path),\r\n  post: \u003CT>(path: string, data: unknown) => api\u003CT>(path, { method: 'POST', body: JSON.stringify(data) }),\r\n  put: \u003CT>(path: string, data: unknown) => api\u003CT>(path, { method: 'PUT', body: JSON.stringify(data) }),\r\n  patch: \u003CT>(path: string, data: unknown) => api\u003CT>(path, { method: 'PATCH', body: JSON.stringify(data) }),\r\n  delete: \u003CT>(path: string) => api\u003CT>(path, { method: 'DELETE' }),\r\n};\r\n```\r\n\r\n### Option B: React Query + Typed Client (Recommended for React)\r\n\r\n```typescript\r\n\u002F\u002F hooks\u002Fuse-orders.ts\r\nimport { useQuery, useMutation, useQueryClient } from '@tanstack\u002Freact-query';\r\nimport { apiClient } from '@\u002Flib\u002Fapi-client';\r\n\r\ninterface Order { id: string; total: number; status: string; }\r\ninterface CreateOrderInput { items: { productId: string; quantity: number }[] }\r\n\r\nexport function useOrders() {\r\n  return useQuery({\r\n    queryKey: ['orders'],\r\n    queryFn: () => apiClient.get\u003C{ data: Order[] }>('\u002Fapi\u002Forders'),\r\n    staleTime: 1000 * 60,  \u002F\u002F 1 min\r\n  });\r\n}\r\n\r\nexport function useCreateOrder() {\r\n  const queryClient = useQueryClient();\r\n  return useMutation({\r\n    mutationFn: (data: CreateOrderInput) =>\r\n      apiClient.post\u003C{ data: Order }>('\u002Fapi\u002Forders', data),\r\n    onSuccess: () => {\r\n      queryClient.invalidateQueries({ queryKey: ['orders'] });\r\n    },\r\n  });\r\n}\r\n\r\n\u002F\u002F Usage in component:\r\nfunction OrdersPage() {\r\n  const { data, isLoading, error } = useOrders();\r\n  const createOrder = useCreateOrder();\r\n  if (isLoading) return \u003CSkeleton \u002F>;\r\n  if (error) return \u003CErrorBanner error={error} \u002F>;\r\n  \u002F\u002F ...\r\n}\r\n```\r\n\r\n### Option C: tRPC (Same Team Owns Both Sides)\r\n\r\n```typescript\r\n\u002F\u002F server: trpc\u002Frouter.ts\r\nexport const appRouter = router({\r\n  orders: router({\r\n    list: publicProcedure.query(async () => {\r\n      return db.order.findMany({ include: { items: true } });\r\n    }),\r\n    create: protectedProcedure\r\n      .input(z.object({ items: z.array(orderItemSchema) }))\r\n      .mutation(async ({ input, ctx }) => {\r\n        return orderService.create(ctx.user.id, input);\r\n      }),\r\n  }),\r\n});\r\nexport type AppRouter = typeof appRouter;\r\n\r\n\u002F\u002F client: automatic type safety, no code generation\r\nconst { data } = trpc.orders.list.useQuery();\r\nconst createOrder = trpc.orders.create.useMutation();\r\n```\r\n\r\n### Option D: OpenAPI Generated Client (Public \u002F Multi-Consumer APIs)\r\n\r\n```bash\r\nnpx openapi-typescript-codegen \\\r\n  --input http:\u002F\u002Flocalhost:3001\u002Fapi\u002Fopenapi.json \\\r\n  --output src\u002Fgenerated\u002Fapi \\\r\n  --client axios\r\n```\r\n\r\n### Decision: Which API Client?\r\n\r\n| Approach | When | Type Safety | Effort |\r\n|----------|------|-------------|--------|\r\n| Typed fetch wrapper | Simple apps, small teams | Manual types | Low |\r\n| React Query + fetch | React apps, server state | Manual types | Medium |\r\n| tRPC | Same team, TypeScript both sides | Automatic | Low |\r\n| OpenAPI generated | Public API, multi-consumer | Automatic | Medium |\r\n| GraphQL codegen | GraphQL APIs | Automatic | Medium |\r\n\r\n---\r\n\r\n## 6. Authentication & Middleware (HIGH)\r\n\r\n> **Full reference:** [references\u002Fauth-flow.md](references\u002Fauth-flow.md) — JWT bearer flow, automatic token refresh, Next.js server-side auth, RBAC pattern, backend middleware order.\r\n\r\n### Standard Middleware Order\r\n\r\n```\r\nRequest → 1.RequestID → 2.Logging → 3.CORS → 4.RateLimit → 5.BodyParse\r\n       → 6.Auth → 7.Authz → 8.Validation → 9.Handler → 10.ErrorHandler → Response\r\n```\r\n\r\n### JWT Rules\r\n\r\n```\r\n✅ Short expiry access token (15min) + refresh token (server-stored)\r\n✅ Minimal claims: userId, roles (not entire user object)\r\n✅ Rotate signing keys periodically\r\n\r\n❌ Never store tokens in localStorage (XSS risk)\r\n❌ Never pass tokens in URL query params\r\n```\r\n\r\n### RBAC Pattern\r\n\r\n```typescript\r\nfunction authorize(...roles: Role[]) {\r\n  return (req, res, next) => {\r\n    if (!req.user) throw new UnauthorizedError();\r\n    if (!roles.some(r => req.user.roles.includes(r))) throw new ForbiddenError();\r\n    next();\r\n  };\r\n}\r\nrouter.delete('\u002Fusers\u002F:id', authenticate, authorize('admin'), deleteUser);\r\n```\r\n\r\n### Auth Token Automatic Refresh\r\n\r\n```typescript\r\n\u002F\u002F lib\u002Fapi-client.ts — transparent refresh on 401\r\nasync function apiWithRefresh\u003CT>(path: string, options: RequestInit = {}): Promise\u003CT> {\r\n  try {\r\n    return await api\u003CT>(path, options);\r\n  } catch (err) {\r\n    if (err instanceof ApiError && err.status === 401) {\r\n      const refreshed = await api\u003C{ accessToken: string }>('\u002Fapi\u002Fauth\u002Frefresh', {\r\n        method: 'POST',\r\n        credentials: 'include',  \u002F\u002F send httpOnly cookie\r\n      });\r\n      setAuthToken(refreshed.accessToken);\r\n      return api\u003CT>(path, options);  \u002F\u002F retry\r\n    }\r\n    throw err;\r\n  }\r\n}\r\n```\r\n\r\n---\r\n\r\n## 7. Logging & Observability (MEDIUM-HIGH)\r\n\r\n### Structured JSON Logging\r\n\r\n```typescript\r\n\u002F\u002F ✅ Structured — parseable, filterable, alertable\r\nlogger.info('Order created', {\r\n  orderId: order.id, userId: user.id, total: order.total,\r\n  items: order.items.length, duration_ms: Date.now() - startTime,\r\n});\r\n\u002F\u002F Output: {\"level\":\"info\",\"msg\":\"Order created\",\"orderId\":\"ord_123\",...}\r\n\r\n\u002F\u002F ❌ Unstructured — useless at scale\r\nconsole.log(`Order created for user ${user.id} with total ${order.total}`);\r\n```\r\n\r\n### Log Levels\r\n\r\n| Level | When | Production? |\r\n|-------|------|------------|\r\n| error | Requires immediate attention | ✅ Always |\r\n| warn | Unexpected but handled | ✅ Always |\r\n| info | Normal operations, audit trail | ✅ Always |\r\n| debug | Dev troubleshooting | ❌ Dev only |\r\n\r\n### Rules\r\n\r\n```\r\n✅ Request ID in every log entry (propagated via middleware)\r\n✅ Log at layer boundaries (request in, response out, external call)\r\n❌ Never log passwords, tokens, PII, or secrets\r\n❌ Never use console.log in production code\r\n```\r\n\r\n---\r\n\r\n## 8. Background Jobs & Async (MEDIUM)\r\n\r\n### Rules\r\n\r\n```\r\n✅ All jobs must be IDEMPOTENT (same job running twice = same result)\r\n✅ Failed jobs → retry (max 3) → dead letter queue → alert\r\n✅ Workers run as SEPARATE processes (not threads in API server)\r\n\r\n❌ Never put long-running tasks in request handlers\r\n❌ Never assume job runs exactly once\r\n```\r\n\r\n### Idempotent Job Pattern\r\n\r\n```typescript\r\nasync function processPayment(data: { orderId: string }) {\r\n  const order = await orderRepo.findById(data.orderId);\r\n  if (order.paymentStatus === 'completed') return;  \u002F\u002F already processed\r\n  await paymentGateway.charge(order);\r\n  await orderRepo.updatePaymentStatus(order.id, 'completed');\r\n}\r\n```\r\n\r\n---\r\n\r\n## 9. Caching Patterns (MEDIUM)\r\n\r\n### Cache-Aside (Lazy Loading)\r\n\r\n```typescript\r\nasync function getUser(id: string): Promise\u003CUser> {\r\n  const cached = await redis.get(`user:${id}`);\r\n  if (cached) return JSON.parse(cached);\r\n\r\n  const user = await userRepo.findById(id);\r\n  if (!user) throw new NotFoundError('User', id);\r\n\r\n  await redis.set(`user:${id}`, JSON.stringify(user), 'EX', 900);  \u002F\u002F 15min TTL\r\n  return user;\r\n}\r\n```\r\n\r\n### Rules\r\n\r\n```\r\n✅ ALWAYS set TTL — never cache without expiry\r\n✅ Invalidate on write (delete cache key after update)\r\n✅ Use cache for reads, never for authoritative state\r\n\r\n❌ Never cache without TTL (stale data is worse than slow data)\r\n```\r\n\r\n| Data Type | Suggested TTL |\r\n|-----------|---------------|\r\n| User profile | 5-15 min |\r\n| Product catalog | 1-5 min |\r\n| Config \u002F feature flags | 30-60 sec |\r\n| Session | Match session duration |\r\n\r\n---\r\n\r\n## 10. File Upload Patterns (MEDIUM)\r\n\r\n### Option A: Presigned URL (Recommended for Large Files)\r\n\r\n```\r\nClient → GET \u002Fapi\u002Fuploads\u002Fpresign?filename=photo.jpg&type=image\u002Fjpeg\r\nServer → { uploadUrl: \"https:\u002F\u002Fs3...\u002Fpresigned\", fileKey: \"uploads\u002Fabc123.jpg\" }\r\nClient → PUT uploadUrl (direct to S3, bypasses your server)\r\nClient → POST \u002Fapi\u002Fphotos { fileKey: \"uploads\u002Fabc123.jpg\" }  (save reference)\r\n```\r\n\r\n**Backend:**\r\n```typescript\r\napp.get('\u002Fapi\u002Fuploads\u002Fpresign', authenticate, async (req, res) => {\r\n  const { filename, type } = req.query;\r\n  const key = `uploads\u002F${crypto.randomUUID()}-${filename}`;\r\n  const url = await s3.getSignedUrl('putObject', {\r\n    Bucket: process.env.S3_BUCKET, Key: key,\r\n    ContentType: type, Expires: 300,  \u002F\u002F 5 min\r\n  });\r\n  res.json({ uploadUrl: url, fileKey: key });\r\n});\r\n```\r\n\r\n**Frontend:**\r\n```typescript\r\nasync function uploadFile(file: File) {\r\n  const { uploadUrl, fileKey } = await apiClient.get\u003CPresignResponse>(\r\n    `\u002Fapi\u002Fuploads\u002Fpresign?filename=${file.name}&type=${file.type}`\r\n  );\r\n  await fetch(uploadUrl, { method: 'PUT', body: file, headers: { 'Content-Type': file.type } });\r\n  return apiClient.post('\u002Fapi\u002Fphotos', { fileKey });\r\n}\r\n```\r\n\r\n### Option B: Multipart (Small Files \u003C 10MB)\r\n\r\n```typescript\r\n\u002F\u002F Frontend\r\nconst formData = new FormData();\r\nformData.append('file', file);\r\nformData.append('description', 'Profile photo');\r\nconst res = await fetch('\u002Fapi\u002Fupload', { method: 'POST', body: formData });\r\n\u002F\u002F Note: do NOT set Content-Type header — browser sets boundary automatically\r\n```\r\n\r\n### Decision\r\n\r\n| Method | File Size | Server Load | Complexity |\r\n|--------|-----------|-------------|------------|\r\n| Presigned URL | Any (recommended > 5MB) | None (direct to storage) | Medium |\r\n| Multipart | \u003C 10MB | High (streams through server) | Low |\r\n| Chunked \u002F Resumable | > 100MB | Medium | High |\r\n\r\n---\r\n\r\n## 11. Real-Time Patterns (MEDIUM)\r\n\r\n### Option A: Server-Sent Events (SSE) — One-Way Server → Client\r\n\r\nBest for: notifications, live feeds, streaming AI responses.\r\n\r\n**Backend (Express):**\r\n```typescript\r\napp.get('\u002Fapi\u002Fevents', authenticate, (req, res) => {\r\n  res.writeHead(200, {\r\n    'Content-Type': 'text\u002Fevent-stream',\r\n    'Cache-Control': 'no-cache',\r\n    Connection: 'keep-alive',\r\n  });\r\n  const send = (event: string, data: unknown) => {\r\n    res.write(`event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`);\r\n  };\r\n  const unsubscribe = eventBus.subscribe(req.user.id, (event) => {\r\n    send(event.type, event.payload);\r\n  });\r\n  req.on('close', () => unsubscribe());\r\n});\r\n```\r\n\r\n**Frontend:**\r\n```typescript\r\nfunction useServerEvents(userId: string) {\r\n  useEffect(() => {\r\n    const source = new EventSource(`\u002Fapi\u002Fevents?userId=${userId}`);\r\n    source.addEventListener('notification', (e) => {\r\n      showToast(JSON.parse(e.data).message);\r\n    });\r\n    source.onerror = () => { source.close(); setTimeout(() => \u002F* reconnect *\u002F, 3000); };\r\n    return () => source.close();\r\n  }, [userId]);\r\n}\r\n```\r\n\r\n### Option B: WebSocket — Bidirectional\r\n\r\nBest for: chat, collaborative editing, gaming.\r\n\r\n**Backend (ws library):**\r\n```typescript\r\nimport { WebSocketServer } from 'ws';\r\nconst wss = new WebSocketServer({ server: httpServer, path: '\u002Fws' });\r\nwss.on('connection', (ws, req) => {\r\n  const userId = authenticateWs(req);\r\n  if (!userId) { ws.close(4001, 'Unauthorized'); return; }\r\n  ws.on('message', (raw) => handleMessage(userId, JSON.parse(raw.toString())));\r\n  ws.on('close', () => cleanupUser(userId));\r\n  const interval = setInterval(() => ws.ping(), 30000);\r\n  ws.on('pong', () => { \u002F* alive *\u002F });\r\n  ws.on('close', () => clearInterval(interval));\r\n});\r\n```\r\n\r\n**Frontend:**\r\n```typescript\r\nfunction useWebSocket(url: string) {\r\n  const [ws, setWs] = useState\u003CWebSocket | null>(null);\r\n  useEffect(() => {\r\n    const socket = new WebSocket(url);\r\n    socket.onopen = () => setWs(socket);\r\n    socket.onclose = () => setTimeout(() => \u002F* reconnect *\u002F, 3000);\r\n    return () => socket.close();\r\n  }, [url]);\r\n  const send = useCallback((data: unknown) => ws?.send(JSON.stringify(data)), [ws]);\r\n  return { ws, send };\r\n}\r\n```\r\n\r\n### Option C: Polling (Simplest, No Infrastructure)\r\n\r\n```typescript\r\nfunction useOrderStatus(orderId: string) {\r\n  return useQuery({\r\n    queryKey: ['order-status', orderId],\r\n    queryFn: () => apiClient.get\u003COrder>(`\u002Fapi\u002Forders\u002F${orderId}`),\r\n    refetchInterval: (query) => {\r\n      if (query.state.data?.status === 'completed') return false;\r\n      return 5000;\r\n    },\r\n  });\r\n}\r\n```\r\n\r\n### Decision\r\n\r\n| Method | Direction | Complexity | When |\r\n|--------|-----------|------------|------|\r\n| Polling | Client → Server | Low | Simple status checks, \u003C 10 clients |\r\n| SSE | Server → Client | Medium | Notifications, feeds, AI streaming |\r\n| WebSocket | Bidirectional | High | Chat, collaboration, gaming |\r\n\r\n---\r\n\r\n## 12. Cross-Boundary Error Handling (MEDIUM)\r\n\r\n### API Error → User-Facing Message\r\n\r\n```typescript\r\n\u002F\u002F lib\u002Ferror-handler.ts\r\nexport function getErrorMessage(error: unknown): string {\r\n  if (error instanceof ApiError) {\r\n    switch (error.status) {\r\n      case 401: return 'Please log in to continue.';\r\n      case 403: return 'You don\\'t have permission to do this.';\r\n      case 404: return 'The item you\\'re looking for doesn\\'t exist.';\r\n      case 409: return 'This conflicts with an existing item.';\r\n      case 422:\r\n        const fields = error.body?.errors;\r\n        if (fields?.length) return fields.map((f: any) => f.message).join('. ');\r\n        return 'Please check your input.';\r\n      case 429: return 'Too many requests. Please wait a moment.';\r\n      default: return 'Something went wrong. Please try again.';\r\n    }\r\n  }\r\n  if (error instanceof TypeError && error.message === 'Failed to fetch') {\r\n    return 'Cannot connect to server. Check your internet connection.';\r\n  }\r\n  return 'An unexpected error occurred.';\r\n}\r\n```\r\n\r\n### React Query Global Error Handler\r\n\r\n```typescript\r\nconst queryClient = new QueryClient({\r\n  defaultOptions: {\r\n    mutations: { onError: (error) => toast.error(getErrorMessage(error)) },\r\n    queries: {\r\n      retry: (failureCount, error) => {\r\n        if (error instanceof ApiError && error.status \u003C 500) return false;\r\n        return failureCount \u003C 3;\r\n      },\r\n    },\r\n  },\r\n});\r\n```\r\n\r\n### Rules\r\n\r\n```\r\n✅ Map every API error code to a human-readable message\r\n✅ Show field-level validation errors next to form inputs\r\n✅ Auto-retry on 5xx (max 3, with backoff), never on 4xx\r\n✅ Redirect to login on 401 (after refresh attempt fails)\r\n✅ Show \"offline\" banner when fetch fails with TypeError\r\n\r\n❌ Never show raw API error messages to users (\"NullPointerException\")\r\n❌ Never silently swallow errors (show toast or log)\r\n❌ Never retry 4xx errors (client is wrong, retrying won't help)\r\n```\r\n\r\n### Integration Decision Tree\r\n\r\n```\r\nSame team owns frontend + backend?\r\n│\r\n├─ YES, both TypeScript\r\n│   └─ tRPC (end-to-end type safety, zero codegen)\r\n│\r\n├─ YES, different languages\r\n│   └─ OpenAPI spec → generated client (type safety via codegen)\r\n│\r\n├─ NO, public API\r\n│   └─ REST + OpenAPI → generated SDKs for consumers\r\n│\r\n└─ Complex data needs, multiple frontends\r\n    └─ GraphQL + codegen (flexible queries per client)\r\n\r\nReal-time needed?\r\n│\r\n├─ Server → Client only (notifications, feeds, AI streaming)\r\n│   └─ SSE (simplest, auto-reconnect, works through proxies)\r\n│\r\n├─ Bidirectional (chat, collaboration)\r\n│   └─ WebSocket (need heartbeat + reconnection logic)\r\n│\r\n└─ Simple status polling (\u003C 10 clients)\r\n    └─ React Query refetchInterval (no infrastructure needed)\r\n```\r\n\r\n---\r\n\r\n## 13. Production Hardening (MEDIUM)\r\n\r\n### Health Checks\r\n\r\n```typescript\r\napp.get('\u002Fhealth', (req, res) => res.json({ status: 'ok' }));           \u002F\u002F liveness\r\napp.get('\u002Fready', async (req, res) => {                                   \u002F\u002F readiness\r\n  const checks = {\r\n    database: await checkDb(), redis: await checkRedis(), \r\n  };\r\n  const ok = Object.values(checks).every(c => c.status === 'ok');\r\n  res.status(ok ? 200 : 503).json({ status: ok ? 'ok' : 'degraded', checks });\r\n});\r\n```\r\n\r\n### Graceful Shutdown\r\n\r\n```typescript\r\nprocess.on('SIGTERM', async () => {\r\n  logger.info('SIGTERM received');\r\n  server.close();              \u002F\u002F stop new connections\r\n  await drainConnections();    \u002F\u002F finish in-flight\r\n  await closeDatabase();\r\n  process.exit(0);\r\n});\r\n```\r\n\r\n### Security Checklist\r\n\r\n```\r\n✅ CORS: explicit origins (never '*' in production)\r\n✅ Security headers (helmet \u002F equivalent)\r\n✅ Rate limiting on public endpoints\r\n✅ Input validation on ALL endpoints (trust nothing)\r\n✅ HTTPS enforced\r\n❌ Never expose internal errors to clients\r\n```\r\n\r\n---\r\n\r\n## Anti-Patterns\r\n\r\n| # | ❌ Don't | ✅ Do Instead |\r\n|---|---------|--------------|\r\n| 1 | Business logic in routes\u002Fcontrollers | Move to service layer |\r\n| 2 | `process.env` scattered everywhere | Centralized typed config |\r\n| 3 | `console.log` for logging | Structured JSON logger |\r\n| 4 | Generic `Error('oops')` | Typed error hierarchy |\r\n| 5 | Direct DB calls in controllers | Repository pattern |\r\n| 6 | No input validation | Validate at boundary (Zod\u002FPydantic) |\r\n| 7 | Catching errors silently | Log + rethrow or return error |\r\n| 8 | No health check endpoints | `\u002Fhealth` + `\u002Fready` |\r\n| 9 | Hardcoded config\u002Fsecrets | Environment variables |\r\n| 10 | No graceful shutdown | Handle SIGTERM properly |\r\n| 11 | Hardcode API URL in frontend | Environment variable (`NEXT_PUBLIC_API_URL`) |\r\n| 12 | Store JWT in localStorage | Memory + httpOnly refresh cookie |\r\n| 13 | Show raw API errors to users | Map to human-readable messages |\r\n| 14 | Retry 4xx errors | Only retry 5xx (server failures) |\r\n| 15 | Skip loading states | Skeleton\u002Fspinner while fetching |\r\n| 16 | Upload large files through API server | Presigned URL → direct to S3 |\r\n| 17 | Poll for real-time data | SSE or WebSocket |\r\n| 18 | Duplicate types frontend + backend | Shared types, tRPC, or OpenAPI codegen |\r\n\r\n---\r\n\r\n## Common Issues\r\n\r\n### Issue 1: \"Where does this business rule go?\"\r\n\r\n**Rule:** If it involves HTTP (request parsing, status codes, headers) → controller. If it involves business decisions (pricing, permissions, rules) → service. If it touches the database → repository.\r\n\r\n### Issue 2: \"Service is getting too big\"\r\n\r\n**Symptom:** One service file > 500 lines with 20+ methods.\r\n\r\n**Fix:** Split by sub-domain. `OrderService` → `OrderCreationService` + `OrderFulfillmentService` + `OrderQueryService`. Each focused on one workflow.\r\n\r\n### Issue 3: \"Tests are slow because they hit the database\"\r\n\r\n**Fix:** Unit tests mock the repository layer (fast). Integration tests use test containers or transaction rollback (real DB, still fast). Never mock the service layer in integration tests.\r\n\r\n---\r\n\r\n## Reference Documents\r\n\r\nThis skill includes deep-dive references for specialized topics. Read the relevant reference when you need detailed guidance.\r\n\r\n| Need to… | Reference |\r\n|----------|-----------|\r\n| Write backend tests (unit, integration, e2e, contract, performance) | [references\u002Ftesting-strategy.md](references\u002Ftesting-strategy.md) |\r\n| Validate a release before deployment (6-gate checklist) | [references\u002Frelease-checklist.md](references\u002Frelease-checklist.md) |\r\n| Choose a tech stack (language, framework, database, infra) | [references\u002Ftechnology-selection.md](references\u002Ftechnology-selection.md) |\r\n| Build with Django \u002F DRF (models, views, serializers, admin) | [references\u002Fdjango-best-practices.md](references\u002Fdjango-best-practices.md) |\r\n| Design REST\u002FGraphQL\u002FgRPC endpoints (URLs, status codes, pagination) | [references\u002Fapi-design.md](references\u002Fapi-design.md) |\r\n| Design database schema, indexes, migrations, multi-tenancy | [references\u002Fdb-schema.md](references\u002Fdb-schema.md) |\r\n| Auth flow (JWT bearer, token refresh, Next.js SSR, RBAC, middleware order) | [references\u002Fauth-flow.md](references\u002Fauth-flow.md) |\r\n| CORS config, env vars per environment, common CORS issues | [references\u002Fenvironment-management.md](references\u002Fenvironment-management.md) |\r\n",{"name":5,"license":14,"metadata":23,"description":34,"description_en":35,"description_zh":36},{"sources":24,"version":32,"category":33},[25,26,27,28,29,30,31],"The Twelve-Factor App (12factor.net)","Clean Architecture (Robert C. Martin)","Domain-Driven Design (Eric Evans)","Patterns of Enterprise Application Architecture (Martin Fowler)","Martin Fowler (Testing Pyramid, Contract Tests)","Google SRE Handbook (Release Engineering)","ThoughtWorks Technology Radar","1.0.0","full-stack","Full-stack backend architecture and frontend-backend integration guide.\nTRIGGER when: building a full-stack app, creating REST API with frontend, scaffolding backend service,\nbuilding todo app, building CRUD app, building real-time app, building chat app,\nExpress + React, Next.js API, Node.js backend, Python backend, Go backend,\ndesigning service layers, implementing error handling, managing config\u002Fauth,\nsetting up API clients, implementing auth flows, handling file uploads,\nadding real-time features (SSE\u002FWebSocket), hardening for production.\nDO NOT TRIGGER when: pure frontend UI work, pure CSS\u002Fstyling, database schema only.\n","Full-stack architecture guide (REST API, Express, React, Next.js)","全栈应用架构与开发指南","main","5e45653f59a2e4a2a65f575e8aaf7637165674d5","workbuddy\u002Fexperts\u002Fsenior-developer\u002Fskills\u002Ffullstack-dev",39,"https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills","https:\u002F\u002Fgithub.com\u002Fahang1598","2026-11-06 15:01:27",{"source":8,"skillName":5,"commands":45,"prompt":55,"zipAvailable":56},[46,49,52],{"tool":47,"command":48},"npx","npx skills add ahang1598\u002Fdoubao-workbuddy-qwenwork-skills --skill fullstack-dev",{"tool":50,"command":51},"bunx","bunx skills add ahang1598\u002Fdoubao-workbuddy-qwenwork-skills --skill fullstack-dev",{"tool":53,"command":54},"pnpm","pnpm dlx skills add ahang1598\u002Fdoubao-workbuddy-qwenwork-skills --skill fullstack-dev","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fexperts\u002Fsenior-developer\u002Fskills\u002Ffullstack-dev\u002FSKILL.md",true,[58,64,68,72,76,80,84,88],{"path":59,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":62,"sourceHtmlUrl":63},"references\u002Fapi-design.md","REFERENCE","参考文档",14354,"https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fexperts\u002Fsenior-developer\u002Fskills\u002Ffullstack-dev\u002Freferences\u002Fapi-design.md",{"path":65,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":66,"sourceHtmlUrl":67},"references\u002Fauth-flow.md",4731,"https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fexperts\u002Fsenior-developer\u002Fskills\u002Ffullstack-dev\u002Freferences\u002Fauth-flow.md",{"path":69,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":70,"sourceHtmlUrl":71},"references\u002Fdb-schema.md",24106,"https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fexperts\u002Fsenior-developer\u002Fskills\u002Ffullstack-dev\u002Freferences\u002Fdb-schema.md",{"path":73,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":74,"sourceHtmlUrl":75},"references\u002Fdjango-best-practices.md",13518,"https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fexperts\u002Fsenior-developer\u002Fskills\u002Ffullstack-dev\u002Freferences\u002Fdjango-best-practices.md",{"path":77,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":78,"sourceHtmlUrl":79},"references\u002Fenvironment-management.md",2387,"https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fexperts\u002Fsenior-developer\u002Fskills\u002Ffullstack-dev\u002Freferences\u002Fenvironment-management.md",{"path":81,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":82,"sourceHtmlUrl":83},"references\u002Frelease-checklist.md",8119,"https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fexperts\u002Fsenior-developer\u002Fskills\u002Ffullstack-dev\u002Freferences\u002Frelease-checklist.md",{"path":85,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":86,"sourceHtmlUrl":87},"references\u002Ftechnology-selection.md",9477,"https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fexperts\u002Fsenior-developer\u002Fskills\u002Ffullstack-dev\u002Freferences\u002Ftechnology-selection.md",{"path":89,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":90,"sourceHtmlUrl":91},"references\u002Ftesting-strategy.md",12222,"https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fexperts\u002Fsenior-developer\u002Fskills\u002Ffullstack-dev\u002Freferences\u002Ftesting-strategy.md",[93,101,110,117,125,133],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":97,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":18},"01M79AD9QRFFSMWE9ZHAV6049W","xiaoyi-pdf-win","PDF 综合处理技能，处理文档生成、编辑、安全与解析。 适用情形： 1. 创建与排版：从零生成报告、提案、简历等 PDF，或对现有文档重新排版美化； 2. 表单与水印：自动填写 PDF 表单字段，或添加文字\u002F图片水印（如打水印、标机密）； 3. 页面管理：合并多个 PDF，或拆分、提取指定页码； 4. 安全控制：为 PDF 添加密码（加密）或移除密码（解密）； 5. 内容提取：从 PDF 中提取纯文本或导出表格数据。 只要用户诉求涉及生成、排版、美化、转换、拼接、拆分 PDF，或处理水印、表单、密码，必须触发本技能。","https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fxiaoyiwork\u002Fskills\u002Fxiaoyi-pdf-win\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fxiaoyiwork\u002Fskills\u002Fxiaoyi-pdf-win\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":105,"licenseFileUrl":106,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":18},"01M79A6AXW44V3H0DVPHXE32YE","skill-creator-win","Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fxiaoyiwork\u002Fskills\u002Fskill-creator-win\u002Flicense.txt","https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fxiaoyiwork\u002Fskills\u002Fskill-creator-win\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":18},"01M79A5DRYQNS61T7W9TA1ZNPY","markitdown-win","Convert files and office documents to Markdown. Supports PDF, DOCX, PPTX, XLSX, images (with OCR), audio (with transcription), HTML, CSV, JSON, XML, ZIP, YouTube URLs, EPubs and more.","https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fxiaoyiwork\u002Fskills\u002Fmarkitdown-win\u002FSKILL.md",[],[],{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":121,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":18},"01M79A35XSZGH60W5XQE6CR0Q5","minimax-docx","Professional DOCX document creation, editing, and formatting using OpenXML SDK (.NET). Three pipelines: (A) create new documents from scratch, (B) fill\u002Fedit content in existing documents, (C) apply template formatting with XSD validation gate-check. MUST use this skill whenever the user wants to produce, modify, or format a Word document — including when they say \"write a report\", \"draft a proposal\", \"make a contract\", \"fill in this form\", \"reformat to match this template\", or any task whose final output is a .docx file. Even if the user doesn't mention \"docx\" explicitly, if the task implies a printable\u002Fformal document, use this skill.","https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fxiaoyiwork\u002Fexperts\u002Fdocument-generation-expert\u002Fskills\u002Fminimax-docx\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fxiaoyiwork\u002Fexperts\u002Fdocument-generation-expert\u002Fskills\u002Fminimax-docx\u002FSKILL.md",[],[],{"skillNo":126,"name":127,"nameZh":6,"description":128,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":129,"sourceHtmlUrl":130,"categories":131,"keywords":132,"publishedAt":18},"01M79A1WEZ6HQWMH6KDE32Q928","skillhub-daily","SkillHub 每日推荐 - 扫描 skillhub.cn 全站 Top100 + 7 大分类各 Top20（共 240 个 Skill），\n基于用户痛点精准推荐高价值 Skill，支持 IMA\u002F飞书\u002FObsidian 多通道存储。\n触发词：每日推荐、SkillHub 日报、潜力Skill、帮我推荐技能。\n支持两种使用模式：常规 Skills 模式（对话触发）\u002F Cron 定时任务模式。","https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fskills\u002Fskillhub-daily\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fskills\u002Fskillhub-daily\u002FSKILL.md",[],[],{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":139,"publishedAt":18},"01M799ZCAYFF5A73KRC4G4VMWX","deep-research","Structured deep research workflow with human-in-the-loop control. Use \u002Fresearch to generate research outline, \u002Fresearch-deep for parallel web search across items, \u002Fresearch-report to compile markdown reports. Supports academic research, benchmark research, technology selection, market analysis, and due diligence. Triggers: 'deep research', 'research topic', 'benchmark comparison', 'technology survey', 'market analysis'. Requires: WebSearch capability.","https:\u002F\u002Fgithub.com\u002Fahang1598\u002Fdoubao-workbuddy-qwenwork-skills\u002Fblob\u002Fmain\u002Fworkbuddy\u002Fskills\u002Fdeep-research\u002FSKILL.md",[],[]]