{
  "openapi": "3.0.0",
  "info": {
    "title": "ResolvAI Auth API",
    "version": "1.0.0",
    "description": "ResolvAI Authentication and User Management API Documentation",
    "contact": {
      "name": "ResolvAI Team",
      "email": "support@resolvai.app"
    }
  },
  "servers": [
    {
      "url": "https://resolvai.ngrok.app",
      "description": "Authentication Service URL"
    }
  ],
  "tags": [
    {
      "name": "App",
      "description": "Application-level APIs for end users"
    },
    {
      "name": "Admin",
      "description": "Administrative APIs (admin access required)"
    },
    {
      "name": "Subscriptions",
      "description": "Subscription state APIs backed by RevenueCat (Apple/Google/Stripe)."
    },
    {
      "name": "Webhooks",
      "description": "Inbound webhooks from external providers (e.g. RevenueCat)."
    },
    {
      "name": "Cron",
      "description": "Scheduled background jobs (Vercel cron / Bearer auth)."
    },
    {
      "name": "Agents",
      "description": "AI Agent management and chat APIs"
    },
    {
      "name": "OAuth2",
      "description": "OAuth2 provider and integration management"
    },
    {
      "name": "Profile",
      "description": "User profile management APIs"
    },
    {
      "name": "Devices",
      "description": "Device and security management APIs"
    },
    {
      "name": "Tools",
      "description": "System tools and metadata APIs"
    },
    {
      "name": "ExternalSubmissions",
      "description": "External waitlist/feedback submissions (admin-only)"
    },
    {
      "name": "Health",
      "description": "V1.4 health domain APIs (health profile, energy, graded chests, check-ins)"
    },
    {
      "name": "V2",
      "description": "All /api/v2 endpoints (the new-app contract). Each endpoint also appears under its business tag (Memory / Health / User / Shop …)."
    }
  ],
  "components": {
    "securitySchemes": {
      "sessionAuth": {
        "type": "apiKey",
        "in": "cookie",
        "name": "better-auth.session_token",
        "description": "Session-based authentication passed via cookie"
      },
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT",
        "description": "Bearer token authentication"
      }
    },
    "schemas": {
      "Error": {
        "type": "object",
        "properties": {
          "success": {
            "type": "boolean",
            "example": false
          },
          "error": {
            "type": "string",
            "example": "VALIDATION_ERROR"
          },
          "message": {
            "type": "string",
            "example": "Invalid request parameters"
          }
        }
      },
      "Success": {
        "type": "object",
        "properties": {
          "success": {
            "type": "boolean",
            "example": true
          },
          "message": {
            "type": "string",
            "example": "Operation completed successfully"
          }
        }
      },
      "HealthProfile": {
        "type": "object",
        "description": "V1.4 user health profile (DEV-937).",
        "properties": {
          "userId": {
            "type": "string",
            "description": "Owner user id (PK).",
            "example": "user_123"
          },
          "height": {
            "type": "number",
            "nullable": true,
            "description": "Height in cm (may be fractional).",
            "example": 175
          },
          "goalWeight": {
            "type": "integer",
            "nullable": true,
            "description": "Goal weight in grams (integer; client divides by 1000 for kg).",
            "example": 68500
          },
          "goal": {
            "type": "string",
            "nullable": true,
            "enum": [
              "lose_weight",
              "maintain",
              "gain_weight"
            ],
            "description": "Q1 onboarding: primary goal (single-select)."
          },
          "activityLevel": {
            "type": "string",
            "nullable": true,
            "enum": [
              "sedentary",
              "lightly_active",
              "active",
              "very_active"
            ],
            "description": "V2 onboarding: day-to-day activity level (single-select). Required input for the worker budget formula."
          },
          "dietPreference": {
            "type": "array",
            "nullable": true,
            "items": {
              "type": "string",
              "enum": [
                "balanced",
                "high_protein",
                "low_carb",
                "keto",
                "paleo",
                "mediterranean",
                "pescatarian",
                "vegetarian",
                "vegan"
              ]
            },
            "description": "V2 onboarding: eating style (multi-select)."
          },
          "allergies": {
            "type": "array",
            "nullable": true,
            "items": {
              "type": "string"
            },
            "description": "V2 onboarding: foods to avoid. 8 preset slugs (dairy/eggs/gluten/peanuts/tree_nuts/fish/shellfish/soy) mixed with free text (<=40 chars each, <=20 entries). Hard constraint for meal suggestions."
          },
          "mealsPerDay": {
            "type": "integer",
            "nullable": true,
            "minimum": 1,
            "maximum": 5,
            "description": "V2 onboarding: meals per day."
          },
          "mealTimes": {
            "type": "array",
            "nullable": true,
            "items": {
              "type": "string"
            },
            "example": [
              "07:00",
              "19:00"
            ],
            "description": "V2 onboarding: meal times as 24h \"HH:MM\" local wall-clock, ordered by MEAL ORDER (not clock order — overnight windows are legal). Currently always 2 entries = [first meal, last meal]; the eating window is always the first and last entry."
          },
          "eatingChallenges": {
            "type": "array",
            "nullable": true,
            "items": {
              "type": "string",
              "enum": [
                "cravings_snacking",
                "too_busy_to_cook",
                "eating_out_a_lot",
                "portion_control",
                "emotional_eating",
                "sweet_tooth"
              ]
            },
            "description": "V2 onboarding: biggest eating challenges (multi-select)."
          },
          "barrier": {
            "type": "array",
            "nullable": true,
            "items": {
              "type": "string",
              "enum": [
                "cravings",
                "low_motivation",
                "no_plan",
                "bad_habits"
              ]
            },
            "description": "DEPRECATED (not collected by V2 onboarding) — Q2 onboarding: biggest challenge (multi-select)."
          },
          "sleepTargetTime": {
            "type": "string",
            "nullable": true,
            "example": "23:00",
            "description": "DEPRECATED (not collected by V2 onboarding) — Q3 onboarding: target bedtime, 24h \"HH:MM\"."
          },
          "wakeTargetTime": {
            "type": "string",
            "nullable": true,
            "example": "07:00",
            "description": "DEPRECATED (not collected by V2 onboarding) — Q3 onboarding: target wake-up time, 24h \"HH:MM\"."
          },
          "mealFrequency": {
            "type": "string",
            "nullable": true,
            "enum": [
              "one_to_two",
              "three",
              "four_plus",
              "varies"
            ],
            "description": "DEPRECATED (not collected by V2 onboarding) — Q4 onboarding: meal frequency (single-select)."
          },
          "exerciseComfortLevel": {
            "type": "string",
            "nullable": true,
            "enum": [
              "beginner",
              "light",
              "moderate",
              "active"
            ],
            "description": "DEPRECATED (not collected by V2 onboarding) — Q5 onboarding: exercise comfort (legacy; kept during transition, mapped forward to exerciseFrequency)."
          },
          "exerciseFrequency": {
            "type": "string",
            "nullable": true,
            "enum": [
              "almost_never",
              "one_to_two",
              "three_to_four",
              "five_plus"
            ],
            "description": "DEPRECATED (not collected by V2 onboarding) — Q5 onboarding: exercise frequency (DEV-1145). Preferred over exerciseComfortLevel; derived from it for legacy rows."
          },
          "createdAt": {
            "type": "string",
            "format": "date-time",
            "description": "Row creation time."
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time",
            "description": "Last update time."
          }
        }
      },
      "EnergyState": {
        "type": "object",
        "description": "V1.4 燃脂力 energy state (DEV-939). Backend maps energy→level for display; it does NOT gate features.",
        "properties": {
          "energy": {
            "type": "integer",
            "description": "Cumulative EXP (+10 per completed task)",
            "example": 30
          },
          "level": {
            "type": "integer",
            "description": "Energy level mapped from EXP (Lv1-10 at 0/10/30/50/100/200/350/550/800/1100; new users start at Lv1). Display only — it unlocks nothing and the backend does NOT gate on it.",
            "example": 3
          },
          "nextLevelExp": {
            "type": "integer",
            "nullable": true,
            "description": "EXP threshold of the next level; null at max level.",
            "example": 50
          }
        }
      },
      "Chest": {
        "type": "object",
        "description": "V1.4 graded daily chest (DEV-938).",
        "properties": {
          "id": {
            "type": "integer",
            "description": "Chest id.",
            "example": 101
          },
          "tier": {
            "type": "string",
            "enum": [
              "bronze",
              "silver",
              "gold"
            ],
            "description": "Tier by that day's completed-task count: 3→bronze, 4→silver, 5→gold.",
            "example": "bronze"
          },
          "status": {
            "type": "string",
            "enum": [
              "locked",
              "unlocked",
              "opened"
            ],
            "description": "Lifecycle: unlocked (granted, not opened) → opened (PATCH to open). locked reserved.",
            "example": "unlocked"
          },
          "grantedForDate": {
            "type": "string",
            "format": "date",
            "description": "User-local day (YYYY-MM-DD) the chest belongs to; grouping key for daily reset.",
            "example": "2026-06-11"
          },
          "openedAt": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "When opened; null until opened."
          },
          "rewards": {
            "type": "object",
            "description": "Populated on open. Fragments when an active fragment_exchange campaign has drops for the user; otherwise a per-tier fallback seed reward (seeds > 0, fragments empty) so an open is never empty.",
            "properties": {
              "seeds": {
                "type": "integer",
                "description": "Fallback seeds, paid only when no fragments dropped (no active campaign / pool exhausted).",
                "example": 0
              },
              "fragments": {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "outfitItemId": {
                      "type": "integer",
                      "example": 42
                    },
                    "quantity": {
                      "type": "integer",
                      "example": 1
                    }
                  }
                }
              }
            }
          }
        }
      },
      "WeightReport": {
        "type": "object",
        "description": "V1.4 weight progress report (DEV-955/956). Summary fields are all-time; trend + periodDelta cover the range window. weekOverWeekDelta / monthOverMonthDelta are calendar week-over-week / month-over-month deltas (Mon-start week / 1st-of-month, user tz), independent of range. Pure calculation, no LLM.",
        "properties": {
          "range": {
            "type": "string",
            "enum": [
              "week",
              "month"
            ],
            "description": "Trend window: week = last 7 days, month = last 30. Summary fields are all-time regardless."
          },
          "current": {
            "type": "integer",
            "nullable": true,
            "description": "Latest recorded weight, integer grams; null if no records.",
            "example": 74000
          },
          "start": {
            "type": "integer",
            "nullable": true,
            "description": "Earliest recorded weight (integer grams).",
            "example": 80000
          },
          "goal": {
            "type": "integer",
            "nullable": true,
            "description": "Goal weight from health profile, integer grams; null if unset.",
            "example": 60000
          },
          "lost": {
            "type": "integer",
            "nullable": true,
            "description": "start - current (grams lost; positive = progress)",
            "example": 6000
          },
          "toGo": {
            "type": "integer",
            "nullable": true,
            "description": "current - goal (grams remaining); null if no goal",
            "example": 14000
          },
          "progress": {
            "type": "number",
            "nullable": true,
            "description": "0-100%; null if no goal or start <= goal",
            "example": 30
          },
          "trend": {
            "type": "array",
            "description": "Weight points within the range window (ascending).",
            "items": {
              "type": "object",
              "properties": {
                "date": {
                  "type": "string",
                  "format": "date",
                  "example": "2026-06-13"
                },
                "weight": {
                  "type": "integer",
                  "example": 74000
                }
              }
            }
          },
          "periodDelta": {
            "type": "integer",
            "nullable": true,
            "description": "current - first-in-window (negative = lost)",
            "example": -2000
          },
          "weekOverWeekDelta": {
            "type": "integer",
            "nullable": true,
            "description": "Calendar week-over-week change in grams (Mon-start weeks, user tz): latest weigh-in this week minus the most recent weigh-in before this week (falls back past an empty previous week). Negative = lost. null if no check-in this week, no prior record, or no records. Independent of `range`.",
            "example": -1500
          },
          "monthOverMonthDelta": {
            "type": "integer",
            "nullable": true,
            "description": "Calendar month-over-month change in grams (1st-of-month start, user tz): latest weigh-in this month minus the most recent weigh-in before this month (falls back past an empty previous month). Negative = lost. null if no check-in this month, no prior record, or no records. Independent of `range`.",
            "example": -3000
          },
          "lastLoggedAt": {
            "type": "string",
            "format": "date",
            "nullable": true,
            "description": "User-local date (YYYY-MM-DD) of the latest check-in; null if no records.",
            "example": "2026-06-13"
          }
        }
      },
      "UserProfile": {
        "type": "object",
        "properties": {
          "userId": {
            "type": "string",
            "example": "user_123"
          },
          "avatarUrl": {
            "type": "string",
            "nullable": true,
            "example": "https://example.com/avatar.jpg"
          },
          "bio": {
            "type": "string",
            "nullable": true,
            "example": "User bio description"
          },
          "gender": {
            "type": "string",
            "nullable": true,
            "enum": [
              "male",
              "female",
              "other"
            ],
            "description": "Canonical gender (DEV-937; edited via PATCH /api/v0/profile). V1.7 起收窄成三值；旧值 them / prefer_not_to_say 写入时归一成 other",
            "example": "female"
          },
          "birthdate": {
            "type": "string",
            "format": "date",
            "nullable": true,
            "description": "V1.4 canonical birthdate YYYY-MM-DD (DEV-937)",
            "example": "1995-08-20"
          },
          "locale": {
            "type": "string",
            "example": "zh-CN"
          },
          "timezone": {
            "type": "string",
            "nullable": true,
            "example": "Asia/Shanghai"
          },
          "location": {
            "type": "object",
            "nullable": true,
            "properties": {
              "latitude": {
                "type": "number",
                "example": 39.9042
              },
              "longitude": {
                "type": "number",
                "example": 116.4074
              }
            },
            "additionalProperties": true,
            "description": "User location coordinates"
          },
          "notificationSettings": {
            "type": "object",
            "nullable": true,
            "properties": {
              "email": {
                "type": "boolean",
                "example": true
              },
              "push": {
                "type": "boolean",
                "example": false
              },
              "phone": {
                "type": "boolean",
                "example": false
              },
              "whatsapp": {
                "type": "boolean",
                "example": false
              }
            }
          },
          "privacySettings": {
            "type": "object",
            "nullable": true,
            "properties": {
              "profileVisible": {
                "type": "boolean",
                "example": true
              },
              "emailVisible": {
                "type": "boolean",
                "example": false
              }
            }
          },
          "metadata": {
            "type": "object",
            "nullable": true,
            "additionalProperties": true,
            "description": "Custom metadata including stripe_customer_id, subscriptions, etc.",
            "example": {
              "stripe_customer_id": "cus_123",
              "subscriptions": {}
            }
          },
          "createdAt": {
            "type": "string",
            "format": "date-time",
            "example": "2024-01-01T00:00:00Z"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time",
            "example": "2024-01-01T00:00:00Z"
          }
        }
      },
      "Device": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "example": "device_123"
          },
          "userId": {
            "type": "string",
            "example": "user_123"
          },
          "deviceId": {
            "type": "string",
            "example": "device_unique_id"
          },
          "token": {
            "type": "string",
            "example": "push_notification_token"
          },
          "platform": {
            "type": "string",
            "enum": [
              "ios",
              "android",
              "web",
              "desktop"
            ],
            "example": "ios"
          },
          "deviceName": {
            "type": "string",
            "nullable": true,
            "example": "iPhone 15 Pro"
          },
          "lastUsedAt": {
            "type": "number",
            "example": 1704067200000
          },
          "isActive": {
            "type": "boolean",
            "example": true
          },
          "isTrusted": {
            "type": "boolean",
            "example": false
          },
          "metadata": {
            "type": "object",
            "nullable": true,
            "properties": {
              "ipAddress": {
                "type": "string",
                "example": "192.168.1.100"
              },
              "userAgent": {
                "type": "string",
                "example": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_1 like Mac OS X)"
              },
              "deviceType": {
                "type": "string",
                "enum": [
                  "mobile",
                  "tablet",
                  "desktop"
                ],
                "example": "mobile"
              },
              "location": {
                "type": "string",
                "example": "Beijing, China"
              }
            }
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "Integration": {
        "type": "object",
        "properties": {
          "provider": {
            "type": "string",
            "example": "google",
            "description": "Third-party service provider"
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "revoked",
              "error"
            ],
            "example": "active",
            "description": "Connection status"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time",
            "example": "2024-01-01T00:00:00Z"
          }
        }
      },
      "Activity": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "example": "activity_123"
          },
          "action": {
            "type": "string",
            "example": "connection_created",
            "description": "Activity type"
          },
          "integrationId": {
            "type": "string",
            "nullable": true,
            "example": "integration_456",
            "description": "Integration ID (optional)"
          },
          "details": {
            "type": "string",
            "nullable": true,
            "example": "Google Drive connection created",
            "description": "Activity details (optional)"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time",
            "example": "2024-01-15T10:30:00Z",
            "description": "Creation timestamp"
          }
        }
      },
      "OAuth2Provider": {
        "type": "object",
        "description": "Admin-facing provider view. `config.clientSecret` is deliberately absent — the plaintext secret never leaves the server; use `hasClientSecret` to tell whether one is stored.",
        "properties": {
          "id": {
            "type": "string",
            "example": "provider_123",
            "description": "Provider ID"
          },
          "name": {
            "type": "string",
            "example": "google",
            "description": "Provider name (unique identifier)"
          },
          "displayName": {
            "type": "string",
            "example": "Google",
            "description": "Display name for the provider"
          },
          "logo": {
            "type": "string",
            "nullable": true,
            "example": "/images/providers/google.png",
            "description": "Logo URL for the provider"
          },
          "hasClientSecret": {
            "type": "boolean",
            "example": true,
            "description": "Whether a client secret is stored. The secret itself is never returned."
          },
          "config": {
            "type": "object",
            "properties": {
              "clientId": {
                "type": "string",
                "example": "client_id_123",
                "description": "OAuth2 client ID"
              },
              "authUrl": {
                "type": "string",
                "format": "uri",
                "example": "https://accounts.google.com/o/oauth2/v2/auth",
                "description": "Authorization URL"
              },
              "tokenUrl": {
                "type": "string",
                "format": "uri",
                "example": "https://oauth2.googleapis.com/token",
                "description": "Token exchange URL"
              },
              "scope": {
                "type": "array",
                "items": {
                  "type": "string"
                },
                "example": [
                  "https://www.googleapis.com/auth/calendar"
                ],
                "description": "OAuth2 scopes"
              },
              "redirectUri": {
                "type": "string",
                "format": "uri",
                "example": "https://example.com/oauth2/callback",
                "description": "Redirect URI after authorization"
              },
              "responseType": {
                "type": "string",
                "enum": [
                  "code",
                  "token"
                ],
                "example": "code",
                "description": "OAuth2 response type"
              },
              "grantType": {
                "type": "string",
                "enum": [
                  "authorization_code",
                  "refresh_token"
                ],
                "example": "authorization_code",
                "description": "OAuth2 grant type"
              },
              "additionalParams": {
                "type": "object",
                "additionalProperties": {
                  "type": "string"
                },
                "nullable": true,
                "description": "Additional OAuth2 parameters"
              },
              "tokenAuthMethod": {
                "type": "string",
                "enum": [
                  "basic",
                  "post"
                ],
                "description": "How client credentials are sent to the token endpoint: 'basic' (default) = Authorization header, 'post' = client_secret_post body"
              }
            },
            "required": [
              "clientId",
              "authUrl",
              "tokenUrl",
              "scope",
              "redirectUri"
            ]
          },
          "isActive": {
            "type": "boolean",
            "example": true,
            "description": "Whether the provider is active"
          },
          "sortOrder": {
            "type": "integer",
            "example": 10,
            "default": 100,
            "description": "Display weight for the client integration list — lower sorts first, ties fall back to displayName. 100 means \"not pinned\"."
          },
          "createdAt": {
            "type": "string",
            "format": "date-time",
            "example": "2024-01-01T00:00:00Z",
            "description": "Creation timestamp"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time",
            "example": "2024-01-01T00:00:00Z",
            "description": "Last update timestamp"
          }
        },
        "required": [
          "id",
          "name",
          "displayName",
          "config",
          "hasClientSecret",
          "isActive"
        ]
      },
      "OAuth2ProvidersResponse": {
        "type": "object",
        "properties": {
          "success": {
            "type": "boolean",
            "example": true
          },
          "providers": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/OAuth2Provider"
            },
            "description": "List of OAuth2 providers"
          }
        },
        "required": [
          "success",
          "providers"
        ]
      },
      "OAuth2ProviderResponse": {
        "type": "object",
        "properties": {
          "success": {
            "type": "boolean",
            "example": true
          },
          "provider": {
            "$ref": "#/components/schemas/OAuth2Provider"
          }
        },
        "required": [
          "success",
          "provider"
        ]
      },
      "CreateOAuth2ProviderRequest": {
        "type": "object",
        "required": [
          "name",
          "displayName",
          "config"
        ],
        "properties": {
          "name": {
            "type": "string",
            "example": "google",
            "description": "Provider name (unique identifier)"
          },
          "displayName": {
            "type": "string",
            "example": "Google",
            "description": "Display name for the provider"
          },
          "logo": {
            "type": "string",
            "nullable": true,
            "example": "/images/providers/google.png",
            "description": "Logo URL for the provider"
          },
          "config": {
            "type": "object",
            "required": [
              "clientId",
              "clientSecret",
              "authUrl",
              "tokenUrl",
              "scope",
              "redirectUri"
            ],
            "properties": {
              "clientId": {
                "type": "string",
                "example": "client_id_123"
              },
              "clientSecret": {
                "type": "string",
                "example": "client_secret_123"
              },
              "authUrl": {
                "type": "string",
                "format": "uri",
                "example": "https://accounts.google.com/o/oauth2/v2/auth"
              },
              "tokenUrl": {
                "type": "string",
                "format": "uri",
                "example": "https://oauth2.googleapis.com/token"
              },
              "scope": {
                "type": "array",
                "items": {
                  "type": "string"
                },
                "example": [
                  "https://www.googleapis.com/auth/calendar"
                ]
              },
              "redirectUri": {
                "type": "string",
                "format": "uri",
                "example": "https://example.com/oauth2/callback"
              },
              "responseType": {
                "type": "string",
                "enum": [
                  "code",
                  "token"
                ],
                "default": "code"
              },
              "grantType": {
                "type": "string",
                "enum": [
                  "authorization_code",
                  "refresh_token"
                ],
                "default": "authorization_code"
              },
              "additionalParams": {
                "type": "object",
                "additionalProperties": {
                  "type": "string"
                },
                "nullable": true
              }
            }
          },
          "isActive": {
            "type": "boolean",
            "default": true,
            "description": "Whether the provider is active"
          },
          "sortOrder": {
            "type": "integer",
            "default": 100,
            "description": "Display weight for the client integration list — lower sorts first. Omit to use 100 (\"not pinned\")."
          }
        }
      },
      "UpdateOAuth2ProviderRequest": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "example": "google",
            "description": "Provider name (unique identifier)"
          },
          "displayName": {
            "type": "string",
            "example": "Google",
            "description": "Display name for the provider"
          },
          "logo": {
            "type": "string",
            "nullable": true,
            "example": "/images/providers/google.png",
            "description": "Logo URL for the provider"
          },
          "config": {
            "type": "object",
            "properties": {
              "clientId": {
                "type": "string",
                "example": "client_id_123"
              },
              "clientSecret": {
                "type": "string",
                "example": "client_secret_123"
              },
              "authUrl": {
                "type": "string",
                "format": "uri",
                "example": "https://accounts.google.com/o/oauth2/v2/auth"
              },
              "tokenUrl": {
                "type": "string",
                "format": "uri",
                "example": "https://oauth2.googleapis.com/token"
              },
              "scope": {
                "type": "array",
                "items": {
                  "type": "string"
                },
                "example": [
                  "https://www.googleapis.com/auth/calendar"
                ]
              },
              "redirectUri": {
                "type": "string",
                "format": "uri",
                "example": "https://example.com/oauth2/callback"
              },
              "responseType": {
                "type": "string",
                "enum": [
                  "code",
                  "token"
                ]
              },
              "grantType": {
                "type": "string",
                "enum": [
                  "authorization_code",
                  "refresh_token"
                ]
              },
              "additionalParams": {
                "type": "object",
                "additionalProperties": {
                  "type": "string"
                },
                "nullable": true
              }
            }
          },
          "isActive": {
            "type": "boolean",
            "example": true,
            "description": "Whether the provider is active"
          },
          "sortOrder": {
            "type": "integer",
            "example": 10,
            "description": "Display weight for the client integration list — lower sorts first. Omitted or empty keeps the stored weight."
          }
        },
        "description": "All fields are optional. Supports flat structure (config fields at root) or nested structure (config object). Any config field that is omitted or sent as an empty string keeps its stored value — in particular an empty `clientSecret` means \"keep the existing secret\", since GET never returns it."
      },
      "Subscription": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "example": "order_123",
            "description": "Order ID"
          },
          "planId": {
            "type": "string",
            "example": "premium_monthly",
            "description": "Subscription plan ID"
          },
          "amount": {
            "type": "string",
            "example": "99.00",
            "description": "Order amount"
          },
          "currency": {
            "type": "string",
            "example": "CNY",
            "description": "Currency code"
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "active",
              "expired",
              "cancelled"
            ],
            "example": "active",
            "description": "Order status"
          },
          "startDate": {
            "type": "string",
            "format": "date-time",
            "example": "2024-01-01T00:00:00Z",
            "description": "Subscription start date"
          },
          "endDate": {
            "type": "string",
            "format": "date-time",
            "example": "2024-12-31T23:59:59Z",
            "description": "Subscription end date"
          },
          "autoRenew": {
            "type": "boolean",
            "example": true,
            "description": "Whether subscription auto-renews"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time",
            "example": "2024-01-01T00:00:00Z",
            "description": "Order creation timestamp"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time",
            "example": "2024-01-01T00:00:00Z",
            "description": "Order last update timestamp"
          },
          "metadata": {
            "type": "object",
            "nullable": true,
            "additionalProperties": true,
            "description": "Additional order metadata (e.g., Stripe session ID)"
          }
        }
      },
      "SubscriptionsResponse": {
        "type": "object",
        "properties": {
          "success": {
            "type": "boolean",
            "example": true
          },
          "subscriptions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Subscription"
            },
            "description": "List of user subscriptions"
          },
          "total": {
            "type": "integer",
            "example": 5,
            "description": "Total number of subscriptions"
          }
        },
        "required": [
          "success",
          "subscriptions",
          "total"
        ]
      },
      "CreateOrderRequest": {
        "type": "object",
        "required": [
          "planId",
          "amount"
        ],
        "properties": {
          "planId": {
            "type": "string",
            "example": "premium_monthly",
            "description": "Subscription plan ID"
          },
          "amount": {
            "type": "string",
            "example": "99.00",
            "description": "Order amount"
          },
          "currency": {
            "type": "string",
            "example": "CNY",
            "description": "Currency code (default: CNY)"
          },
          "successUrl": {
            "type": "string",
            "format": "uri",
            "nullable": true,
            "example": "https://example.com/success",
            "description": "Success redirect URL after payment"
          },
          "cancelUrl": {
            "type": "string",
            "format": "uri",
            "nullable": true,
            "example": "https://example.com/cancel",
            "description": "Cancel redirect URL"
          }
        }
      },
      "CreateSubscriptionResponse": {
        "type": "object",
        "properties": {
          "success": {
            "type": "boolean",
            "example": true
          },
          "data": {
            "type": "object",
            "nullable": true,
            "properties": {
              "sessionId": {
                "type": "string",
                "nullable": true,
                "example": "cs_test_123",
                "description": "Stripe checkout session ID"
              },
              "checkoutUrl": {
                "type": "string",
                "nullable": true,
                "format": "uri",
                "example": "https://checkout.stripe.com/pay/cs_test_123",
                "description": "Stripe checkout URL"
              }
            }
          },
          "error": {
            "type": "string",
            "nullable": true,
            "example": null,
            "description": "Error message if operation failed"
          },
          "code": {
            "type": "string",
            "nullable": true,
            "example": "SUBSCRIPTION_ALREADY_ACTIVE",
            "description": "Error code if operation failed"
          }
        }
      },
      "SubscriptionRowDTO": {
        "type": "object",
        "description": "One active/trialing/in_grace_period subscription row owned by the user.",
        "properties": {
          "provider": {
            "type": "string",
            "enum": [
              "apple",
              "google",
              "stripe"
            ],
            "example": "apple"
          },
          "productId": {
            "type": "string",
            "example": "kicker_pro_subscribe_m",
            "description": "Store-issued product identifier (App Store Connect / Google Play / Stripe price id)."
          },
          "planId": {
            "type": "string",
            "enum": [
              "pro_monthly",
              "pro_yearly"
            ],
            "example": "pro_monthly",
            "description": "Internal plan identifier resolved from productId via the productId→planId map."
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "trialing",
              "in_grace_period"
            ],
            "example": "active"
          },
          "currentPeriodEnd": {
            "type": "string",
            "format": "date-time",
            "example": "2026-06-09T00:00:00.000Z",
            "description": "ISO timestamp when the current paid period ends."
          },
          "willRenew": {
            "type": "boolean",
            "example": true,
            "description": "False once the user has cancelled but the period has not yet ended."
          },
          "isTrial": {
            "type": "boolean",
            "example": false
          },
          "trialEnd": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "example": null
          },
          "originalTransactionId": {
            "type": "string",
            "example": "1000000123456789",
            "description": "Store-side original transaction id; stable across renewals."
          }
        },
        "required": [
          "provider",
          "productId",
          "planId",
          "status",
          "currentPeriodEnd",
          "willRenew",
          "isTrial",
          "trialEnd",
          "originalTransactionId"
        ]
      },
      "AggregatedSubscriptionState": {
        "type": "object",
        "description": "Caller-effective subscription state derived from local pay_subscription rows. When the user has no active/trialing/in_grace_period rows with currentPeriodEnd in the future, isPro is false and all representative fields are null.",
        "properties": {
          "isPro": {
            "type": "boolean",
            "example": true,
            "description": "Whether the user is currently entitled to Pro features."
          },
          "provider": {
            "type": "string",
            "enum": [
              "apple",
              "google",
              "stripe"
            ],
            "nullable": true,
            "example": "apple"
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "trialing",
              "in_grace_period",
              "expired",
              "paused"
            ],
            "nullable": true,
            "example": "active"
          },
          "planId": {
            "type": "string",
            "enum": [
              "pro_monthly",
              "pro_yearly"
            ],
            "nullable": true,
            "example": "pro_monthly"
          },
          "currentPeriodEnd": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "example": "2026-06-09T00:00:00.000Z"
          },
          "willRenew": {
            "type": "boolean",
            "example": true
          },
          "isTrial": {
            "type": "boolean",
            "example": false
          },
          "trialEnd": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "example": null
          },
          "originalTransactionId": {
            "type": "string",
            "nullable": true,
            "example": "1000000123456789"
          },
          "subscriptions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SubscriptionRowDTO"
            },
            "description": "All currently-effective rows for this user, sorted by currentPeriodEnd desc."
          }
        },
        "required": [
          "isPro",
          "provider",
          "status",
          "planId",
          "currentPeriodEnd",
          "willRenew",
          "isTrial",
          "trialEnd",
          "originalTransactionId",
          "subscriptions"
        ]
      },
      "AggregatedSubscriptionStateResponse": {
        "type": "object",
        "description": "Standard envelope wrapping the aggregated subscription state.",
        "properties": {
          "success": {
            "type": "boolean",
            "example": true
          },
          "data": {
            "$ref": "#/components/schemas/AggregatedSubscriptionState"
          },
          "message": {
            "type": "string",
            "nullable": true
          }
        },
        "required": [
          "success",
          "data"
        ]
      },
      "LinkRevenueCatResponse": {
        "type": "object",
        "description": "No-op stub response. The mobile client already aliases the RevenueCat anonymous id to userId via Purchases.logIn(userId), so this endpoint just confirms identity is linked.",
        "properties": {
          "success": {
            "type": "boolean",
            "example": true
          },
          "data": {
            "type": "object",
            "properties": {
              "linked": {
                "type": "boolean",
                "example": true
              }
            },
            "required": [
              "linked"
            ]
          }
        },
        "required": [
          "success",
          "data"
        ]
      },
      "AgentConfig": {
        "type": "object",
        "properties": {
          "model": {
            "type": "string",
            "example": "gpt-5-nano",
            "description": "Model name"
          },
          "systemPrompt": {
            "type": "string",
            "example": "You are a helpful assistant.",
            "description": "System prompt for the agent"
          },
          "temperature": {
            "type": "number",
            "example": 0.7,
            "minimum": 0,
            "maximum": 2,
            "description": "Temperature setting for the model"
          },
          "thinkingBudget": {
            "type": "integer",
            "example": 0,
            "minimum": 0,
            "description": "Thinking budget in tokens, passed through by the app's on-device Gemini analysis; 0 = thinking off"
          },
          "maxSteps": {
            "type": "number",
            "example": 10,
            "minimum": 1,
            "maximum": 50,
            "description": "Maximum steps the agent can take"
          },
          "toolChoice": {
            "oneOf": [
              {
                "type": "string",
                "enum": [
                  "auto",
                  "required",
                  "none"
                ]
              },
              {
                "type": "object",
                "properties": {
                  "type": {
                    "type": "string",
                    "enum": [
                      "tool"
                    ]
                  },
                  "toolName": {
                    "type": "string"
                  }
                }
              }
            ],
            "example": "auto",
            "description": "Tool choice strategy"
          },
          "stopWhen": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "type": {
                  "type": "string",
                  "enum": [
                    "stepCount"
                  ]
                },
                "maxSteps": {
                  "type": "number"
                }
              }
            },
            "description": "Conditions to stop agent execution"
          },
          "tools": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "name": {
                  "type": "string"
                },
                "enabled": {
                  "type": "boolean"
                },
                "config": {
                  "type": "object",
                  "additionalProperties": true
                }
              }
            },
            "description": "Available tools for the agent"
          }
        }
      },
      "Agent": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "example": "agent_123"
          },
          "name": {
            "type": "string",
            "example": "Customer Support Agent"
          },
          "description": {
            "type": "string",
            "nullable": true,
            "example": "AI assistant for customer support"
          },
          "configuration": {
            "$ref": "#/components/schemas/AgentConfig"
          },
          "isActive": {
            "type": "boolean",
            "example": true
          },
          "createdBy": {
            "type": "string",
            "example": "user_123"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "AgentsResponse": {
        "type": "object",
        "properties": {
          "agents": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Agent"
            }
          },
          "total": {
            "type": "number",
            "example": 100
          },
          "page": {
            "type": "number",
            "example": 1
          },
          "limit": {
            "type": "number",
            "example": 10
          }
        }
      },
      "CreateAgentRequest": {
        "type": "object",
        "required": [
          "name",
          "configuration"
        ],
        "properties": {
          "name": {
            "type": "string",
            "example": "Customer Support Agent"
          },
          "description": {
            "type": "string",
            "nullable": true,
            "example": "AI assistant for customer support"
          },
          "configuration": {
            "$ref": "#/components/schemas/AgentConfig"
          }
        }
      },
      "UpdateAgentRequest": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "example": "Customer Support Agent"
          },
          "description": {
            "type": "string",
            "nullable": true,
            "example": "AI assistant for customer support"
          },
          "configuration": {
            "$ref": "#/components/schemas/AgentConfig"
          }
        }
      },
      "MemoryContent": {
        "type": "object",
        "properties": {
          "text": {
            "type": "string",
            "description": "Full text content"
          },
          "summary": {
            "type": "string",
            "description": "Short summary of the content"
          },
          "keywords": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Extracted keywords"
          },
          "entities": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "type": {
                  "type": "string",
                  "example": "person"
                },
                "value": {
                  "type": "string",
                  "example": "John Doe"
                },
                "confidence": {
                  "type": "number",
                  "minimum": 0,
                  "maximum": 1,
                  "example": 0.95
                }
              }
            },
            "description": "Extracted entities with confidence scores"
          }
        }
      },
      "AttributeDelta": {
        "type": "object",
        "description": "Pre-computed attribute growth delta, keyed by attribute name. Values are rounded to 1 decimal place.",
        "properties": {
          "fitness": {
            "type": "number",
            "example": 1.2
          },
          "logic": {
            "type": "number",
            "example": 0.8
          },
          "creativity": {
            "type": "number",
            "example": 1.5
          },
          "empathy": {
            "type": "number",
            "example": 0.9
          },
          "discipline": {
            "type": "number",
            "example": 1.1
          }
        },
        "additionalProperties": false
      },
      "MemoryItem": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "description": "Memory/task id.",
            "example": "mem_abc123"
          },
          "userId": {
            "type": "string",
            "description": "Owner user id.",
            "example": "user_xyz"
          },
          "channelLabel": {
            "type": "string",
            "description": "Free-text topic/theme (e.g. \"Health\", \"Work\"). User-editable.",
            "example": "telegram"
          },
          "refId": {
            "type": "string",
            "description": "Source reference id; unique together with channelLabel.",
            "example": "ref_001"
          },
          "type": {
            "type": "string",
            "enum": [
              "action",
              "memory",
              "fact",
              "task",
              "plan"
            ],
            "description": "Memory kind. Daily tasks / check-ins are type \"task\"."
          },
          "title": {
            "type": "string",
            "description": "Task/memory title.",
            "example": "Morning run"
          },
          "dueDate": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "Scheduled/ due time; null if none."
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "done",
              "ignored",
              "overridden",
              "unprocessed"
            ],
            "description": "Lifecycle. \"done\" is the switch that triggers completion side-effects (energy / chest / check-in persistence)."
          },
          "labels": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "User labels."
          },
          "tags": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "System/agent tags."
          },
          "priority": {
            "type": "integer",
            "description": "Priority; 0 is valid.",
            "example": 1
          },
          "description": {
            "type": "string",
            "nullable": true,
            "description": "Long-form description of the task/memory."
          },
          "healthType": {
            "type": "string",
            "enum": [
              "weight",
              "diet",
              "exercise",
              "sleep",
              "other"
            ],
            "description": "V1.4 health domain classification (DEV-939).",
            "example": "exercise"
          },
          "grade": {
            "type": "string",
            "nullable": true,
            "enum": [
              "in_range",
              "below",
              "above",
              "met",
              "on_time",
              "late"
            ],
            "description": "Per-completion quality verdict, frozen at the first done-transition (client sends it on the completion PATCH); null if none was sent. For seed-reward retrospection/analytics."
          },
          "analysis": {
            "type": "object",
            "nullable": true,
            "description": "V1.4 diet/exercise check-in record + async analysis (DEV-965/966). Present only for diet/exercise tasks that have a check-in; otherwise null.",
            "properties": {
              "status": {
                "type": "string",
                "enum": [
                  "pending",
                  "processing",
                  "completed",
                  "failed"
                ],
                "description": "Analysis lifecycle, advanced asynchronously by kicker-agent-worker: pending → processing → completed/failed. result is null until completed."
              },
              "input": {
                "type": "object",
                "additionalProperties": true,
                "description": "Raw user check-in input. Diet: { inputType?, image?, text? }. Exercise: { source?, text?, duration?, intensity? }."
              },
              "result": {
                "type": "object",
                "nullable": true,
                "additionalProperties": true,
                "description": "Nutrition-level analysis (null until completed). diet: items[] + total {calories(kcal), protein/carbs/fat(grams)}; exercise: {type, duration(min), caloriesBurned(kcal)}."
              }
            }
          },
          "createdAt": {
            "type": "string",
            "format": "date-time",
            "description": "Row creation time."
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time",
            "description": "Last update time."
          },
          "completedAt": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "任务首次完成时刻（status→done 时设）；未完成为 null。"
          },
          "content": {
            "$ref": "#/components/schemas/MemoryContent"
          },
          "metadata": {
            "type": "object",
            "nullable": true,
            "additionalProperties": true,
            "description": "Arbitrary client/agent metadata (merged on update)."
          },
          "attributeDelta": {
            "nullable": true,
            "description": "Pre-computed attribute growth preview. Non-null for tasks created after this feature shipped; null for older tasks.",
            "allOf": [
              {
                "$ref": "#/components/schemas/AttributeDelta"
              }
            ]
          }
        }
      },
      "UIMessagePart": {
        "type": "object",
        "description": "UI message part - can be text, file, tool, reasoning, source, data, or step-start",
        "discriminator": {
          "propertyName": "type"
        },
        "oneOf": [
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "text"
                ],
                "example": "text"
              },
              "text": {
                "type": "string",
                "example": "Hello, I need help"
              },
              "state": {
                "type": "string",
                "enum": [
                  "streaming",
                  "done"
                ]
              },
              "providerMetadata": {
                "type": "object",
                "additionalProperties": true
              }
            },
            "required": [
              "type",
              "text"
            ]
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "reasoning"
                ],
                "example": "reasoning"
              },
              "text": {
                "type": "string",
                "example": "I need to think about this..."
              },
              "state": {
                "type": "string",
                "enum": [
                  "streaming",
                  "done"
                ]
              },
              "providerMetadata": {
                "type": "object",
                "additionalProperties": true
              }
            },
            "required": [
              "type",
              "text"
            ]
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "file"
                ],
                "example": "file"
              },
              "mediaType": {
                "type": "string",
                "example": "image/png"
              },
              "url": {
                "type": "string",
                "example": "https://example.com/file.png"
              },
              "filename": {
                "type": "string",
                "example": "file.png"
              },
              "providerMetadata": {
                "type": "object",
                "additionalProperties": true
              }
            },
            "required": [
              "type",
              "mediaType",
              "url"
            ]
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "pattern": "^tool-"
              },
              "toolCallId": {
                "type": "string"
              },
              "state": {
                "type": "string",
                "enum": [
                  "input-streaming",
                  "input-available",
                  "output-available",
                  "output-error"
                ]
              },
              "input": {
                "type": "object",
                "additionalProperties": true
              },
              "output": {
                "type": "object",
                "additionalProperties": true
              },
              "errorText": {
                "type": "string"
              },
              "providerExecuted": {
                "type": "boolean"
              },
              "callProviderMetadata": {
                "type": "object",
                "additionalProperties": true
              }
            },
            "required": [
              "type",
              "toolCallId",
              "state"
            ]
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "dynamic-tool"
                ],
                "example": "dynamic-tool"
              },
              "toolName": {
                "type": "string",
                "example": "custom_tool"
              },
              "toolCallId": {
                "type": "string"
              },
              "state": {
                "type": "string",
                "enum": [
                  "input-streaming",
                  "input-available",
                  "output-available",
                  "output-error"
                ]
              },
              "input": {
                "type": "object",
                "additionalProperties": true
              },
              "output": {
                "type": "object",
                "additionalProperties": true
              },
              "errorText": {
                "type": "string"
              },
              "providerExecuted": {
                "type": "boolean"
              },
              "callProviderMetadata": {
                "type": "object",
                "additionalProperties": true
              }
            },
            "required": [
              "type",
              "toolName",
              "toolCallId",
              "state"
            ]
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "source-url"
                ],
                "example": "source-url"
              },
              "sourceId": {
                "type": "string"
              },
              "url": {
                "type": "string",
                "example": "https://example.com"
              },
              "title": {
                "type": "string"
              },
              "providerMetadata": {
                "type": "object",
                "additionalProperties": true
              }
            },
            "required": [
              "type",
              "sourceId",
              "url"
            ]
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "source-document"
                ],
                "example": "source-document"
              },
              "sourceId": {
                "type": "string"
              },
              "mediaType": {
                "type": "string"
              },
              "title": {
                "type": "string"
              },
              "filename": {
                "type": "string"
              },
              "providerMetadata": {
                "type": "object",
                "additionalProperties": true
              }
            },
            "required": [
              "type",
              "sourceId",
              "mediaType",
              "title"
            ]
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "pattern": "^data-"
              },
              "id": {
                "type": "string"
              },
              "data": {
                "type": "object",
                "additionalProperties": true
              }
            },
            "required": [
              "type",
              "data"
            ]
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "step-start"
                ],
                "example": "step-start"
              }
            },
            "required": [
              "type"
            ]
          }
        ]
      },
      "UIMessage": {
        "type": "object",
        "description": "AI SDK UI Message format for chat conversations",
        "properties": {
          "id": {
            "type": "string",
            "description": "Unique identifier for the message",
            "example": "msg_123456"
          },
          "role": {
            "type": "string",
            "enum": [
              "system",
              "user",
              "assistant"
            ],
            "description": "Message role - system messages should be avoided (use system prompt on server instead)",
            "example": "user"
          },
          "metadata": {
            "type": "object",
            "description": "Optional message metadata",
            "additionalProperties": true
          },
          "parts": {
            "type": "array",
            "description": "Message parts - system messages can have text parts; user messages can have text and file parts; assistant messages can have text, reasoning, tool invocation, and file parts",
            "items": {
              "$ref": "#/components/schemas/UIMessagePart"
            },
            "example": [
              {
                "type": "text",
                "text": "Hello, I need help with my order"
              }
            ]
          }
        },
        "required": [
          "id",
          "role",
          "parts"
        ]
      },
      "ChatRequest": {
        "type": "object",
        "properties": {
          "messages": {
            "type": "array",
            "description": "Array of UI messages representing the conversation history",
            "items": {
              "$ref": "#/components/schemas/UIMessage"
            },
            "minItems": 1
          },
          "conversationId": {
            "type": "string",
            "description": "Optional conversation ID for tracking and resuming conversations",
            "example": "conv_123456"
          }
        },
        "required": [
          "messages"
        ]
      },
      "UpdateAvatarPayload": {
        "type": "object",
        "description": "Fields accepted to update an avatar",
        "properties": {
          "name": {
            "type": "string"
          },
          "nameI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "logic": {
            "type": "integer"
          },
          "discipline": {
            "type": "integer"
          },
          "fitness": {
            "type": "integer"
          },
          "empathy": {
            "type": "integer"
          },
          "creativity": {
            "type": "integer"
          },
          "exploreMax": {
            "type": "integer"
          },
          "affinity": {
            "type": "integer"
          },
          "description": {
            "type": "string"
          },
          "descriptionI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "isActive": {
            "type": "boolean"
          },
          "shape": {
            "type": "string",
            "enum": [
              "circle",
              "square",
              "triangle"
            ]
          }
        }
      },
      "CreateAvatarPayload": {
        "type": "object",
        "description": "Fields accepted to create an avatar",
        "properties": {
          "name": {
            "type": "string"
          },
          "nameI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "logic": {
            "type": "integer"
          },
          "discipline": {
            "type": "integer"
          },
          "fitness": {
            "type": "integer"
          },
          "empathy": {
            "type": "integer"
          },
          "creativity": {
            "type": "integer"
          },
          "exploreMax": {
            "type": "integer"
          },
          "affinity": {
            "type": "integer"
          },
          "description": {
            "type": "string"
          },
          "descriptionI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "shape": {
            "type": "string",
            "enum": [
              "circle",
              "square",
              "triangle"
            ]
          }
        },
        "required": [
          "name",
          "shape"
        ]
      },
      "Avatar": {
        "type": "object",
        "description": "Avatar resource",
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "logic": {
            "type": "number"
          },
          "discipline": {
            "type": "number"
          },
          "fitness": {
            "type": "number"
          },
          "empathy": {
            "type": "number"
          },
          "creativity": {
            "type": "number"
          },
          "energy": {
            "type": "integer",
            "description": "V1.4 燃脂力 EXP (DEV-939). Replaces the deprecated 5-dim attributes.",
            "example": 30
          },
          "energyState": {
            "description": "V1.4 mapped energy level (avatar GET response). Backend maps; does not gate.",
            "allOf": [
              {
                "$ref": "#/components/schemas/EnergyState"
              }
            ]
          },
          "exploreMax": {
            "type": "integer"
          },
          "affinity": {
            "type": "integer"
          },
          "description": {
            "type": "string"
          },
          "isActive": {
            "type": "boolean"
          },
          "createdBy": {
            "type": "string"
          },
          "updatedBy": {
            "type": "string"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "UserAvatar": {
        "allOf": [
          {
            "$ref": "#/components/schemas/Avatar"
          }
        ],
        "type": "object",
        "description": "The current user's avatar instance. Includes the V1.4 mapped energyState (DEV-950).",
        "properties": {
          "userId": {
            "type": "string",
            "example": "user_123"
          },
          "avatarId": {
            "type": "integer",
            "example": 1
          },
          "shape": {
            "type": "string",
            "enum": [
              "circle",
              "square",
              "triangle"
            ]
          },
          "color": {
            "type": "string",
            "example": "#5B5EF2"
          },
          "status": {
            "type": "string",
            "example": "idle"
          },
          "imageUrl": {
            "type": "string",
            "nullable": true
          },
          "outfit": {
            "type": "object",
            "additionalProperties": true,
            "description": "Equipped outfit map; never null (defaults to {})"
          },
          "metadata": {
            "type": "object",
            "additionalProperties": true,
            "description": "Instance metadata bag returned by GET /api/v0/game/user/avatar"
          },
          "descriptionI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            },
            "description": "Localized avatar descriptions keyed by locale"
          }
        }
      },
      "OutfitItem": {
        "type": "object",
        "description": "Outfit item resource",
        "properties": {
          "id": {
            "type": "integer"
          },
          "setId": {
            "type": "integer",
            "nullable": true
          },
          "name": {
            "type": "string"
          },
          "nameI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "type": {
            "type": "string",
            "enum": [
              "headscarf",
              "glasses",
              "bowtie",
              "left_hand",
              "right_hand",
              "shoes"
            ]
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "descriptionI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "rarity": {
            "type": "integer",
            "description": "FK to app_rarities.id"
          },
          "riveProperty": {
            "type": "object",
            "additionalProperties": true
          },
          "metadata": {
            "type": "object",
            "description": "Extensible metadata for arbitrary key-value pairs (e.g. seasonal tags, unlock conditions)",
            "additionalProperties": true
          },
          "thumbnail": {
            "type": "string",
            "nullable": true
          },
          "previewImage": {
            "type": "string",
            "nullable": true
          },
          "price": {
            "type": "integer"
          },
          "shape": {
            "type": "string",
            "enum": [
              "circle",
              "square",
              "triangle"
            ],
            "nullable": true,
            "description": "Avatar shape this outfit fits; null = universal (fits any shape)"
          },
          "fragmentPrice": {
            "type": "integer",
            "nullable": true,
            "description": "Cost in fragments to redeem this outfit; null = not redeemable via fragments"
          },
          "isEvent": {
            "type": "boolean",
            "description": "Whether this item is only obtainable via events"
          },
          "isPurchasable": {
            "type": "boolean",
            "description": "Whether this item can be purchased from the shop"
          },
          "isActive": {
            "type": "boolean"
          },
          "createdBy": {
            "type": "string"
          },
          "updatedBy": {
            "type": "string"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "OutfitSet": {
        "type": "object",
        "description": "Outfit set resource",
        "properties": {
          "id": {
            "type": "integer"
          },
          "name": {
            "type": "string"
          },
          "nameI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "descriptionI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "rarity": {
            "type": "integer",
            "description": "FK to app_rarities.id"
          },
          "metadata": {
            "type": "object",
            "description": "Extensible metadata for arbitrary key-value pairs (e.g. theme info, bonus effects)",
            "additionalProperties": true
          },
          "thumbnail": {
            "type": "string",
            "nullable": true
          },
          "previewImage": {
            "type": "string",
            "nullable": true
          },
          "price": {
            "type": "integer"
          },
          "isEvent": {
            "type": "boolean",
            "description": "Whether this set is only obtainable via events"
          },
          "isPurchasable": {
            "type": "boolean",
            "description": "Whether this set can be purchased from the shop"
          },
          "isActive": {
            "type": "boolean"
          },
          "createdBy": {
            "type": "string"
          },
          "updatedBy": {
            "type": "string"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "Item": {
        "type": "object",
        "description": "Item resource",
        "properties": {
          "id": {
            "type": "integer"
          },
          "name": {
            "type": "string"
          },
          "nameI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "descriptionI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "rarity": {
            "type": "integer",
            "description": "FK to app_rarities.id"
          },
          "effects": {
            "type": "object",
            "additionalProperties": true
          },
          "metadata": {
            "type": "object",
            "description": "Extensible metadata for arbitrary key-value pairs",
            "additionalProperties": true
          },
          "typeName": {
            "type": "string",
            "enum": [
              "food",
              "tool",
              "souvenir",
              "map",
              "special"
            ]
          },
          "thumbnail": {
            "type": "string",
            "nullable": true
          },
          "previewImage": {
            "type": "string",
            "nullable": true
          },
          "isEvent": {
            "type": "boolean",
            "description": "Whether this item is only obtainable via events"
          },
          "isPurchasable": {
            "type": "boolean",
            "description": "Whether this item can be purchased from the shop"
          },
          "isActive": {
            "type": "boolean"
          },
          "createdBy": {
            "type": "string"
          },
          "updatedBy": {
            "type": "string"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "UserItem": {
        "type": "object",
        "description": "User item resource",
        "properties": {
          "id": {
            "type": "integer"
          },
          "userId": {
            "type": "string"
          },
          "itemId": {
            "type": "integer"
          },
          "name": {
            "type": "string"
          },
          "nameI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "descriptionI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "rarity": {
            "type": "integer",
            "description": "FK to app_rarities.id"
          },
          "effects": {
            "type": "object",
            "additionalProperties": true
          },
          "metadata": {
            "type": "object",
            "description": "Extensible metadata for arbitrary key-value pairs",
            "additionalProperties": true
          },
          "typeName": {
            "type": "string",
            "enum": [
              "food",
              "tool",
              "souvenir",
              "map",
              "special"
            ]
          },
          "thumbnail": {
            "type": "string",
            "nullable": true
          },
          "previewImage": {
            "type": "string",
            "nullable": true
          },
          "quantity": {
            "type": "integer"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "Rarity": {
        "type": "object",
        "description": "Rarity definition resource",
        "properties": {
          "id": {
            "type": "integer"
          },
          "category": {
            "type": "string",
            "enum": [
              "item",
              "outfit",
              "achievement"
            ],
            "description": "Rarity category (item=道具, outfit=时装, achievement=成就)"
          },
          "level": {
            "type": "integer",
            "description": "Numeric level (e.g. 1=Common, 5=Legendary)"
          },
          "name": {
            "type": "string"
          },
          "nameI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "color": {
            "type": "string",
            "description": "Hex color string for display"
          },
          "sortOrder": {
            "type": "integer"
          },
          "isActive": {
            "type": "boolean"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "UserOutfitItem": {
        "type": "object",
        "description": "User outfit item resource",
        "properties": {
          "id": {
            "type": "integer"
          },
          "userId": {
            "type": "string"
          },
          "outfitItemId": {
            "type": "integer"
          },
          "source": {
            "type": "string",
            "enum": [
              "journey",
              "purchase",
              "gift",
              "system"
            ],
            "nullable": true
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "UserOutfitSet": {
        "type": "object",
        "description": "User outfit set resource",
        "properties": {
          "id": {
            "type": "integer"
          },
          "userId": {
            "type": "string"
          },
          "outfitSetId": {
            "type": "integer"
          },
          "source": {
            "type": "string",
            "enum": [
              "journey",
              "purchase",
              "gift",
              "system"
            ],
            "nullable": true
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "UserOutfitSetWithItems": {
        "type": "object",
        "description": "User outfit set resource",
        "properties": {
          "id": {
            "type": "integer"
          },
          "userId": {
            "type": "string"
          },
          "outfitSetId": {
            "type": "integer"
          },
          "source": {
            "type": "string",
            "enum": [
              "journey",
              "purchase",
              "gift",
              "system"
            ],
            "nullable": true
          },
          "outfitItems": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "integer"
                },
                "userId": {
                  "type": "string"
                },
                "outfitItemId": {
                  "type": "integer"
                },
                "source": {
                  "type": "string",
                  "enum": [
                    "journey",
                    "purchase",
                    "gift",
                    "system"
                  ],
                  "nullable": true
                },
                "createdAt": {
                  "type": "string",
                  "format": "date-time"
                },
                "updatedAt": {
                  "type": "string",
                  "format": "date-time"
                }
              }
            }
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "SlotReward": {
        "type": "object",
        "description": "Per-slot reward bundle. At least one of seeds/items/outfits is non-empty.",
        "properties": {
          "seeds": {
            "type": "integer",
            "nullable": true
          },
          "items": {
            "type": "array",
            "nullable": true,
            "items": {
              "type": "object",
              "properties": {
                "itemId": {
                  "type": "integer"
                },
                "quantity": {
                  "type": "integer"
                }
              }
            }
          },
          "outfits": {
            "type": "array",
            "nullable": true,
            "description": "Outfit rewards enriched at read time with metadata from outfit_items.",
            "items": {
              "type": "object",
              "properties": {
                "outfitItemId": {
                  "type": "integer"
                },
                "name": {
                  "type": "string",
                  "nullable": true
                },
                "nameI18n": {
                  "type": "object",
                  "nullable": true,
                  "additionalProperties": {
                    "type": "string"
                  }
                },
                "thumbnail": {
                  "type": "string",
                  "nullable": true
                },
                "metadata": {
                  "type": "object",
                  "nullable": true,
                  "additionalProperties": {}
                }
              }
            }
          },
          "preview_image": {
            "type": "string",
            "nullable": true
          },
          "preview_text": {
            "type": "string",
            "nullable": true
          },
          "preview_text_i18n": {
            "type": "object",
            "nullable": true,
            "additionalProperties": {
              "type": "string"
            },
            "description": "BCP-47 language tag → localized preview text (e.g. zh-CN, en-US)"
          }
        }
      },
      "CampaignViewSlot": {
        "type": "object",
        "description": "One slot in the seven-day-login user view.",
        "properties": {
          "index": {
            "type": "integer",
            "description": "1-based slot index"
          },
          "status": {
            "type": "string",
            "enum": [
              "locked",
              "claimable",
              "claimed"
            ]
          },
          "reward": {
            "$ref": "#/components/schemas/SlotReward"
          }
        }
      },
      "SevenDayLoginCampaignView": {
        "type": "object",
        "description": "Response data shape for GET /api/v0/campaigns/seven-day-login. Wrap in { success, data } envelope.",
        "properties": {
          "campaign": {
            "type": "object",
            "properties": {
              "id": {
                "type": "integer"
              },
              "name": {
                "type": "string"
              },
              "starts_at": {
                "type": "string",
                "format": "date-time",
                "nullable": true
              },
              "ends_at": {
                "type": "string",
                "format": "date-time",
                "nullable": true
              },
              "slot_count": {
                "type": "integer"
              },
              "state": {
                "type": "string",
                "enum": [
                  "draft",
                  "upcoming",
                  "active",
                  "ended"
                ]
              }
            }
          },
          "progress": {
            "type": "object",
            "properties": {
              "unlocked_slots": {
                "type": "array",
                "items": {
                  "type": "integer"
                },
                "description": "Sorted ascending; 1-based."
              },
              "claimed_slots": {
                "type": "array",
                "items": {
                  "type": "integer"
                },
                "description": "Subset of unlocked_slots; sorted ascending; 1-based."
              },
              "slot_count": {
                "type": "integer"
              }
            }
          },
          "slots": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CampaignViewSlot"
            }
          }
        }
      },
      "SevenDayLoginClaimResult": {
        "type": "object",
        "description": "Result of POST /api/v0/campaigns/seven-day-login/claim.",
        "properties": {
          "reward": {
            "$ref": "#/components/schemas/SlotReward"
          },
          "progress": {
            "type": "object",
            "properties": {
              "unlocked_slots": {
                "type": "array",
                "items": {
                  "type": "integer"
                }
              },
              "claimed_slots": {
                "type": "array",
                "items": {
                  "type": "integer"
                }
              },
              "slot_count": {
                "type": "integer"
              }
            }
          }
        }
      },
      "FragmentExchangeRosterOutfit": {
        "type": "object",
        "description": "One roster slot in a fragment_exchange campaign view. fragmentsOwned tracks the user-specific accumulated count for this outfit.",
        "properties": {
          "outfitItemId": {
            "type": "integer"
          },
          "name": {
            "type": "string",
            "nullable": true
          },
          "nameI18n": {
            "type": "object",
            "additionalProperties": {
              "type": "string"
            }
          },
          "thumbnail": {
            "type": "string",
            "nullable": true
          },
          "fragmentPrice": {
            "type": "integer",
            "nullable": true,
            "description": "null when admin config is incomplete"
          },
          "fragmentsOwned": {
            "type": "integer",
            "description": "User-specific accumulated fragments for this outfit; carries across cycles."
          },
          "ownedOutfit": {
            "type": "boolean",
            "description": "Whether the user already has the redeemed outfit (any source)."
          }
        }
      },
      "FragmentExchangeView": {
        "type": "object",
        "description": "Response data shape for GET /api/v0/campaigns/fragment-exchange. Wrap in { success, data } envelope. data may be null when no active fragment_exchange campaign exists.",
        "properties": {
          "campaign": {
            "type": "object",
            "properties": {
              "id": {
                "type": "integer"
              },
              "name": {
                "type": "string"
              },
              "starts_at": {
                "type": "string",
                "format": "date-time",
                "nullable": true
              },
              "ends_at": {
                "type": "string",
                "format": "date-time",
                "nullable": true
              },
              "state": {
                "type": "string",
                "enum": [
                  "draft",
                  "upcoming",
                  "active",
                  "ended"
                ]
              }
            }
          },
          "my_shape": {
            "type": "string",
            "enum": [
              "circle",
              "square",
              "triangle"
            ],
            "nullable": true,
            "description": "null when the user has no avatar"
          },
          "roster": {
            "type": "object",
            "description": "Per-shape roster of redeemable outfits.",
            "properties": {
              "circle": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/FragmentExchangeRosterOutfit"
                }
              },
              "square": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/FragmentExchangeRosterOutfit"
                }
              },
              "triangle": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/FragmentExchangeRosterOutfit"
                }
              }
            }
          },
          "bonus": {
            "type": "object",
            "description": "Per-shape bonus outfit metadata (full OutfitItem row). null when admin has not configured a bonus for that shape.",
            "properties": {
              "circle": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/OutfitItem"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "square": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/OutfitItem"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "triangle": {
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/OutfitItem"
                  },
                  {
                    "type": "null"
                  }
                ]
              }
            }
          },
          "progress": {
            "type": "object",
            "description": "Aggregate user progress flags. Per-outfit collection state lives in roster[shape][].fragmentsOwned + ownedOutfit; frontend derives \"X/Y collected\" locally.",
            "properties": {
              "my_roster_complete": {
                "type": "boolean",
                "description": "User owns every outfit in their shape roster; false when my_shape is null."
              },
              "bonus_claimable": {
                "type": "boolean",
                "description": "true when my_shape exists, my_roster_complete, and bonus not yet granted. Frontend uses this to enable the claim-bonus button."
              },
              "bonus_granted": {
                "type": "boolean",
                "description": "Bonus already in the user outfit collection (claimed or admin-granted)."
              }
            }
          }
        }
      },
      "FragmentInventoryItem": {
        "type": "object",
        "description": "One row of GET /api/v0/game/fragments — user-scoped fragment balance with outfit metadata.",
        "properties": {
          "outfitItemId": {
            "type": "integer"
          },
          "quantity": {
            "type": "integer"
          },
          "outfit": {
            "type": "object",
            "properties": {
              "name": {
                "type": "string"
              },
              "nameI18n": {
                "type": "object",
                "additionalProperties": {
                  "type": "string"
                }
              },
              "thumbnail": {
                "type": "string",
                "nullable": true
              },
              "fragmentPrice": {
                "type": "integer",
                "nullable": true
              },
              "shape": {
                "type": "string",
                "nullable": true
              }
            }
          },
          "owned": {
            "type": "boolean",
            "description": "Whether the user already owns the redeemed outfit."
          }
        }
      },
      "RedemptionResult": {
        "type": "object",
        "description": "Result of POST /api/v0/game/redemptions.",
        "properties": {
          "redemption": {
            "type": "object",
            "properties": {
              "outfitItemId": {
                "type": "integer"
              },
              "fragmentsSpent": {
                "type": "integer"
              },
              "redeemedAt": {
                "type": "string",
                "format": "date-time"
              }
            }
          },
          "updatedBalance": {
            "type": "integer",
            "description": "Remaining fragment balance for this outfit after the spend."
          },
          "awardedOutfit": {
            "type": "object",
            "properties": {
              "id": {
                "type": "integer",
                "description": "app_user_outfit_items primary key (NOT outfit_items.id)"
              },
              "outfitItemId": {
                "type": "integer"
              },
              "createdAt": {
                "type": "string",
                "format": "date-time",
                "nullable": true
              }
            }
          }
        }
      },
      "BonusClaimResult": {
        "type": "object",
        "description": "Result of POST /api/v0/campaigns/fragment-exchange/claim-bonus.",
        "properties": {
          "awardedOutfit": {
            "type": "object",
            "properties": {
              "id": {
                "type": "integer",
                "description": "app_user_outfit_items primary key"
              },
              "outfitItemId": {
                "type": "integer"
              },
              "createdAt": {
                "type": "string",
                "format": "date-time",
                "nullable": true
              }
            }
          }
        }
      },
      "DailyTargets": {
        "type": "object",
        "properties": {
          "calorieMode": {
            "type": "string",
            "enum": [
              "recommended",
              "custom"
            ]
          },
          "customCalories": {
            "type": "integer",
            "nullable": true
          },
          "recommendedCalories": {
            "type": "integer",
            "nullable": true
          },
          "safeMinimum": {
            "type": "integer"
          },
          "mealsPerDay": {
            "type": "integer",
            "nullable": true
          },
          "firstMealTime": {
            "type": "string",
            "nullable": true,
            "example": "07:00"
          },
          "lastMealTime": {
            "type": "string",
            "nullable": true,
            "example": "19:00"
          },
          "recommendedChange": {
            "type": "object",
            "nullable": true,
            "properties": {
              "current": {
                "type": "integer"
              },
              "suggested": {
                "type": "integer"
              },
              "weightGrams": {
                "type": "integer",
                "nullable": true
              },
              "weightTrend": {
                "type": "string",
                "nullable": true,
                "enum": [
                  "down",
                  "up"
                ]
              }
            }
          }
        }
      }
    }
  },
  "security": [
    {
      "sessionAuth": []
    }
  ],
  "paths": {
    "/api/v0/admin/agency-rules/{id}": {
      "patch": {
        "summary": "(Admin) Update a campaign→agency rule",
        "description": "channel / note 传空串即清空该字段。",
        "tags": [
          "Admin",
          "Attribution"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Updated"
          },
          "400": {
            "description": "Invalid input"
          },
          "404": {
            "description": "Rule not found"
          }
        }
      },
      "delete": {
        "summary": "(Admin) Delete a campaign→agency rule",
        "tags": [
          "Admin",
          "Attribution"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Deleted"
          },
          "404": {
            "description": "Rule not found"
          }
        }
      }
    },
    "/api/v0/admin/agency-rules/reorder": {
      "post": {
        "summary": "(Admin) Reorder campaign→agency rules",
        "description": "顺序即优先级，所以调序是业务操作而非装饰。未在 ids 里出现的规则\n保持相对顺序、追加在后面（防止漏传导致规则丢失）。\n",
        "tags": [
          "Admin",
          "Attribution"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "ids"
                ],
                "properties": {
                  "ids": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Reordered",
            "returns the new full order": null
          },
          "400": {
            "description": "Invalid input"
          }
        }
      }
    },
    "/api/v0/admin/agency-rules": {
      "get": {
        "summary": "(Admin) List campaign→agency rules in priority order",
        "description": "数组顺序即优先级，第一条命中即止。同时返回代码词表 mediaPlatforms\n供前端的 channel 下拉使用（该字段允许自定义值，词表只是候选）。\n",
        "tags": [
          "Admin",
          "Attribution"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Rules in priority order + media platform vocabulary"
          },
          "404": {
            "description": "Not authorized (hidden)"
          }
        }
      },
      "post": {
        "summary": "(Admin) Create a campaign→agency rule",
        "description": "新规则追加到末尾（最低优先级）；需要提前请用 /reorder。",
        "tags": [
          "Admin",
          "Attribution"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "match",
                  "pattern",
                  "agency"
                ],
                "properties": {
                  "match": {
                    "type": "string",
                    "enum": [
                      "prefix",
                      "contains",
                      "exact"
                    ]
                  },
                  "pattern": {
                    "type": "string",
                    "description": "campaign 名片段，大小写不敏感"
                  },
                  "agency": {
                    "type": "string",
                    "description": "nexad / inpander / direct / …"
                  },
                  "channel": {
                    "type": "string",
                    "description": "可选媒体平台覆盖，仅 SDK 未给出时生效"
                  },
                  "note": {
                    "type": "string"
                  },
                  "enabled": {
                    "type": "boolean",
                    "default": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Created"
          },
          "400": {
            "description": "Invalid input"
          }
        }
      }
    },
    "/api/v0/admin/agency-rules/unmatched": {
      "get": {
        "summary": "(Admin) Campaigns with no matching agency rule",
        "description": "本设计的关键可观测面，不是装饰。投放那边开了新 campaign，这里就会\n冒出来，运营据此补规则、无需发版。没有这块，配置化只是把硬编码\n搬了个地方。\n\n口径：agency IS NULL AND utm_campaign 非空的 app_open_attribution 行，\n**且 created_at >= 归因回填窗口起点**（lib/agency-rules 的\nATTRIBUTION_BACKFILL_SINCE）。\n\n那条下限是硬性的，不是优化：更早的行从未被回填过，agency 恒为 NULL，\n与「有没有规则命中」无关。少了它，这个面板 99.5% 是假阳性（实测\n5,863 行噪音 vs 32 行真需要补规则）。`days` 只能在此之上进一步收窄。\n",
        "tags": [
          "Admin",
          "Attribution"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "days",
            "description": "在回填窗口之上再收窄的天数上限；取两者中更晚的那个下限",
            "schema": {
              "type": "integer",
              "default": 90
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Distinct campaigns with row counts and last-seen"
          }
        }
      }
    },
    "/api/v0/admin/audit-logs": {
      "get": {
        "summary": "(Admin) List audit logs",
        "description": "Query audit logs with filters. Admin access required.",
        "tags": [
          "Admin",
          "Audit"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "eventType",
            "schema": {
              "type": "string",
              "enum": [
                "user_deleted",
                "user_banned",
                "user_unbanned",
                "account_linked",
                "account_unlinked",
                "role_changed",
                "admin_action",
                "data_export",
                "config_changed"
              ]
            }
          },
          {
            "in": "query",
            "name": "userId",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "performedBy",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "default": 1
            }
          },
          {
            "in": "query",
            "name": "size",
            "schema": {
              "type": "integer",
              "default": 50
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Audit logs list"
          },
          "403": {
            "description": "Admin access required"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/admin/campaigns/{id}/clone": {
      "post": {
        "summary": "(Admin) Clone a campaign into a new draft",
        "description": "Copies type/name/config; appends \"(copy)\" to name; clears time window.",
        "tags": [
          "Admin",
          "Campaigns"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "201": {
            "description": "Cloned (new draft)"
          },
          "404": {
            "description": "Source not found / unauthorized"
          }
        }
      }
    },
    "/api/v0/admin/campaigns/{id}/publish": {
      "post": {
        "summary": "(Admin) Publish a draft campaign",
        "tags": [
          "Admin",
          "Campaigns"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Published"
          },
          "404": {
            "description": "Not found / unauthorized"
          },
          "409": {
            "description": "Not in draft state",
            "or validateForPublish failed": null
          },
          "503": {
            "description": "Type not registered"
          }
        }
      }
    },
    "/api/v0/admin/campaigns/{id}": {
      "get": {
        "summary": "(Admin) Read campaign by id",
        "tags": [
          "Admin",
          "Campaigns"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Campaign with derived state"
          },
          "404": {
            "description": "Not found or unauthorized"
          }
        }
      },
      "patch": {
        "summary": "(Admin) Update campaign (field rules per state)",
        "tags": [
          "Admin",
          "Campaigns"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Updated"
          },
          "404": {
            "description": "Not found / unauthorized"
          },
          "409": {
            "description": "Field locked / invalid window"
          }
        }
      },
      "delete": {
        "summary": "(Admin) Delete campaign (draft only)",
        "tags": [
          "Admin",
          "Campaigns"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "204": {
            "description": "Deleted"
          },
          "404": {
            "description": "Not found / unauthorized"
          },
          "409": {
            "description": "Not deletable in current state"
          }
        }
      }
    },
    "/api/v0/admin/campaigns/{id}/unpublish": {
      "post": {
        "summary": "(Admin) Unpublish a campaign (sets is_published=false)",
        "tags": [
          "Admin",
          "Campaigns"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Unpublished"
          },
          "404": {
            "description": "Not found / unauthorized"
          },
          "409": {
            "description": "Not currently published"
          }
        }
      }
    },
    "/api/v0/admin/campaigns": {
      "get": {
        "summary": "(Admin) List campaigns",
        "tags": [
          "Admin",
          "Campaigns"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "type",
            "schema": {
              "type": "string",
              "enum": [
                "seven_day_login",
                "fragment_exchange"
              ]
            }
          },
          {
            "in": "query",
            "name": "state",
            "schema": {
              "type": "string",
              "enum": [
                "draft",
                "upcoming",
                "active",
                "ended"
              ]
            }
          },
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "default": 1
            }
          },
          {
            "in": "query",
            "name": "size",
            "schema": {
              "type": "integer",
              "default": 50
            }
          }
        ],
        "responses": {
          "200": {
            "description": "List"
          },
          "404": {
            "description": "Not authorized (hidden)"
          }
        }
      },
      "post": {
        "summary": "(Admin) Create draft campaign",
        "tags": [
          "Admin",
          "Campaigns"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "type",
                  "name",
                  "config"
                ],
                "properties": {
                  "type": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  },
                  "description": {
                    "type": "string",
                    "nullable": true
                  },
                  "startsAt": {
                    "type": "string",
                    "format": "date-time",
                    "nullable": true
                  },
                  "endsAt": {
                    "type": "string",
                    "format": "date-time",
                    "nullable": true
                  },
                  "config": {}
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Created"
          },
          "400": {
            "description": "Invalid input"
          },
          "404": {
            "description": "Not authorized"
          },
          "409": {
            "description": "Conflict (e.g. invalid time window)"
          }
        }
      }
    },
    "/api/v0/admin/configs": {
      "get": {
        "summary": "(Admin) List or read KV configs (app_configs / app_game_configs)",
        "description": "不带 `key` 返回该表全部行(按 key 排序);带 `key` 返回单行。\n这两张表控制运行时行为 —— 其中 `app` 表的 `entitlements.matrix`\n是免费/Pro 门禁的总开关(`enabled` + 每功能 `minTier`)。\n",
        "tags": [
          "Admin"
        ],
        "security": [
          {
            "sessionAuth": [],
            "bearerAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "table",
            "required": true,
            "schema": {
              "type": "string",
              "enum": [
                "app",
                "game"
              ]
            },
            "description": "app = app_configs，game = app_game_configs"
          },
          {
            "in": "query",
            "name": "key",
            "schema": {
              "type": "string"
            },
            "description": "省略则返回整表"
          }
        ],
        "responses": {
          "200": {
            "description": "Config row(s)"
          },
          "400": {
            "description": "Invalid table"
          },
          "404": {
            "description": "Not authorized (hidden)，或 key 不存在"
          }
        }
      },
      "put": {
        "summary": "(Admin) Upsert one KV config row (whole-value replace)",
        "description": "**整值覆盖**，不是深合并。先 GET 取完整 value、本地改好再整体 PUT 回来。\n写入会落 `audit_logs`（含改前的值）。\n",
        "tags": [
          "Admin"
        ],
        "security": [
          {
            "sessionAuth": [],
            "bearerAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "table",
                  "key",
                  "value"
                ],
                "properties": {
                  "table": {
                    "type": "string",
                    "enum": [
                      "app",
                      "game"
                    ]
                  },
                  "key": {
                    "type": "string",
                    "example": "entitlements.matrix"
                  },
                  "value": {
                    "description": "任意 JSON —— 整值覆盖",
                    "example": {
                      "enabled": false,
                      "minTier": {
                        "taskgen.daily": "pro"
                      }
                    }
                  },
                  "description": {
                    "type": "string",
                    "nullable": true,
                    "description": "省略则保留原描述"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Upserted，返回改后的行 + created 标记"
          },
          "400": {
            "description": "Invalid input"
          },
          "404": {
            "description": "Not authorized (hidden)"
          }
        }
      }
    },
    "/api/v0/admin/imessage-lines/{id}": {
      "patch": {
        "summary": "(Admin) Update iMessage line",
        "tags": [
          "Admin",
          "Messaging"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Updated"
          },
          "404": {
            "description": "Not found / unauthorized"
          },
          "409": {
            "description": "Phone already in use"
          }
        }
      },
      "delete": {
        "summary": "(Admin) Delete iMessage line",
        "tags": [
          "Admin",
          "Messaging"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "204": {
            "description": "Deleted"
          },
          "404": {
            "description": "Not found / unauthorized"
          }
        }
      }
    },
    "/api/v0/admin/imessage-lines": {
      "get": {
        "summary": "(Admin) List iMessage lines with today's in+out count",
        "tags": [
          "Admin",
          "Messaging"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "List of lines with todayCount attached"
          },
          "404": {
            "description": "Not authorized (hidden)"
          }
        }
      },
      "post": {
        "summary": "(Admin) Create iMessage line",
        "tags": [
          "Admin",
          "Messaging"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "phone"
                ],
                "properties": {
                  "phone": {
                    "type": "string",
                    "description": "E.164 phone (+14156974954)"
                  },
                  "label": {
                    "type": "string",
                    "nullable": true
                  },
                  "enabled": {
                    "type": "boolean",
                    "default": true
                  },
                  "dailyQuota": {
                    "type": "integer",
                    "default": 5000
                  },
                  "notes": {
                    "type": "string",
                    "nullable": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Created"
          },
          "400": {
            "description": "Invalid input"
          },
          "409": {
            "description": "Phone already exists"
          }
        }
      }
    },
    "/api/v0/admin/monitoring/diary/{diaryId}/trace": {
      "get": {
        "summary": "Full generation trace for a single diary row (admin only)",
        "description": "Returns the diary row plus its associated agent_runs (newest first).\nEach agent_run carries the full trace: decision, context, prompt\n(system+user), and rawResult — captured at generation time.\n",
        "tags": [
          "Admin",
          "Monitoring"
        ]
      }
    },
    "/api/v0/admin/upload-image": {
      "post": {
        "summary": "Admin image upload",
        "description": "Upload an image to private object storage for use in admin-managed resources (avatars, items, outfits, etc.). Returns a capability URL (`/media/{id}`).",
        "tags": [
          "Admin"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "required": [
                  "file"
                ],
                "properties": {
                  "file": {
                    "type": "string",
                    "format": "binary"
                  },
                  "category": {
                    "type": "string",
                    "description": "Optional label recorded in the server log (e.g. \"items\", \"avatars\", \"outfits\"). No longer part of the object path — objects are grouped by uploader. Defaults to \"misc\"."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Upload successful",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "url": {
                      "type": "string"
                    },
                    "size": {
                      "type": "number"
                    },
                    "contentType": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/admin/users/{userId}/fragments": {
      "get": {
        "summary": "(Admin) Read a user's fragment balance",
        "tags": [
          "Admin",
          "FragmentExchange"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ]
      },
      "post": {
        "summary": "(Admin) Grant fragments to a user",
        "tags": [
          "Admin",
          "FragmentExchange"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "outfitItemId",
                  "quantity"
                ],
                "properties": {
                  "outfitItemId": {
                    "type": "integer"
                  },
                  "quantity": {
                    "type": "integer",
                    "minimum": 1
                  },
                  "reason": {
                    "type": "string"
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/admin/web-invitations": {
      "get": {
        "summary": "List web registration invitations (admin only)",
        "description": "Admin browser session cookie only; bearer and API key credentials are rejected.",
        "tags": [
          "Admin",
          "WebInvitations"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "default": 1
            },
            "description": "Page number (50 items per page)"
          }
        ],
        "responses": {
          "200": {
            "description": "{ success, data: { items } }"
          },
          "403": {
            "description": "Not an admin browser session"
          }
        }
      },
      "post": {
        "summary": "Create a reusable web invitation (admin only)",
        "tags": [
          "Admin",
          "WebInvitations"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "name",
                  "maxSignups"
                ],
                "properties": {
                  "name": {
                    "type": "string",
                    "maxLength": 100
                  },
                  "maxSignups": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 100000
                  },
                  "expiresAt": {
                    "type": "string",
                    "format": "date-time",
                    "nullable": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Created invitation with a generated 6-letter code"
          },
          "400": {
            "description": "Invalid settings"
          },
          "403": {
            "description": "Not an admin browser session"
          }
        }
      },
      "patch": {
        "summary": "Pause/resume an invitation or change its limit/expiry (admin only)",
        "tags": [
          "Admin",
          "WebInvitations"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "id"
                ],
                "properties": {
                  "id": {
                    "type": "string"
                  },
                  "enabled": {
                    "type": "boolean"
                  },
                  "maxSignups": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 100000
                  },
                  "expiresAt": {
                    "type": "string",
                    "format": "date-time",
                    "nullable": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated invitation"
          },
          "400": {
            "description": "Invalid settings"
          },
          "403": {
            "description": "Not an admin browser session"
          },
          "409": {
            "description": "Unknown id",
            "or the new limit is below the used count": null
          }
        }
      }
    },
    "/api/v0/agents/configs/{id}/publish": {
      "post": {
        "summary": "Publish an agent config to the kicker-agent runtime (admin only)",
        "tags": [
          "Agents"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Published"
          },
          "403": {
            "description": "Admin access required"
          },
          "404": {
            "description": "Config not found"
          },
          "409": {
            "description": "Name owned by admin on the runtime side"
          },
          "422": {
            "description": "system_prompt has unresolved section markers"
          },
          "503": {
            "description": "Publish feature disabled"
          }
        }
      }
    },
    "/api/v0/agents/configs/{id}": {
      "get": {
        "summary": "Get agent config by id",
        "tags": [
          "Agents"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Agent config"
          },
          "404": {
            "description": "Config not found"
          }
        }
      },
      "put": {
        "summary": "Update an agent config (admin only)",
        "tags": [
          "Agents"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Updated agent config"
          },
          "404": {
            "description": "Config not found"
          }
        }
      },
      "delete": {
        "summary": "Delete an agent config (admin only)",
        "tags": [
          "Agents"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Deleted agent config"
          },
          "404": {
            "description": "Config not found"
          }
        }
      }
    },
    "/api/v0/agents/configs/{id}/test-chat": {
      "post": {
        "summary": "One-shot LLM call with this config, for pre-publish testing (admin)",
        "tags": [
          "Agents"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "assistant text + token usage"
          },
          "429": {
            "description": "rate limited"
          },
          "503": {
            "description": "feature disabled"
          }
        }
      }
    },
    "/api/v0/agents/configs": {
      "get": {
        "summary": "List all agent configs",
        "tags": [
          "Agents"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "List of agent configs"
          }
        }
      },
      "post": {
        "summary": "Create a new agent config (admin only)",
        "tags": [
          "Agents"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "name"
                ],
                "properties": {
                  "name": {
                    "type": "string"
                  },
                  "model": {
                    "type": "string"
                  },
                  "systemPrompt": {
                    "type": "string"
                  },
                  "sections": {
                    "type": "object",
                    "additionalProperties": {
                      "type": "string"
                    }
                  },
                  "temperature": {
                    "type": "number"
                  },
                  "thinkingBudget": {
                    "type": "integer",
                    "description": "Thinking budget in tokens for the app's on-device Gemini analysis; 0 = off"
                  },
                  "maxSteps": {
                    "type": "integer"
                  },
                  "stopWhen": {
                    "type": "array"
                  },
                  "tools": {
                    "type": "array"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Created agent config"
          }
        }
      }
    },
    "/api/v0/agents/transcribe": {
      "post": {
        "summary": "Transcribe audio to text",
        "description": "Transcribe audio file to text using the configured speech-to-text\nprovider (OpenAI-compatible or Gemini, selected via DB config).\nAccepts base64-encoded audio data and returns transcribed text.\n- Convert audio to text transcription\n- Support various audio formats via base64 encoding\n- Returns transcription result as JSON\n",
        "tags": [
          "Agents"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "base64data"
                ],
                "properties": {
                  "base64data": {
                    "type": "string",
                    "description": "Base64-encoded audio data (without data URI prefix)",
                    "example": "data:audio/mp3;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQAAAAA="
                  },
                  "conversationId": {
                    "type": "string",
                    "description": "Optional conversation ID for tracking",
                    "example": "conv_123456"
                  }
                }
              },
              "example": {
                "base64data": "data:audio/mp3;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQAAAAA=",
                "conversationId": "conv_123456"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successfully transcribed audio to text",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "description": "Transcription result from OpenAI Whisper",
                      "properties": {
                        "text": {
                          "type": "string",
                          "description": "Transcribed text content",
                          "example": "Hello, this is a transcription of the audio."
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad request - Invalid audio data format",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "invalidFormat": {
                    "value": {
                      "error": "Base64 data is required"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized access",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/campaigns/fragment-exchange/claim-bonus": {
      "post": {
        "summary": "Claim the cycle-scoped bonus outfit for the user's shape",
        "description": "Manually grants the bonus outfit when the user has collected every roster\nitem for their shape. Cycle-scoped: returns 404 NO_CAMPAIGN once the active\ncampaign window ends, regardless of whether the user completed the roster\nin time. No carryover — bonus is forfeit if not claimed during the cycle.\n\nFrontend gates this on `progress.bonus_claimable === true` from\n`GET /api/v0/campaigns/fragment-exchange`.\n",
        "tags": [
          "Campaigns",
          "FragmentExchange"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Bonus outfit awarded",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "$ref": "#/components/schemas/BonusClaimResult"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "NO_CAMPAIGN — no active fragment_exchange campaign in window",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "NO_SHAPE (user has no avatar) / ROSTER_INCOMPLETE / ALREADY_CLAIMED",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/campaigns/fragment-exchange": {
      "get": {
        "summary": "Get the active fragment_exchange campaign and current user's progress",
        "description": "Returns the active campaign + per-shape roster (with the user's per-outfit\nfragments owned + ownership flag) + bonus outfits + aggregate progress flags.\n\n`data` is `null` when no published fragment_exchange campaign is in window.\nThe user's historical fragment balance remains queryable via\n`/api/v0/game/fragments` and redeemable via `/api/v0/game/redemptions` even\nwhen this endpoint returns `null`.\n\nPer-outfit collection state lives in `roster[shape][].fragmentsOwned` +\n`ownedOutfit`. Frontend derives \"X/Y collected\" by reducing the array.\n",
        "tags": [
          "Campaigns",
          "FragmentExchange"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "View (data may be null if no active campaign)",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "oneOf": [
                        {
                          "$ref": "#/components/schemas/FragmentExchangeView"
                        },
                        {
                          "type": "null"
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/campaigns/seven-day-login/claim": {
      "post": {
        "summary": "Claim a specific slot reward",
        "description": "Atomically credits seeds + items + outfits for the given slot and appends it\nto claimed_slots. Uses FOR UPDATE row lock to defend against parallel claims.\n",
        "tags": [
          "Campaigns",
          "SevenDayLogin"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "slot"
                ],
                "properties": {
                  "slot": {
                    "type": "integer",
                    "minimum": 1,
                    "description": "1-based slot index (1..slot_count)"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Reward credited",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "$ref": "#/components/schemas/SevenDayLoginClaimResult"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "INVALID_SLOT or INVALID_INPUT (Zod validation)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "NO_CAMPAIGN — user has no claimable campaign",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "SLOT_NOT_UNLOCKED or ALREADY_CLAIMED",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/campaigns/seven-day-login": {
      "get": {
        "summary": "Get the current seven-day-login campaign view for the authenticated user",
        "description": "Returns the campaign view + user progress + per-slot status. `data` is `null`\nwhen no published campaign is in window AND the user has no unfinished progress\non a prior cycle. Otherwise returns the campaign (may be `state: 'ended'` for\na carryover view where the user still has unclaimed slots).\n",
        "tags": [
          "Campaigns",
          "SevenDayLogin"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Campaign view (data may be null)",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "oneOf": [
                        {
                          "$ref": "#/components/schemas/SevenDayLoginCampaignView"
                        },
                        {
                          "type": "null"
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/chat/uploads": {
      "post": {
        "summary": "Upload a chat attachment (image or PDF)",
        "description": "Upload an image or PDF file (≤4MB) to private object storage for use as a chat\nattachment. Returns the public URL and metadata. The 4 MB cap is\nset by the Vercel function body limit; see code comments for how\nto increase it via direct upload if larger files are needed.\n",
        "tags": [
          "Chat"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "required": [
                  "file"
                ],
                "properties": {
                  "file": {
                    "type": "string",
                    "format": "binary",
                    "description": "Image (PNG/JPEG/WebP/GIF) or PDF file, max 4MB"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Upload successful",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "url": {
                      "type": "string"
                    },
                    "size": {
                      "type": "number"
                    },
                    "contentType": {
                      "type": "string"
                    },
                    "originalName": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad request (no file, invalid type, or file too large)"
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal error (e.g. blob storage misconfigured)"
          }
        }
      }
    },
    "/api/v0/checkout/portal": {
      "post": {
        "summary": "Open the Stripe Customer Portal",
        "description": "Returns a Stripe billing portal URL for self-service management\n(payment method, cancel, invoices). Migrated from koda-pay's\nPOST /v1/checkout/portal.\n",
        "tags": [
          "Subscriptions"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "{ url }"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "No Stripe customer"
          },
          "503": {
            "description": "Stripe not configured"
          }
        }
      }
    },
    "/api/v0/checkout/subscribe": {
      "post": {
        "summary": "Create a subscription checkout session (or upgrade/downgrade)",
        "description": "Migrated from koda-pay's POST /v1/checkout/subscribe. Reuses an active\ncached checkout link (bumping its view counter) before hitting Stripe.\nAn existing active subscription is updated in place (proration on\nupgrade); otherwise a Checkout session is created and cached in\npay_checkout_link. `subscription_data.metadata.userId` lets the webhook\nresolve the subscription back to the user.\n",
        "tags": [
          "Subscriptions"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "{ url } or { upgraded: true }"
          },
          "400": {
            "description": "Bad tier/interval or already on plan"
          },
          "401": {
            "description": "Unauthorized"
          },
          "503": {
            "description": "Stripe not configured"
          }
        }
      }
    },
    "/api/v0/devices": {
      "get": {
        "summary": "Get user device list",
        "description": "Get all registered devices for the current user",
        "tags": [
          "Device Management"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully retrieved device list",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "devices": {
                          "type": "array",
                          "items": {
                            "$ref": "#/components/schemas/Device"
                          }
                        }
                      }
                    },
                    "meta": {
                      "type": "object",
                      "properties": {
                        "count": {
                          "type": "number",
                          "example": 3
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized access",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "post": {
        "summary": "Register device token",
        "description": "Register or update device push token for the current user",
        "tags": [
          "Device Management"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "deviceId",
                  "token",
                  "platform"
                ],
                "properties": {
                  "deviceId": {
                    "type": "string",
                    "example": "device_unique_id_123",
                    "description": "Device unique identifier"
                  },
                  "token": {
                    "type": "string",
                    "example": "push_notification_token_abc123",
                    "description": "Push notification token"
                  },
                  "platform": {
                    "type": "string",
                    "enum": [
                      "ios",
                      "android",
                      "web"
                    ],
                    "example": "ios",
                    "description": "Device platform"
                  },
                  "deviceName": {
                    "type": "string",
                    "nullable": true,
                    "example": "iPhone 15 Pro",
                    "description": "Device name"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Device registered successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "id": {
                          "type": "string",
                          "example": "device_token_123"
                        },
                        "message": {
                          "type": "string",
                          "example": "Device token registered successfully"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid request parameters",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized access",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "delete": {
        "summary": "Delete device token",
        "description": "Delete device token(s) for current user",
        "tags": [
          "Device Management"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "deviceId": {
                    "type": "string",
                    "example": "device_unique_id_123",
                    "description": "Device ID (optional)"
                  },
                  "deleteAll": {
                    "type": "boolean",
                    "example": false,
                    "description": "Delete all devices if true"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Device deleted successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "message": {
                      "type": "string",
                      "example": "Device deleted successfully"
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "deletedCount": {
                          "type": "number",
                          "example": 1
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid request parameters",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized access",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Device not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "put": {
        "summary": "Update device trust status and active status",
        "description": "Update trust status and/or active status for a specific device",
        "tags": [
          "Device Management"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "deviceId",
                  "isTrusted"
                ],
                "properties": {
                  "deviceId": {
                    "type": "string",
                    "example": "device_unique_id_123",
                    "description": "Device ID"
                  },
                  "isTrusted": {
                    "type": "boolean",
                    "example": true,
                    "description": "Trust status for the device"
                  },
                  "isActive": {
                    "type": "boolean",
                    "example": true,
                    "description": "Active status for the device (optional)"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Device status updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "message": {
                      "type": "string",
                      "example": "Device trust status updated successfully"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid request parameters",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized access",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Device not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/devices/security": {
      "get": {
        "summary": "Get device security info",
        "description": "Get device security information including active and trusted devices",
        "tags": [
          "Device Management"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully returned security information",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "totalDevices": {
                          "type": "number",
                          "example": 5,
                          "description": "Total number of devices"
                        },
                        "activeDevices": {
                          "type": "number",
                          "example": 4,
                          "description": "Number of active devices"
                        },
                        "trustedDevices": {
                          "type": "number",
                          "example": 2,
                          "description": "Number of trusted devices"
                        },
                        "recentDevices": {
                          "type": "array",
                          "items": {
                            "type": "object",
                            "properties": {
                              "id": {
                                "type": "string",
                                "example": "device_token_123"
                              },
                              "deviceName": {
                                "type": "string",
                                "example": "iPhone 15 Pro"
                              },
                              "platform": {
                                "type": "string",
                                "example": "ios"
                              },
                              "deviceType": {
                                "type": "string",
                                "example": "mobile"
                              },
                              "lastUsedAt": {
                                "type": "number",
                                "example": 1704067200000
                              },
                              "lastIpAddress": {
                                "type": "string",
                                "example": "192.168.1.100"
                              },
                              "lastLocation": {
                                "type": "string",
                                "example": "Beijing, China"
                              },
                              "isTrusted": {
                                "type": "boolean",
                                "example": true
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized access",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/feature-flags": {
      "get": {
        "summary": "Runtime feature flags for the authenticated client",
        "tags": [
          "System"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Flag map"
          }
        }
      }
    },
    "/api/v0/feedback/log-upload": {
      "post": {
        "summary": "Upload a diagnostic log file for a feedback submission",
        "description": "Upload a plain-text diagnostic log (≤4MB) to Vercel Blob and return its\npublic URL, which the mobile app appends to the feedback message so\nsupport can open the user's client logs. The URL is unguessable\n(userId + timestamp + nanoid + Vercel's random suffix) but is NOT\nauth-gated — anyone with the link can read it. The 4 MB cap is set by\nthe Vercel function body limit; the client truncates oldest content to\nfit. Per-user rate limited.\n",
        "tags": [
          "Feedback"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "required": [
                  "file"
                ],
                "properties": {
                  "file": {
                    "type": "string",
                    "format": "binary",
                    "description": "Plain-text log file (text/plain), max 4MB"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Upload successful",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "url": {
                      "type": "string"
                    },
                    "size": {
                      "type": "number"
                    },
                    "contentType": {
                      "type": "string"
                    },
                    "originalName": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad request (no file, invalid type, or file too large)"
          },
          "401": {
            "description": "Unauthorized"
          },
          "429": {
            "description": "Too many uploads (per-user rate limit)"
          },
          "500": {
            "description": "Internal error (e.g. blob storage misconfigured)"
          }
        }
      }
    },
    "/api/v0/game/avatar/{id}": {
      "get": {
        "summary": "(Admin) Get an avatar by ID",
        "description": "Fetches an avatar resource identified by the path parameter `id`. The request must be authenticated, and the authenticated user must have the \"admin\" role. Admin access required.\n",
        "tags": [
          "Admin",
          "Game",
          "Avatar"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Avatar identifier",
            "schema": {
              "type": "integer",
              "example": 1
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Avatar retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "$ref": "#/components/schemas/Avatar"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad request — missing id parameter",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Forbidden — Admin access required",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Not found — avatar with the specified id does not exist",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "put": {
        "summary": "(Admin) Update an existing avatar by ID",
        "description": "Updates an avatar resource identified by the path parameter `id`. Request must be authenticated and the authenticated user must have the \"admin\" role. The request body is validated against the avatar update schema. Admin access required.\n",
        "tags": [
          "Admin",
          "Game",
          "Avatar"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Avatar identifier",
            "schema": {
              "type": "integer",
              "example": 1
            }
          }
        ],
        "requestBody": {
          "description": "Avatar fields to update. Must conform to PutAvatarPayload schema.",
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateAvatarPayload"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Avatar updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "$ref": "#/components/schemas/Avatar"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad request — validation failed or missing id parameter",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "Forbidden — Admin access required",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Not found — avatar with the specified id does not exist",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/game/avatar": {
      "get": {
        "summary": "(Admin) List all avatars",
        "description": "Returns all avatar presets ordered by id. Admin access required.",
        "tags": [
          "Admin",
          "Game",
          "Avatar"
        ],
        "responses": {
          "200": {
            "description": "Avatar list retrieved successfully"
          },
          "403": {
            "description": "Admin access required"
          }
        }
      },
      "post": {
        "summary": "(Admin) Create a new avatar",
        "description": "Creates a new avatar with the specified parameters. Admin access required.",
        "tags": [
          "Admin",
          "Game",
          "Avatar"
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateAvatarPayload"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Avatar created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "type": "object",
                      "schema": {
                        "$ref": "#/components/schemas/Avatar"
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error",
            "schema": {
              "$ref": null
            }
          },
          "403": {
            "description": "Admin access required",
            "schema": {
              "$ref": null
            }
          },
          "500": {
            "description": "Internal server error",
            "schema": {
              "$ref": null
            }
          }
        }
      }
    },
    "/api/v0/game/backdoor/user-avatar": {
      "patch": {
        "summary": "Update user avatar attributes (Admin Backdoor)",
        "description": "Directly modifies a user's avatar properties. Admin role required.",
        "tags": [
          "Admin",
          "Game"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "userId"
                ],
                "properties": {
                  "userId": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  },
                  "shape": {
                    "type": "string",
                    "enum": [
                      "circle",
                      "square",
                      "triangle"
                    ]
                  },
                  "color": {
                    "type": "string"
                  },
                  "logic": {
                    "type": "integer"
                  },
                  "discipline": {
                    "type": "integer"
                  },
                  "fitness": {
                    "type": "integer"
                  },
                  "empathy": {
                    "type": "integer"
                  },
                  "creativity": {
                    "type": "integer"
                  },
                  "exploreMax": {
                    "type": "integer"
                  },
                  "affinity": {
                    "type": "integer"
                  },
                  "description": {
                    "type": "string"
                  },
                  "outfit": {
                    "type": "object"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "User avatar updated successfully"
          },
          "400": {
            "description": "Invalid request"
          },
          "403": {
            "description": "Forbidden - Admin access required"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/backdoor/user-outfit-item": {
      "post": {
        "summary": "Issue outfit item to user (Admin Backdoor)",
        "description": "Directly adds an outfit item to a user's collection. Admin role required.",
        "tags": [
          "Admin",
          "Game"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "userId",
                  "outfitItemId"
                ],
                "properties": {
                  "userId": {
                    "type": "string",
                    "description": "ID of the user to receive the outfit item"
                  },
                  "outfitItemId": {
                    "type": "integer",
                    "description": "ID of the outfit item to issue"
                  },
                  "source": {
                    "type": "string",
                    "enum": [
                      "journey",
                      "purchase",
                      "gift",
                      "system"
                    ],
                    "default": "system",
                    "description": "Source of the item"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Outfit item issued successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "$ref": "#/components/schemas/UserOutfitItem"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid request or item not found"
          },
          "403": {
            "description": "Forbidden - Admin access required"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/backdoor/user-wallet": {
      "post": {
        "summary": "Add seeds to user wallet (Admin Backdoor)",
        "description": "Directly adds seeds (currency) to a user's wallet. Admin role required.",
        "tags": [
          "Admin",
          "Game"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "userId",
                  "amount"
                ],
                "properties": {
                  "userId": {
                    "type": "string",
                    "description": "ID of the user to receive seeds"
                  },
                  "amount": {
                    "type": "integer",
                    "description": "Number of seeds to add"
                  },
                  "description": {
                    "type": "string",
                    "description": "Reason for adding seeds"
                  },
                  "metadata": {
                    "type": "object",
                    "description": "Additional metadata for the transaction"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Seeds added successfully"
          },
          "400": {
            "description": "Invalid request"
          },
          "403": {
            "description": "Forbidden - Admin access required"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "delete": {
        "summary": "Deduct seeds from user wallet (Admin Backdoor)",
        "description": "Directly deducts seeds (currency) from a user's wallet. Admin role required.",
        "tags": [
          "Admin",
          "Game"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "userId",
                  "amount"
                ],
                "properties": {
                  "userId": {
                    "type": "string",
                    "description": "ID of the user to deduct seeds from"
                  },
                  "amount": {
                    "type": "integer",
                    "description": "Number of seeds to deduct"
                  },
                  "description": {
                    "type": "string",
                    "description": "Reason for deducting seeds"
                  },
                  "metadata": {
                    "type": "object",
                    "description": "Additional metadata for the transaction"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Seeds deducted successfully"
          },
          "400": {
            "description": "Invalid request or insufficient balance"
          },
          "403": {
            "description": "Forbidden - Admin access required"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/fragments": {
      "get": {
        "summary": "List the current user's outfit fragments cross-campaign",
        "description": "Returns every fragment balance row the user has, joined with outfit metadata\n(name, thumbnail, fragmentPrice, shape) plus an `owned` flag indicating whether\nthe user already has the redeemed outfit. Rows are ordered by `updatedAt DESC`.\n\nIndependent of any active campaign — past-cycle fragments stay queryable.\n",
        "tags": [
          "Game",
          "FragmentExchange"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "List of fragment rows joined with outfit details",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/FragmentInventoryItem"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/game/outfit/item/{id}": {
      "get": {
        "summary": "Get outfit item by ID",
        "description": "Get a single outfit item by ID",
        "tags": [
          "Game",
          "Outfit"
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            },
            "description": "Outfit Item ID"
          }
        ],
        "responses": {
          "200": {
            "description": "Outfit item details",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OutfitItem"
                }
              }
            }
          },
          "404": {
            "description": "Outfit item not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "put": {
        "summary": "(Admin) Update outfit item",
        "description": "Update an outfit item by ID. Admin access required.",
        "tags": [
          "Admin",
          "Game",
          "Outfit"
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            },
            "description": "Outfit Item ID"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "setId": {
                    "type": "integer"
                  },
                  "name": {
                    "type": "string"
                  },
                  "nameI18n": {
                    "type": "object"
                  },
                  "type": {
                    "type": "string",
                    "enum": [
                      "headscarf",
                      "glasses",
                      "bowtie",
                      "left_hand",
                      "right_hand",
                      "shoes"
                    ]
                  },
                  "description": {
                    "type": "string"
                  },
                  "descriptionI18n": {
                    "type": "object"
                  },
                  "rarity": {
                    "type": "integer",
                    "description": "Rarity ID referencing app_rarities table"
                  },
                  "riveProperty": {
                    "type": "object"
                  },
                  "metadata": {
                    "type": "object",
                    "description": "Extensible metadata for arbitrary key-value pairs",
                    "additionalProperties": true
                  },
                  "thumbnail": {
                    "type": "string"
                  },
                  "previewImage": {
                    "type": "string"
                  },
                  "price": {
                    "type": "integer"
                  },
                  "isActive": {
                    "type": "boolean"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Outfit item updated",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OutfitItem"
                }
              }
            }
          },
          "400": {
            "description": "Validation error"
          },
          "404": {
            "description": "Outfit item not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/outfit/item": {
      "post": {
        "summary": "(Admin) Create outfit item",
        "description": "Create a new outfit item. Admin access required.",
        "tags": [
          "Admin",
          "Game",
          "Outfit"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "name",
                  "type",
                  "rarity"
                ],
                "properties": {
                  "setId": {
                    "type": "integer"
                  },
                  "name": {
                    "type": "string"
                  },
                  "nameI18n": {
                    "type": "object"
                  },
                  "type": {
                    "type": "string",
                    "enum": [
                      "headscarf",
                      "glasses",
                      "bowtie",
                      "left_hand",
                      "right_hand",
                      "shoes"
                    ]
                  },
                  "description": {
                    "type": "string"
                  },
                  "descriptionI18n": {
                    "type": "object"
                  },
                  "rarity": {
                    "type": "integer",
                    "description": "Rarity ID referencing app_rarities table"
                  },
                  "riveProperty": {
                    "type": "object"
                  },
                  "metadata": {
                    "type": "object",
                    "description": "Extensible metadata for arbitrary key-value pairs",
                    "additionalProperties": true
                  },
                  "thumbnail": {
                    "type": "string"
                  },
                  "previewImage": {
                    "type": "string"
                  },
                  "price": {
                    "type": "integer"
                  },
                  "isActive": {
                    "type": "boolean"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Created outfit item",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OutfitItem"
                }
              }
            }
          },
          "400": {
            "description": "Validation error"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "get": {
        "summary": "List outfit items",
        "description": "List outfit items with pagination",
        "tags": [
          "Game",
          "Outfit"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "size",
            "schema": {
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "setId",
            "schema": {
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "type",
            "schema": {
              "type": "string",
              "enum": [
                "headscarf",
                "glasses",
                "bowtie",
                "left_hand",
                "right_hand",
                "shoes"
              ]
            }
          },
          {
            "in": "query",
            "name": "isEvent",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "in": "query",
            "name": "isPurchasable",
            "schema": {
              "type": "boolean"
            },
            "description": "Filter by purchasable status"
          },
          {
            "in": "query",
            "name": "search",
            "schema": {
              "type": "string"
            },
            "description": "Search by name, description, type, or id"
          },
          {
            "in": "query",
            "name": "variantGroupId",
            "schema": {
              "type": "integer"
            },
            "description": "Filter items belonging to a specific variant group"
          }
        ],
        "responses": {
          "200": {
            "description": "List of outfit items",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "outfitItems": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/OutfitItem"
                      }
                    },
                    "total": {
                      "type": "integer"
                    },
                    "page": {
                      "type": "integer"
                    },
                    "size": {
                      "type": "integer"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/outfit/variant-group/{id}": {
      "get": {
        "summary": "(Admin) Get outfit variant group",
        "tags": [
          "Admin",
          "Game",
          "Outfit"
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Variant group details"
          },
          "404": {
            "description": "Not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "patch": {
        "summary": "(Admin) Update outfit variant group",
        "tags": [
          "Admin",
          "Game",
          "Outfit"
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string"
                  },
                  "isActivityOnly": {
                    "type": "boolean"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated variant group"
          },
          "400": {
            "description": "Validation error"
          },
          "403": {
            "description": "Admin access required"
          },
          "404": {
            "description": "Not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "delete": {
        "summary": "(Admin) Delete outfit variant group",
        "tags": [
          "Admin",
          "Game",
          "Outfit"
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Deleted successfully"
          },
          "400": {
            "description": "Group has linked items"
          },
          "403": {
            "description": "Admin access required"
          },
          "404": {
            "description": "Not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/outfit/variant-group": {
      "get": {
        "summary": "(Admin) List outfit variant groups",
        "tags": [
          "Admin",
          "Game",
          "Outfit"
        ],
        "parameters": [
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "size",
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "List of variant groups"
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "post": {
        "summary": "(Admin) Create outfit variant group",
        "tags": [
          "Admin",
          "Game",
          "Outfit"
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "name"
                ],
                "properties": {
                  "name": {
                    "type": "string"
                  },
                  "isActivityOnly": {
                    "type": "boolean"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Created variant group"
          },
          "400": {
            "description": "Validation error"
          },
          "403": {
            "description": "Admin access required"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/rarity/{id}": {
      "get": {
        "summary": "Get rarity by ID",
        "description": "Get a single rarity definition by ID",
        "tags": [
          "Game",
          "Rarity"
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            },
            "description": "Rarity ID"
          }
        ],
        "responses": {
          "200": {
            "description": "Rarity details",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Rarity"
                }
              }
            }
          },
          "404": {
            "description": "Rarity not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "put": {
        "summary": "(Admin) Update rarity",
        "description": "Update a rarity definition by ID. Admin access required.",
        "tags": [
          "Admin",
          "Game",
          "Rarity"
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            },
            "description": "Rarity ID"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "category": {
                    "type": "string",
                    "enum": [
                      "item",
                      "outfit",
                      "achievement"
                    ]
                  },
                  "level": {
                    "type": "integer"
                  },
                  "name": {
                    "type": "string"
                  },
                  "nameI18n": {
                    "type": "object"
                  },
                  "color": {
                    "type": "string"
                  },
                  "sortOrder": {
                    "type": "integer"
                  },
                  "isActive": {
                    "type": "boolean"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Rarity updated",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Rarity"
                }
              }
            }
          },
          "400": {
            "description": "Validation error"
          },
          "404": {
            "description": "Rarity not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/rarity": {
      "post": {
        "summary": "(Admin) Create rarity",
        "description": "Create a new rarity definition. Admin access required.",
        "tags": [
          "Admin",
          "Game",
          "Rarity"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "category",
                  "level",
                  "name",
                  "color"
                ],
                "properties": {
                  "category": {
                    "type": "string",
                    "enum": [
                      "item",
                      "outfit",
                      "achievement"
                    ],
                    "description": "Rarity category (item=道具, outfit=时装, achievement=成就)"
                  },
                  "level": {
                    "type": "integer",
                    "description": "Numeric level (e.g. 1=Common, 5=Legendary)"
                  },
                  "name": {
                    "type": "string"
                  },
                  "nameI18n": {
                    "type": "object"
                  },
                  "color": {
                    "type": "string",
                    "description": "Hex color string"
                  },
                  "sortOrder": {
                    "type": "integer"
                  },
                  "isActive": {
                    "type": "boolean"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Created rarity",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Rarity"
                }
              }
            }
          },
          "400": {
            "description": "Validation error"
          },
          "403": {
            "description": "Admin access required"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "get": {
        "summary": "List rarities",
        "description": "List rarity definitions, optionally filtered by category",
        "tags": [
          "Game",
          "Rarity"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "category",
            "schema": {
              "type": "string",
              "enum": [
                "item",
                "outfit",
                "achievement"
              ]
            },
            "description": "Filter by rarity category"
          }
        ],
        "responses": {
          "200": {
            "description": "List of rarities",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "rarities": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Rarity"
                      }
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/redemptions": {
      "post": {
        "summary": "Redeem fragments for an outfit",
        "description": "Atomic exchange: locks the user's fragment row (FOR UPDATE), checks ownership,\ndeducts `fragmentPrice` fragments, and inserts the outfit into the user's\ncollection. **Does NOT auto-grant the cycle bonus** — use\n`POST /api/v0/campaigns/fragment-exchange/claim-bonus` for that.\n",
        "tags": [
          "Game",
          "FragmentExchange"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "outfitItemId"
                ],
                "properties": {
                  "outfitItemId": {
                    "type": "integer",
                    "minimum": 1,
                    "description": "Outfit catalog id (outfit_items.id)"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Redemption created; outfit awarded",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "$ref": "#/components/schemas/RedemptionResult"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "INVALID_INPUT (Zod validation failed)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "NOT_FOUND — outfit doesn't exist or is inactive",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "409": {
            "description": "NOT_REDEEMABLE (fragmentPrice null) / INSUFFICIENT_FRAGMENTS / ALREADY_OWNED",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/game/shop/outfit/items": {
      "get": {
        "summary": "List shop outfit items",
        "description": "List outfit items available in shop with user owned status",
        "tags": [
          "Game",
          "Shop"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "default": 1
            }
          },
          {
            "in": "query",
            "name": "size",
            "schema": {
              "type": "integer",
              "default": 20,
              "maximum": 100
            }
          },
          {
            "in": "query",
            "name": "setId",
            "schema": {
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "owned",
            "schema": {
              "type": "boolean"
            },
            "description": "Filter by ownership status (true=owned, false=not owned, omit=all)"
          },
          {
            "in": "query",
            "name": "type",
            "schema": {
              "type": "string",
              "enum": [
                "headscarf",
                "glasses",
                "bowtie",
                "left_hand",
                "right_hand",
                "shoes"
              ]
            },
            "description": "Filter by outfit type (body part)"
          },
          {
            "in": "query",
            "name": "sortBy",
            "schema": {
              "type": "string",
              "enum": [
                "rarity",
                "price",
                "createdAt"
              ],
              "default": "rarity"
            },
            "description": "Sort field"
          },
          {
            "in": "query",
            "name": "order",
            "schema": {
              "type": "string",
              "enum": [
                "asc",
                "desc"
              ],
              "default": "desc"
            },
            "description": "Sort direction"
          },
          {
            "in": "query",
            "name": "isPurchasable",
            "schema": {
              "type": "boolean",
              "default": true
            },
            "description": "Filter by purchasable status (default true)"
          }
        ],
        "responses": {
          "200": {
            "description": "List of outfit items with owned status",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "outfitItems": {
                      "type": "array",
                      "items": {
                        "allOf": [
                          {
                            "$ref": "#/components/schemas/OutfitItem"
                          },
                          {
                            "type": "object",
                            "properties": {
                              "owned": {
                                "type": "boolean"
                              },
                              "isVariantUnlocked": {
                                "type": "boolean",
                                "description": "Whether the user has unlocked this activity-only variant item"
                              },
                              "isPurchasable": {
                                "type": "boolean",
                                "description": "Effective purchasable flag (may be overridden true for activity-unlocked variant items)"
                              }
                            }
                          }
                        ]
                      }
                    },
                    "total": {
                      "type": "integer"
                    },
                    "page": {
                      "type": "integer"
                    },
                    "size": {
                      "type": "integer"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/shop/purchase": {
      "post": {
        "summary": "Purchase outfit",
        "description": "Purchase an outfit item or set from the shop",
        "tags": [
          "Game",
          "Shop"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "goodsType",
                  "goodsId"
                ],
                "properties": {
                  "goodsType": {
                    "type": "string",
                    "enum": [
                      "outfit_item"
                    ],
                    "description": "Type of goods to purchase"
                  },
                  "goodsId": {
                    "type": "integer",
                    "description": "ID of the item to purchase"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Purchase successful",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "balance": {
                      "type": "integer",
                      "description": "Remaining balance after purchase"
                    },
                    "transactionId": {
                      "type": "string"
                    },
                    "purchasedGoods": {
                      "type": "object",
                      "properties": {
                        "type": {
                          "type": "string",
                          "enum": [
                            "outfit_item"
                          ]
                        },
                        "id": {
                          "type": "integer"
                        },
                        "name": {
                          "type": "string"
                        },
                        "price": {
                          "type": "integer"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error or business logic error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "402": {
            "description": "Insufficient seed balance"
          },
          "404": {
            "description": "Goods not found or unavailable"
          },
          "409": {
            "description": "Goods already owned"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/user/avatar/image": {
      "post": {
        "summary": "Upload avatar image",
        "description": "Upload a custom avatar image generated by the frontend. Saved to private object storage and stored on the user's avatar record.",
        "tags": [
          "Game",
          "User",
          "Avatar"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "required": [
                  "file"
                ],
                "properties": {
                  "file": {
                    "type": "string",
                    "format": "binary",
                    "description": "Avatar image file (png/jpeg/webp, max 5MB)"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Upload successful",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "imageUrl": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid file"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Avatar not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/user/avatar": {
      "post": {
        "summary": "create user avatar",
        "description": "create user avatar by paramater",
        "tags": [
          "Game",
          "User"
        ],
        "Security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "shape",
                  "color",
                  "name"
                ],
                "properties": {
                  "shape": {
                    "type": "string",
                    "example": "circle",
                    "description": "avatar shape",
                    "enum": [
                      "circle",
                      "square",
                      "triangle"
                    ]
                  },
                  "color": {
                    "type": "string",
                    "example": "#RRGGBB",
                    "description": "Hexadecimal color representation"
                  },
                  "name": {
                    "type": "string",
                    "example": "HeroAvatar",
                    "description": "The name of user's avatar"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The result of creating",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Avatar"
                }
              }
            }
          },
          "400": {
            "description": "Invalid request",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "An avatar with shape could not be found.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "INTERNAL_ERROR",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "patch": {
        "summary": "Update user avatar (legacy alias of PATCH /api/v2/avatar)",
        "description": "Behaviourally identical to `PATCH /api/v2/avatar` — same handler, same\nerror codes. Kept for shipped app versions (1.5.x switches characters\nthrough this path); new clients should call the v2 route.\n\n`shape` switches the active character to an **owned** shape (free and\nunlimited). A shape the user has not unlocked returns 403\n`AVATAR_NOT_OWNED` — unlocking is paid and only exists on\n`POST /api/v2/avatar/unlock`, so legacy clients cannot buy from here.\n",
        "tags": [
          "Game",
          "User"
        ],
        "Security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string",
                    "description": "New name for the avatar"
                  },
                  "shape": {
                    "type": "string",
                    "enum": [
                      "circle",
                      "square",
                      "triangle"
                    ],
                    "description": "Switch the active character to this owned shape (free)"
                  },
                  "outfit": {
                    "type": "object",
                    "description": "New outfit configuration"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successfully updated",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "type": "object"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error"
          },
          "403": {
            "description": "AVATAR_NOT_OWNED — the shape has not been unlocked yet"
          },
          "404": {
            "description": "User avatar not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "get": {
        "summary": "Get user avatar",
        "description": "Get the current user's avatar. Includes `energyState` (V1.4 燃脂力:\nenergy mapped to level per the `energy.levels` config; display only,\nthe backend does NOT gate on it). The 5-dim attributes\nremain in the response (deprecated).\n",
        "tags": [
          "Game",
          "User"
        ],
        "Security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully retrieved",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "$ref": "#/components/schemas/UserAvatar"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "User avatar not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/user/diary/{date}": {
      "get": {
        "summary": "Get single diary by date",
        "description": "Returns a single diary entry for the given date.",
        "tags": [
          "Game",
          "User",
          "Diary"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "date",
            "required": true,
            "schema": {
              "type": "string",
              "format": "date"
            },
            "description": "Diary date (YYYY-MM-DD)"
          }
        ],
        "responses": {
          "200": {
            "description": "Diary entry"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Diary not found"
          }
        }
      }
    },
    "/api/v0/game/user/diary/{year}/{month}": {
      "get": {
        "summary": "Get diary calendar marks",
        "description": "Returns dates with diaries for a given month, filtered by status (defaults to completed).",
        "tags": [
          "Game",
          "User",
          "Diary"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "year",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Year (YYYY)"
          },
          {
            "in": "path",
            "name": "month",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Month (MM)"
          },
          {
            "in": "query",
            "name": "status",
            "schema": {
              "type": "string",
              "enum": [
                "pending",
                "processing",
                "completed",
                "failed"
              ],
              "default": "completed"
            },
            "description": "Filter by diary status (defaults to completed)"
          }
        ],
        "responses": {
          "200": {
            "description": "Array of dates with diaries matching the status"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v0/game/user/diary": {
      "get": {
        "summary": "List user diaries",
        "description": "Returns paginated diaries for the current user within a date range.",
        "tags": [
          "Game",
          "User",
          "Diary"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "startDate",
            "required": true,
            "schema": {
              "type": "string",
              "format": "date"
            },
            "description": "Start date (YYYY-MM-DD)"
          },
          {
            "in": "query",
            "name": "endDate",
            "required": true,
            "schema": {
              "type": "string",
              "format": "date"
            },
            "description": "End date (YYYY-MM-DD)"
          },
          {
            "in": "query",
            "name": "status",
            "schema": {
              "type": "string",
              "enum": [
                "pending",
                "processing",
                "completed",
                "failed"
              ]
            },
            "description": "Filter by diary status"
          },
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "default": 1,
              "minimum": 1
            }
          },
          {
            "in": "query",
            "name": "pageSize",
            "schema": {
              "type": "integer",
              "default": 20,
              "minimum": 1,
              "maximum": 50
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Paginated list of user diaries"
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "patch": {
        "summary": "Mark diaries as read",
        "description": "Mark one or more diaries as read for the current user.",
        "tags": [
          "Game",
          "User",
          "Diary"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "diaryIds"
                ],
                "properties": {
                  "diaryIds": {
                    "type": "array",
                    "items": {
                      "type": "integer"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Diaries marked as read"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/user/outfit/item": {
      "get": {
        "summary": "List user owned outfit items",
        "description": "Returns a list of outfit items owned by the authenticated user.",
        "tags": [
          "Game",
          "User"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "default": 1
            }
          },
          {
            "in": "query",
            "name": "size",
            "schema": {
              "type": "integer",
              "default": 20
            }
          },
          {
            "in": "query",
            "name": "sortBy",
            "schema": {
              "type": "string",
              "enum": [
                "rarity",
                "createdAt"
              ],
              "default": "createdAt"
            }
          },
          {
            "in": "query",
            "name": "order",
            "schema": {
              "type": "string",
              "enum": [
                "asc",
                "desc"
              ],
              "default": "desc"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "List of owned outfit items",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "list": {
                          "type": "array",
                          "items": {
                            "$ref": "#/components/schemas/OutfitItem"
                          }
                        },
                        "total": {
                          "type": "integer"
                        },
                        "page": {
                          "type": "integer"
                        },
                        "size": {
                          "type": "integer"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/user/wallet": {
      "get": {
        "summary": "Get user's wallet",
        "description": "Retrieve the authenticated user's wallet balance and transaction history",
        "tags": [
          "Game",
          "Wallet"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully retrieved user's wallet",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "type": "object",
                        "properties": {
                          "userId": {
                            "type": "string"
                          },
                          "balance": {
                            "type": "integer"
                          },
                          "createdAt": {
                            "type": "string",
                            "format": "date-time"
                          },
                          "updatedAt": {
                            "type": "string",
                            "format": "date-time"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized - missing or invalid session"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/user/wallet/transaction": {
      "get": {
        "summary": "Get user wallet transaction history",
        "description": "Retrieve the authenticated user's wallet transaction history",
        "tags": [
          "Game",
          "Wallet"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "default": 1
            },
            "description": "Page number"
          },
          {
            "in": "query",
            "name": "size",
            "schema": {
              "type": "integer",
              "default": 20,
              "maximum": 100
            },
            "description": "Items per page"
          },
          {
            "in": "query",
            "name": "type",
            "schema": {
              "type": "string",
              "enum": [
                "earn",
                "spend",
                "refund",
                "recharge",
                "system_add",
                "system_deduct"
              ]
            },
            "description": "Filter by transaction type"
          }
        ],
        "responses": {
          "200": {
            "description": "Transaction history retrieved successfully"
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/wallet": {
      "get": {
        "summary": "(Admin) Get user wallet(s)",
        "description": "Query user wallet information. Admin role required.\n- If userId is provided, returns that user's wallet.\n- If userId is not provided, returns a paginated list of all wallets.\n",
        "tags": [
          "Admin",
          "Game"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "userId",
            "schema": {
              "type": "string"
            },
            "description": "ID of a specific user to query (optional). Returns 404 if the user has no wallet."
          },
          {
            "in": "query",
            "name": "size",
            "schema": {
              "type": "integer",
              "default": 20,
              "maximum": 100
            },
            "description": "Number of records per page (for list query)"
          },
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "default": 1
            },
            "description": "Page number, starts from 1 (for list query)"
          }
        ],
        "responses": {
          "200": {
            "description": "Wallet info retrieved successfully"
          },
          "400": {
            "description": "Invalid request parameters"
          },
          "403": {
            "description": "Forbidden - Admin access required"
          },
          "404": {
            "description": "Wallet not found (only when userId is specified)"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/game/wallet/transaction": {
      "get": {
        "summary": "(Admin) Get user wallet transaction history",
        "description": "Retrieve any user's wallet transaction history. Admin role required.",
        "tags": [
          "Admin",
          "Game"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "userId",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "User ID to query transactions for"
          },
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "default": 1
            },
            "description": "Page number"
          },
          {
            "in": "query",
            "name": "size",
            "schema": {
              "type": "integer",
              "default": 20,
              "maximum": 100
            },
            "description": "Items per page"
          },
          {
            "in": "query",
            "name": "type",
            "schema": {
              "type": "string",
              "enum": [
                "earn",
                "spend",
                "refund",
                "recharge",
                "system_add",
                "system_deduct"
              ]
            },
            "description": "Filter by transaction type"
          }
        ],
        "responses": {
          "200": {
            "description": "Transaction history retrieved successfully"
          },
          "400": {
            "description": "Invalid request parameters"
          },
          "403": {
            "description": "Forbidden - Admin access required"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/invite-codes": {
      "get": {
        "summary": "Get invite codes list (admin only)",
        "description": "Get paginated list of invite codes with optional filters",
        "tags": [
          "Admin",
          "InviteCodes"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "default": 1
            },
            "description": "Page number"
          },
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "type": "integer",
              "default": 20
            },
            "description": "Items per page"
          },
          {
            "in": "query",
            "name": "status",
            "schema": {
              "type": "string",
              "enum": [
                "active",
                "used",
                "expired",
                "disabled"
              ]
            },
            "description": "Filter by status"
          },
          {
            "in": "query",
            "name": "identifier",
            "schema": {
              "type": "string"
            },
            "description": "Filter by identifier"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully retrieved invite codes",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "items": {
                          "type": "array",
                          "items": {
                            "type": "object",
                            "properties": {
                              "id": {
                                "type": "string"
                              },
                              "code": {
                                "type": "string"
                              },
                              "identifier": {
                                "type": "string"
                              },
                              "status": {
                                "type": "string"
                              },
                              "usedAt": {
                                "type": "string"
                              },
                              "expiresAt": {
                                "type": "string"
                              },
                              "createdAt": {
                                "type": "string"
                              },
                              "createdBy": {
                                "type": "string"
                              }
                            }
                          }
                        },
                        "pagination": {
                          "type": "object"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "Forbidden - Admin access required"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "post": {
        "summary": "Generate invite codes (admin only)",
        "description": "Generate one or more invite codes (max 10 at a time)",
        "tags": [
          "Admin",
          "InviteCodes"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "count"
                ],
                "properties": {
                  "count": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 10,
                    "example": 5,
                    "description": "Number of codes to generate (1-10)"
                  },
                  "expiresAt": {
                    "type": "string",
                    "format": "date-time",
                    "example": "2024-12-31T23:59:59Z",
                    "description": "Optional expiration date"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Invite codes generated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "codes": {
                          "type": "array",
                          "items": {
                            "type": "object",
                            "properties": {
                              "id": {
                                "type": "string"
                              },
                              "code": {
                                "type": "string"
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid request (count out of range)"
          },
          "403": {
            "description": "Forbidden - Admin access required"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/invite-codes/verify": {
      "post": {
        "summary": "Verify invite code",
        "description": "Verify if an invite code is valid and can be used",
        "tags": [
          "InviteCodes"
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "identifier",
                  "code"
                ],
                "properties": {
                  "identifier": {
                    "type": "string",
                    "example": "device_unique_id_123",
                    "description": "Device ID"
                  },
                  "code": {
                    "type": "string",
                    "example": "ABC123",
                    "description": "6-character invite code"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Verification result",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "valid": {
                          "type": "boolean",
                          "example": true
                        },
                        "message": {
                          "type": "string",
                          "example": "Invite code is valid"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid request (missing code)"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/me/bind-referrer": {
      "post": {
        "summary": "Bind current user to an inviter via referral code (idempotent)",
        "tags": [
          "Referral"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "code"
                ],
                "properties": {
                  "code": {
                    "type": "string"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Bound (newly or already bound)"
          },
          "400": {
            "description": "Invalid code or self-invite"
          }
        }
      }
    },
    "/api/v0/me/channels": {
      "get": {
        "summary": "Available agent contact addresses for the current user",
        "tags": [
          "Profile"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "{ channels: [{ channel, address, linked }] } — available contact channels"
          },
          "401": {
            "description": "Not signed in"
          }
        }
      }
    },
    "/api/v0/me/invite": {
      "get": {
        "summary": "Get current user's invite code + share link + count",
        "tags": [
          "Referral"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": {
              "code": null,
              "shareLink": null,
              "invitedCount": null
            }
          }
        }
      }
    },
    "/api/v0/me/invitees": {
      "get": {
        "summary": "Paginated list of users invited by the current user",
        "tags": [
          "Referral"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "default": 1
            }
          },
          {
            "in": "query",
            "name": "size",
            "schema": {
              "type": "integer",
              "default": 20,
              "maximum": 100
            }
          }
        ]
      }
    },
    "/api/v0/messaging/imessage-lines": {
      "get": {
        "summary": "Get least-loaded iMessage line (load-balanced)",
        "description": "Returns a single-element array with the least-loaded iMessage line\nfor the /get-started CTA, ranked by today's in+out message count\nascending. Lines that have hit their daily_quota are skipped; if\nevery line is over quota the least-loaded one is returned anyway\nso the button keeps working. Public — no auth.\n",
        "tags": [
          "Public",
          "Messaging"
        ],
        "responses": {
          "200": {
            "description": "Available lines",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "lines": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "phone": {
                            "type": "string",
                            "description": "E.164 phone, e.g. +14156974954"
                          },
                          "label": {
                            "type": "string",
                            "nullable": true
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/notifications/{id}": {
      "put": {
        "summary": "Mark notification as read",
        "description": "Mark a specific notification as read for the currently logged in user.\n",
        "tags": [
          "Notifications"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Notification ID"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully marked as read",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "message": {
                      "type": "string",
                      "example": "Notification marked as read"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Notification not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "delete": {
        "summary": "Delete notification",
        "description": "Delete a specific notification for the currently logged in user.\n",
        "tags": [
          "Notifications"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Notification ID"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully deleted",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "message": {
                      "type": "string",
                      "example": "Notification deleted"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Notification not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/notifications": {
      "get": {
        "summary": "Get user notifications with pagination",
        "description": "Get paginated list of notifications for the currently logged in user.\nSupports filtering by status, type, and priority.\n",
        "tags": [
          "Notifications"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            },
            "description": "Page number"
          },
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 20
            },
            "description": "Items per page"
          },
          {
            "in": "query",
            "name": "status",
            "schema": {
              "type": "string",
              "enum": [
                "unread",
                "read",
                "archived"
              ]
            },
            "description": "Filter by notification status"
          },
          {
            "in": "query",
            "name": "type",
            "schema": {
              "type": "string"
            },
            "description": "Filter by notification type"
          },
          {
            "in": "query",
            "name": "priority",
            "schema": {
              "type": "string",
              "enum": [
                "low",
                "normal",
                "high",
                "urgent"
              ]
            },
            "description": "Filter by notification priority"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully retrieved notifications",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "items": {
                          "type": "array",
                          "items": {
                            "type": "object",
                            "properties": {
                              "id": {
                                "type": "string"
                              },
                              "userId": {
                                "type": "string"
                              },
                              "title": {
                                "type": "string"
                              },
                              "content": {
                                "type": "string"
                              },
                              "type": {
                                "type": "string"
                              },
                              "status": {
                                "type": "string"
                              },
                              "priority": {
                                "type": "string"
                              },
                              "metadata": {
                                "type": "object"
                              },
                              "readAt": {
                                "type": "string",
                                "format": "date-time",
                                "nullable": true
                              },
                              "createdAt": {
                                "type": "string",
                                "format": "date-time"
                              },
                              "updatedAt": {
                                "type": "string",
                                "format": "date-time"
                              }
                            }
                          }
                        },
                        "pagination": {
                          "type": "object",
                          "properties": {
                            "page": {
                              "type": "integer"
                            },
                            "limit": {
                              "type": "integer"
                            },
                            "total": {
                              "type": "integer"
                            },
                            "totalPages": {
                              "type": "integer"
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "post": {
        "summary": "Mark all notifications as read",
        "description": "Mark all unread notifications as read for the currently logged in user.\n",
        "tags": [
          "Notifications"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "action": {
                    "type": "string",
                    "enum": [
                      "markAllRead",
                      "deleteAll"
                    ],
                    "description": "Action to perform"
                  },
                  "status": {
                    "type": "string",
                    "enum": [
                      "unread",
                      "read",
                      "archived"
                    ],
                    "description": "Filter by status when deleting all"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successfully processed",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "count": {
                          "type": "integer",
                          "description": "Number of notifications processed"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/oauth2/auth-url": {
      "post": {
        "summary": "Generate OAuth2 authorization URL",
        "description": "Generate OAuth2 authorization URL",
        "tags": [
          "OAuth2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "provider",
                  "redirectUri"
                ],
                "properties": {
                  "provider": {
                    "type": "string",
                    "example": "google"
                  },
                  "redirectUri": {
                    "type": "string",
                    "example": "https://app.example.com/api/oauth2/callback"
                  },
                  "additionalScopes": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    },
                    "example": [
                      "email",
                      "profile"
                    ]
                  },
                  "source": {
                    "type": "string",
                    "enum": [
                      "app",
                      "web"
                    ]
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Authorization URL generated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "authUrl": {
                      "type": "string",
                      "example": "https://accounts.google.com/o/oauth2/v2/auth?..."
                    },
                    "state": {
                      "type": "string",
                      "example": "state_token_123"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid request parameters",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized access",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/oauth2/authorize": {
      "post": {
        "summary": "Create authorization session",
        "description": "Create OAuth2 authorization session token",
        "tags": [
          "OAuth2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "endUser"
                ],
                "properties": {
                  "endUser": {
                    "type": "object",
                    "required": [
                      "id"
                    ],
                    "properties": {
                      "id": {
                        "type": "string"
                      },
                      "email": {
                        "type": "string"
                      },
                      "displayName": {
                        "type": "string"
                      }
                    }
                  },
                  "allowedIntegrations": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Authorization session created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "sessionToken": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Authorization session created successfullyUnauthorized access"
          },
          "500": {
            "description": "Authorization session created successfullyInternal server error"
          }
        }
      }
    },
    "/api/v0/oauth2/connections": {
      "get": {
        "summary": "Get user OAuth2 connections",
        "description": "Get all OAuth2 connections for the current user",
        "tags": [
          "OAuth2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully returned connection list",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "connections": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/OAuth2Connection"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized access",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "delete": {
        "summary": "Delete OAuth2 connection",
        "description": "Delete an OAuth2 connection for the current user by provider name",
        "tags": [
          "OAuth2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "provider"
                ],
                "properties": {
                  "provider": {
                    "type": "string",
                    "example": "google",
                    "description": "Provider name to disconnect"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Connection deleted successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "message": {
                      "type": "string",
                      "example": "Connection deleted successfully"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid request parameters",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized access",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Connection not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/oauth2/integrations": {
      "get": {
        "summary": "Get available OAuth2 integrations",
        "description": "Get available OAuth2 provider integrations for the current user",
        "tags": [
          "OAuth2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully returned integration list",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "integrations": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/OAuth2Integration"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized access",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/oauth2/integrations/token": {
      "get": {
        "deprecated": true,
        "summary": "[DEPRECATED] Get integration access token — use MCP `app_connector` tool instead",
        "description": "**DEPRECATED — will be removed.** Use the MCP `app_connector` tool at `/api/mcp` instead,\nwhich covers identical functionality with safer auth (api-key + JWT, userId derived from\nJWT instead of query param) and richer status discriminators\n(`connected | not_connected | ambiguous | reauth_required | ...`).\n\nGet an OAuth2 access token for a connected integration provider.\nSupports fuzzy matching (e.g. \"gmail\" matches \"google-gmail\").\nAutomatically refreshes expired tokens and persists the new credentials.\nWithout a provider parameter, lists all active integrations.\nAuth: Session / JWT / API Key (x-api-key header + userId query param)\n",
        "tags": [
          "Integrations",
          "Deprecated"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "jwtAuth": []
          },
          {
            "apiKeyAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "provider",
            "schema": {
              "type": "string"
            },
            "description": "Provider name (e.g. \"gmail\", \"google-calendar\", \"notion\"). Supports fuzzy matching. Omit to list all active integrations."
          },
          {
            "in": "query",
            "name": "userId",
            "schema": {
              "type": "string"
            },
            "description": "User ID (required when using API Key auth)"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully returned token or integration list",
            "content": {
              "application/json": {
                "schema": {
                  "oneOf": [
                    {
                      "type": "object",
                      "properties": {
                        "success": {
                          "type": "boolean"
                        },
                        "provider": {
                          "type": "string"
                        },
                        "access_token": {
                          "type": "string"
                        },
                        "token_type": {
                          "type": "string"
                        },
                        "expires_at": {
                          "type": "string",
                          "nullable": true
                        },
                        "refreshed": {
                          "type": "boolean"
                        }
                      }
                    },
                    {
                      "type": "object",
                      "properties": {
                        "success": {
                          "type": "boolean"
                        },
                        "integrations": {
                          "type": "array"
                        },
                        "count": {
                          "type": "number"
                        }
                      }
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Ambiguous provider match or token refresh failed"
          },
          "401": {
            "description": "Unauthorized access"
          },
          "404": {
            "description": "No active connection found for provider"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/oauth2/providers/{id}/info": {
      "get": {
        "summary": "Get public OAuth2 provider info",
        "description": "Get public-facing provider info (name, logo) by ID. Supports JWT auth.",
        "tags": [
          "OAuth2"
        ],
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Provider info returned"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Provider not found"
          }
        }
      }
    },
    "/api/v0/oauth2/providers/{id}": {
      "get": {
        "summary": "(Admin) Get single OAuth2 provider",
        "description": "Get OAuth2 provider configuration by ID, including inactive ones.\n\n**`clientSecret` is never returned** — only `hasClientSecret: boolean`.\nFor the public-facing name/logo lookup any signed-in user may call, use\n`GET /api/v0/oauth2/providers/{id}/info`.\n",
        "tags": [
          "Admin",
          "OAuth2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Provider ID",
            "example": "provider_123"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully returned provider configuration",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuth2ProviderResponse"
                }
              }
            }
          },
          "404": {
            "description": "Provider not found, or the caller is not an admin — the endpoint hides\nitself behind the same status rather than returning 403.\n",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string",
                      "example": "Provider not found"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "put": {
        "summary": "(Admin) Update OAuth2 provider",
        "description": "Partial update of an OAuth2 provider configuration.\nSupports nested structure with config object or flat structure with config fields at root.\n\n**Omitted or empty config fields keep their stored value.** In particular an\nempty `clientSecret` means \"leave the existing secret alone\" — required,\nsince `GET` no longer hands the secret back for the form to resubmit.\n",
        "tags": [
          "Admin",
          "OAuth2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Provider ID",
            "example": "provider_123"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateOAuth2ProviderRequest"
              },
              "example": {
                "displayName": "Google Workspace",
                "logo": "/images/providers/google-new.png",
                "config": {
                  "scope": [
                    "https://www.googleapis.com/auth/calendar",
                    "https://www.googleapis.com/auth/drive",
                    "https://www.googleapis.com/auth/gmail"
                  ]
                },
                "isActive": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Provider updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuth2ProviderResponse"
                }
              }
            }
          },
          "400": {
            "description": "Validation error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Provider not found, or the caller is not an admin — the endpoint hides\nitself behind the same status rather than returning 403.\n",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string",
                      "example": "Provider not found"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "delete": {
        "summary": "(Admin) Delete OAuth2 provider",
        "description": "Delete OAuth2 provider by ID. Fails if any user connection still uses it.",
        "tags": [
          "Admin",
          "OAuth2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Provider ID",
            "example": "provider_123"
          }
        ],
        "responses": {
          "200": {
            "description": "Provider deleted successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "message": {
                      "type": "string",
                      "example": "Provider deleted successfully"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Provider not found, or the caller is not an admin — the endpoint hides\nitself behind the same status rather than returning 403.\n",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string",
                      "example": "Provider not found"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal server error or failed to delete provider",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/oauth2/providers/init": {
      "post": {
        "summary": "(Admin) Initialize default OAuth2 providers",
        "description": "Seed the five default Google providers (Gmail, Calendar, Contacts, Drive, Tasks)\nfrom `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`. Providers that already exist\nare skipped, never overwritten. The response omits `clientSecret`.\n",
        "tags": [
          "Admin",
          "OAuth2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": false,
          "description": "Optional configuration overrides"
        },
        "responses": {
          "200": {
            "description": "Providers initialized successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "message": {
                      "type": "string"
                    },
                    "providers": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/OAuth2Provider"
                      }
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Not an admin (endpoint hides itself rather than returning 403)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/oauth2/providers": {
      "get": {
        "summary": "(Admin) List OAuth2 providers",
        "description": "List all OAuth2 provider configurations, including inactive ones.\n\n**`clientSecret` is never returned** — only `hasClientSecret: boolean`.\nClient-facing integration lists come from `GET /api/v0/oauth2/integrations`,\nwhich is what the mobile app uses; this endpoint is admin-only.\n",
        "tags": [
          "Admin",
          "OAuth2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully returned provider list",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuth2ProvidersResponse"
                }
              }
            }
          },
          "404": {
            "description": "Not an admin (endpoint hides itself rather than returning 403)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "post": {
        "summary": "(Admin) Create new OAuth2 provider",
        "description": "Create a new OAuth2 provider configuration.\nSupports nested structure with config object or flat structure with config fields at root.\nThe response omits `clientSecret`.\n",
        "tags": [
          "Admin",
          "OAuth2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateOAuth2ProviderRequest"
              },
              "example": {
                "name": "google",
                "displayName": "Google",
                "logo": "/images/providers/google.png",
                "config": {
                  "clientId": "client_id_123",
                  "clientSecret": "client_secret_123",
                  "authUrl": "https://accounts.google.com/o/oauth2/v2/auth",
                  "tokenUrl": "https://oauth2.googleapis.com/token",
                  "scope": [
                    "https://www.googleapis.com/auth/calendar",
                    "https://www.googleapis.com/auth/drive"
                  ],
                  "redirectUri": "https://example.com/oauth2/callback",
                  "responseType": "code",
                  "grantType": "authorization_code"
                },
                "isActive": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Provider created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OAuth2ProviderResponse"
                }
              }
            }
          },
          "400": {
            "description": "Validation error or missing required fields",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "Not an admin (endpoint hides itself rather than returning 403)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/openai/chat": {
      "post": {
        "summary": "OpenAI chat completions proxy",
        "description": "Proxies requests to OpenAI Chat Completions API.\nAccepts the same request body as OpenAI's `/v1/chat/completions`.\nThe server injects the API key — clients never need it.\nSupports both streaming (SSE) and non-streaming responses.\n",
        "tags": [
          "OpenAI"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "model",
                  "messages"
                ],
                "properties": {
                  "model": {
                    "type": "string",
                    "example": "gpt-4o"
                  },
                  "messages": {
                    "type": "array",
                    "items": {
                      "type": "object",
                      "properties": {
                        "role": {
                          "type": "string",
                          "enum": [
                            "system",
                            "user",
                            "assistant"
                          ]
                        },
                        "content": {
                          "type": "string"
                        }
                      }
                    }
                  },
                  "stream": {
                    "type": "boolean",
                    "default": false
                  },
                  "temperature": {
                    "type": "number"
                  },
                  "max_tokens": {
                    "type": "integer"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OpenAI response (JSON or SSE stream depending on `stream` flag)"
          },
          "401": {
            "description": "Unauthorized"
          },
          "502": {
            "description": "OpenAI API error"
          }
        }
      }
    },
    "/api/v0/prices": {
      "get": {
        "summary": "List active tier prices from Stripe",
        "description": "Returns Stripe prices tagged with `metadata.tier` (in-process TTL\ncache). Public — the pricing page reads it unauthenticated. Migrated\nfrom koda-pay's GET /v1/prices.\n",
        "tags": [
          "Subscriptions"
        ],
        "responses": {
          "200": {
            "description": "Price catalogue"
          },
          "503": {
            "description": "Stripe not configured"
          }
        }
      }
    },
    "/api/v0/profile": {
      "get": {
        "summary": "Get current user profile",
        "description": "Get personal profile information for the currently logged in user.\nIf no profile exists, returns null.\nTimezone and location are automatically populated on first login via browser APIs.\n",
        "tags": [
          "User"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully retrieved user profile",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "nullable": true,
                      "properties": {
                        "userId": {
                          "type": "string",
                          "example": "user_123"
                        },
                        "avatarUrl": {
                          "type": "string",
                          "nullable": true,
                          "example": "https://example.com/avatar.jpg"
                        },
                        "bio": {
                          "type": "string",
                          "nullable": true
                        },
                        "gender": {
                          "type": "string",
                          "nullable": true,
                          "enum": [
                            "male",
                            "female",
                            "them",
                            "prefer_not_to_say"
                          ],
                          "example": "female"
                        },
                        "birthdate": {
                          "type": "string",
                          "nullable": true,
                          "format": "date",
                          "example": "1995-08-20"
                        },
                        "locale": {
                          "type": "string",
                          "example": "zh-CN",
                          "description": "User locale (e.g., en, zh-CN, ja)"
                        },
                        "timezone": {
                          "type": "string",
                          "nullable": true,
                          "example": "Asia/Shanghai",
                          "description": "IANA timezone, auto-detected from browser on first login"
                        },
                        "location": {
                          "type": "object",
                          "nullable": true,
                          "description": "GPS coordinates, auto-detected from browser on first login",
                          "properties": {
                            "latitude": {
                              "type": "number",
                              "example": 39.9042
                            },
                            "longitude": {
                              "type": "number",
                              "example": 116.4074
                            }
                          }
                        },
                        "notificationSettings": {
                          "type": "object",
                          "nullable": true,
                          "properties": {
                            "push": {
                              "type": "boolean"
                            },
                            "whatsapp": {
                              "type": "boolean"
                            },
                            "phone": {
                              "type": "boolean"
                            }
                          }
                        },
                        "personalizedSettings": {
                          "type": "object",
                          "nullable": true,
                          "additionalProperties": true
                        },
                        "metadata": {
                          "type": "object",
                          "nullable": true,
                          "additionalProperties": true
                        },
                        "createdAt": {
                          "type": "string",
                          "format": "date-time"
                        },
                        "updatedAt": {
                          "type": "string",
                          "format": "date-time"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string",
                      "example": "Unauthorized"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "put": {
        "summary": "Partially update user profile",
        "description": "Update specific fields of the current user's profile.\nAll fields are optional - only provided fields will be updated.\nValidates notification settings keys (push, whatsapp, phone) and personalized settings.\n",
        "tags": [
          "User"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "avatarUrl": {
                    "type": "string",
                    "nullable": true,
                    "example": "https://example.com/avatar.jpg",
                    "description": "User avatar image URL"
                  },
                  "bio": {
                    "type": "string",
                    "nullable": true,
                    "example": "User bio description",
                    "description": "User biography or description"
                  },
                  "gender": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "male",
                      "female",
                      "them",
                      "prefer_not_to_say"
                    ],
                    "description": "User gender (V1.4 health revamp)"
                  },
                  "birthdate": {
                    "type": "string",
                    "nullable": true,
                    "example": "1995-03-01",
                    "description": "Birthdate YYYY-MM-DD (V1.4 health revamp)"
                  },
                  "locale": {
                    "type": "string",
                    "example": "zh-CN",
                    "description": "User locale preference (e.g., zh-CN, en-US)"
                  },
                  "timezone": {
                    "type": "string",
                    "nullable": true,
                    "example": "Asia/Shanghai",
                    "description": "User timezone (IANA timezone format)"
                  },
                  "location": {
                    "type": "object",
                    "nullable": true,
                    "description": "User location coordinates",
                    "properties": {
                      "latitude": {
                        "type": "number",
                        "example": 39.9042
                      },
                      "longitude": {
                        "type": "number",
                        "example": 116.4074
                      }
                    }
                  },
                  "notificationSettings": {
                    "type": "object",
                    "nullable": true,
                    "description": "Notification preferences",
                    "properties": {
                      "push": {
                        "type": "boolean",
                        "example": false
                      },
                      "whatsapp": {
                        "type": "boolean",
                        "example": false
                      },
                      "phone": {
                        "type": "boolean",
                        "example": false
                      }
                    }
                  },
                  "personalizedSettings": {
                    "type": "object",
                    "nullable": true,
                    "additionalProperties": true,
                    "description": "Personalized user settings (supports free-form fields)",
                    "properties": {
                      "labels": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        },
                        "example": [
                          "work",
                          "personal"
                        ],
                        "description": "User-defined labels"
                      },
                      "tags": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        },
                        "example": [
                          "important",
                          "urgent"
                        ],
                        "description": "User-defined tags"
                      }
                    },
                    "example": {
                      "labels": [
                        "work",
                        "personal"
                      ],
                      "tags": [
                        "important",
                        "urgent"
                      ],
                      "customField": "custom value",
                      "customNumber": 123
                    }
                  },
                  "metadata": {
                    "type": "object",
                    "nullable": true,
                    "additionalProperties": true,
                    "description": "Custom metadata object for additional profile data (supports any key-value pairs)",
                    "example": {
                      "theme": "dark",
                      "customField": "value"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Profile updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "message": {
                      "type": "string",
                      "example": "Profile updated successfully"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid request parameters - validation error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": false
                    },
                    "error": {
                      "type": "string",
                      "example": "VALIDATION_ERROR"
                    },
                    "message": {
                      "type": "string",
                      "example": "Invalid notification setting key: invalidKey"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized - Session token missing or invalid",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string",
                      "example": "Unauthorized"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": false
                    },
                    "error": {
                      "type": "string",
                      "example": "INTERNAL_ERROR"
                    },
                    "message": {
                      "type": "string",
                      "example": "Failed to update profile"
                    }
                  }
                }
              }
            }
          }
        }
      },
      "post": {
        "summary": "Create or completely update user profile",
        "description": "Create a new user profile or completely replace existing profile with provided data.\nThis endpoint performs an upsert operation - if profile exists, it will be completely replaced.\nThe locale field is required for profile creation.\n",
        "tags": [
          "User"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "locale"
                ],
                "properties": {
                  "avatarUrl": {
                    "type": "string",
                    "nullable": true,
                    "example": "https://example.com/avatar.jpg",
                    "description": "User avatar image URL"
                  },
                  "bio": {
                    "type": "string",
                    "nullable": true,
                    "example": "User bio description",
                    "description": "User biography or description"
                  },
                  "locale": {
                    "type": "string",
                    "example": "zh-CN",
                    "description": "User locale preference (required)"
                  },
                  "timezone": {
                    "type": "string",
                    "nullable": true,
                    "example": "Asia/Shanghai",
                    "description": "User timezone (IANA timezone format)"
                  },
                  "location": {
                    "type": "object",
                    "nullable": true,
                    "description": "User location coordinates",
                    "properties": {
                      "latitude": {
                        "type": "number",
                        "example": 39.9042
                      },
                      "longitude": {
                        "type": "number",
                        "example": 116.4074
                      }
                    }
                  },
                  "notificationSettings": {
                    "type": "object",
                    "nullable": true,
                    "description": "Notification preferences",
                    "properties": {
                      "push": {
                        "type": "boolean",
                        "example": false
                      },
                      "whatsapp": {
                        "type": "boolean",
                        "example": false
                      },
                      "phone": {
                        "type": "boolean",
                        "example": false
                      }
                    }
                  },
                  "personalizedSettings": {
                    "type": "object",
                    "nullable": true,
                    "additionalProperties": true,
                    "description": "Personalized user settings (supports free-form fields)",
                    "properties": {
                      "labels": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        },
                        "example": [
                          "work",
                          "personal"
                        ],
                        "description": "User-defined labels"
                      },
                      "tags": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        },
                        "example": [
                          "important",
                          "urgent"
                        ],
                        "description": "User-defined tags"
                      }
                    },
                    "example": {
                      "labels": [
                        "work",
                        "personal"
                      ],
                      "tags": [
                        "important",
                        "urgent"
                      ],
                      "customField": "custom value",
                      "customNumber": 123
                    }
                  },
                  "metadata": {
                    "type": "object",
                    "nullable": true,
                    "additionalProperties": true,
                    "description": "Custom metadata object for additional profile data (supports any key-value pairs)",
                    "example": {
                      "theme": "dark",
                      "customField": "value"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Profile created or updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "message": {
                      "type": "string",
                      "example": "Profile created/updated successfully"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized - Session token missing or invalid",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string",
                      "example": "Unauthorized"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": false
                    },
                    "error": {
                      "type": "string",
                      "example": "INTERNAL_ERROR"
                    },
                    "message": {
                      "type": "string",
                      "example": "Failed to create/update profile"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/short-link": {
      "post": {
        "summary": "Create a short link",
        "description": "Generate a short link code for a given URL.\nThe short code is stored in Redis with a configurable TTL (default 24 hours).\nAccess the short link via GET /s/{code} which 302-redirects to the original URL.\n",
        "tags": [
          "ShortLink"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "url"
                ],
                "properties": {
                  "url": {
                    "type": "string",
                    "format": "uri",
                    "description": "The original URL to shorten",
                    "example": "https://example.com/very/long/path?with=params"
                  },
                  "ttl": {
                    "type": "integer",
                    "description": "Time-to-live in seconds (default 86400 = 24h)",
                    "example": 86400
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Short link created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "code": {
                          "type": "string",
                          "description": "The 6-character short code",
                          "example": "aB3xYz"
                        },
                        "shortUrl": {
                          "type": "string",
                          "description": "Full short URL ready to share",
                          "example": "https://resolvai.ngrok.app/s/aB3xYz"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error - url is required",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": false
                    },
                    "error": {
                      "type": "string",
                      "example": "VALIDATION_ERROR"
                    },
                    "message": {
                      "type": "string",
                      "example": "url is required"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized - session or JWT token missing/invalid",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string",
                      "example": "Unauthorized"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": false
                    },
                    "error": {
                      "type": "string",
                      "example": "INTERNAL_ERROR"
                    },
                    "message": {
                      "type": "string",
                      "example": "Failed to create short link"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/subscription/cancel": {
      "post": {
        "summary": "Cancel the caller's Stripe subscription",
        "description": "Cancels at period end (default) or immediately (`{ immediate: true }`).\nApp-store (RC) subscriptions return 400 — manage those in iOS/Android\nsettings. The pay_subscription row is synced by the resulting\ncustomer.subscription.updated/deleted webhook. Migrated from koda-pay.\n",
        "tags": [
          "Subscriptions"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Cancellation scheduled/applied"
          },
          "400": {
            "description": "App-store managed subscription"
          },
          "404": {
            "description": "No active Stripe subscription"
          }
        }
      }
    },
    "/api/v0/subscription/invoices": {
      "get": {
        "summary": "List the caller's Stripe invoices (most recent 20)",
        "tags": [
          "Subscriptions"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Invoice list (empty when no Stripe customer)"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v0/subscription/link-revenuecat": {
      "post": {
        "summary": "Link the caller's account to RevenueCat (no-op stub)",
        "description": "Compatibility endpoint preserved for the mobile client API surface.\nThe client already aliases the RevenueCat anonymous id to our\ninternal `userId` via `Purchases.logIn(userId)`, so this server-side\nendpoint has nothing to do today and simply returns\n`{ success: true, data: { linked: true } }` for any authenticated\ncaller.\n\nReserved as a future hook for anonymous-user rescue logic — see\nspec §6.3.\n",
        "tags": [
          "Subscriptions"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Identity linked (no-op acknowledgement)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LinkRevenueCatResponse"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid session/JWT",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/subscription/me": {
      "get": {
        "summary": "Get caller's effective subscription state",
        "description": "Returns the caller's effective subscription state, derived from\nlocal `pay_subscription` rows that are active/trialing/in_grace_period\nwith `currentPeriodEnd` in the future. The response is the source of\ntruth used by the mobile client to gate Pro features.\n\nThe local state is kept in sync by the RevenueCat webhook\n(`POST /api/v0/revenuecat/webhook`) and the post-purchase push\n(`POST /api/v0/subscription/sync`). When no qualifying row exists,\n`isPro` is `false` and all representative fields are `null`.\n",
        "tags": [
          "Subscriptions"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Aggregated subscription state for the caller",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AggregatedSubscriptionStateResponse"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid session/JWT",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal error while aggregating local rows",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/subscription/payment-method": {
      "get": {
        "summary": "Get the card on file for the caller",
        "description": "Checkout subscription mode attaches the card to the subscription, not\nthe customer, so the customer-level default PM is checked first and the\nsubscription-level default is the fallback. Migrated from koda-pay.\n",
        "tags": [
          "Subscriptions"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Payment method (null when none on file)"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v0/subscription/resume": {
      "post": {
        "summary": "Undo a scheduled cancellation on the caller's Stripe subscription",
        "description": "Clears cancel_at_period_end. App-store (RC) subscriptions return 400.\nThe pay_subscription row is synced by the resulting\ncustomer.subscription.updated webhook. Migrated from koda-pay.\n",
        "tags": [
          "Subscriptions"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Subscription resumed"
          },
          "400": {
            "description": "App-store managed / nothing to resume"
          },
          "404": {
            "description": "No subscription"
          }
        }
      }
    },
    "/api/v0/subscription/status": {
      "get": {
        "summary": "Aggregated subscription state + Stripe billing detail",
        "description": "Returns {@link aggregateSubscriptionState} (the canonical Pro-gating\nstate) plus, for users with a Stripe customer, live Stripe billing\ndetail (cancelAtPeriodEnd, interval, paymentIssue). RC-managed users get\n`stripe: null` — manage those in the app store. Migrated from koda-pay's\nGET /v1/subscription/status.\n",
        "tags": [
          "Subscriptions"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Subscription status"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v0/subscription/sync": {
      "post": {
        "summary": "Pull caller's subscription state from RevenueCat REST and upsert",
        "description": "Post-purchase pull path: fetches the caller's subscriber object from\nthe RevenueCat REST API, upserts every recognized subscription into\n`pay_subscription`, and returns the freshly aggregated state.\n\nUse this immediately after a successful in-app purchase so the client\ndoes not have to wait for the asynchronous webhook to land. The\nwebhook remains the authoritative path for ongoing state changes;\nthis endpoint exists to close the race window on the first purchase.\n\nBehavior notes:\n- Per-user rate-limited via Redis (fail-open on Redis trouble).\n- Unknown product ids and non-purchase stores (e.g. PROMOTIONAL)\n  are skipped fail-soft so partial RC profiles still succeed.\n- Returns `503 SERVICE_UNAVAILABLE` when the server is missing the\n  `REVENUECAT_REST_API_KEY` env var (configuration problem).\n- Returns `502 UPSTREAM_UNAVAILABLE` when the RevenueCat REST API\n  itself fails or times out (5s).\n",
        "tags": [
          "Subscriptions"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Subscriptions pulled and upserted; returns aggregated state",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AggregatedSubscriptionStateResponse"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid session/JWT",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "429": {
            "description": "Rate-limited by the per-user sync lock. Clients should honor\nthe `Retry-After` response header (seconds).\n",
            "headers": {
              "Retry-After": {
                "schema": {
                  "type": "integer",
                  "example": 10
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Unexpected server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "502": {
            "description": "RevenueCat REST API unavailable or returned an error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "503": {
            "description": "Server missing required RevenueCat configuration",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v0/tracking/attribute": {
      "post": {
        "summary": "Stitch a session's anonymous events to the signed-in user",
        "description": "Called once by the client right after signup / login to backfill\nthe `userId` on all previously anonymous tracking events that\nshare the supplied `sessionId`.\n",
        "tags": [
          "Tracking"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "sessionId"
                ],
                "properties": {
                  "sessionId": {
                    "type": "string"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Returns { success, data: { attributed: number } }"
          },
          "400": {
            "description": "Invalid payload"
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal error"
          }
        }
      }
    },
    "/api/v0/turbo-reward/conversions": {
      "post": {
        "summary": "Upload Turbo Reward conversions",
        "description": "Upload conversion events to Turbo Reward (TurboLink) Conversions API.\nEach conversion requires a tlclid (click ID) for attribution.\n",
        "tags": [
          "TurboReward"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "tlclid"
                ],
                "properties": {
                  "tlclid": {
                    "type": "string",
                    "description": "Turbo Reward click ID from landing page URL param"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Upload results",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "logId": {
                            "type": "string"
                          },
                          "success": {
                            "type": "boolean"
                          },
                          "error": {
                            "type": "string"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v0/user-logs": {
      "post": {
        "summary": "Create user log",
        "description": "Create a user log entry for business operations",
        "tags": [
          "User Logs"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "action"
                ],
                "properties": {
                  "action": {
                    "type": "string",
                    "description": "Business operation type (e.g., order_created, connection_created)"
                  },
                  "resourceType": {
                    "type": "string",
                    "description": "Resource type (e.g., order, connection, profile)"
                  },
                  "resourceId": {
                    "type": "string",
                    "description": "Resource ID"
                  },
                  "description": {
                    "type": "string",
                    "description": "Human-readable operation description"
                  },
                  "metadata": {
                    "type": "object",
                    "description": "Log metadata (before/after data, changed fields, IP, User-Agent, etc.)"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successfully created log"
          },
          "400": {
            "description": "Bad request"
          },
          "401": {
            "description": "Unauthorized access"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v0/webhook/revenuecat": {
      "post": {
        "summary": "RevenueCat webhook ingestion (push), migrated from koda-pay",
        "description": "Auth: `Authorization: Bearer <token>` against REVENUECAT_WEBHOOK_SECRET\n(and optional _NEXT for zero-downtime rotation). Always returns 200 on\nauth success — even if processing fails — to avoid RC's retry storm;\nfailures are recorded on pay_subscription_events.error_message and\nretried by the reconcile cron. Relevant events trigger a re-pull of the\nsubscriber into pay_subscription (shares the /sync mapping).\n",
        "tags": [
          "Subscriptions"
        ],
        "responses": {
          "200": {
            "description": "Received"
          },
          "401": {
            "description": "Bad token"
          },
          "503": {
            "description": "Webhook secret not configured"
          }
        }
      }
    },
    "/api/v0/webhook/stripe": {
      "post": {
        "summary": "Stripe subscription webhook (migrated from koda-pay)",
        "description": "Verifies the Stripe signature against `STRIPE_WEBHOOK_SECRET`, dedups on\n`pay_subscription_events.event_id`, and applies subscription-lifecycle\nevents to `pay_subscription`. Processed synchronously; a non-2xx tells\nStripe to retry, and the dedup guard makes retries safe.\n",
        "tags": [
          "Subscriptions"
        ],
        "responses": {
          "200": {
            "description": "Event processed (or duplicate)"
          },
          "400": {
            "description": "Missing/invalid signature"
          },
          "503": {
            "description": "Stripe not configured on this server"
          }
        }
      }
    },
    "/api/v1/memory/{id}": {
      "get": {
        "summary": "Get a single memory by ID",
        "description": "Get memory details by ID",
        "tags": [
          "Memory"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Memory ID"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully retrieved memory"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Memory not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "patch": {
        "summary": "Update a memory",
        "description": "Update memory fields",
        "tags": [
          "Memory"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Memory ID"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "title": {
                    "type": "string"
                  },
                  "description": {
                    "type": "string"
                  },
                  "status": {
                    "type": "string",
                    "enum": [
                      "active",
                      "done",
                      "ignored",
                      "overridden",
                      "unprocessed"
                    ]
                  },
                  "priority": {
                    "type": "integer"
                  },
                  "labels": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  },
                  "tags": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  },
                  "content": {
                    "type": "object"
                  },
                  "metadata": {
                    "type": "object"
                  },
                  "channelLabel": {
                    "type": "string",
                    "description": "Free-text topic label (e.g. \"Health\", \"Work\"). User-editable from UI."
                  },
                  "dueDate": {
                    "type": "string",
                    "format": "date-time"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successfully updated memory",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "type": "array",
                      "items": {
                        "type": "object"
                      }
                    },
                    "gameRewards": {
                      "type": "object",
                      "description": "Present only when this PATCH triggered a per-task seed grant.",
                      "properties": {
                        "seedsAwarded": {
                          "type": "integer"
                        },
                        "walletBalance": {
                          "type": "integer"
                        }
                      }
                    },
                    "attributeDelta": {
                      "type": "object",
                      "nullable": true,
                      "description": "Always `null`. The 5-dim avatar-attribute-growth system\nthis field used to carry is retired; the key is kept\n(as a literal `null`) for wire compatibility with\nclients that still read it. For energy/chest rewards\nuse PATCH /api/v2/memory/{id} instead (this v1 endpoint\nnever returns `energy`/`chest`).\n"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad request (e.g. channelLabel not a non-empty string)."
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Memory not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "delete": {
        "summary": "Delete a memory",
        "description": "Delete a memory by ID",
        "tags": [
          "Memory"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Memory ID"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully deleted memory"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Memory not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v1/memory": {
      "get": {
        "summary": "Get memories with advanced filters",
        "description": "Get paginated list of memories for the currently logged in user.\nSupports filtering by status, type, time range, label, and keyword search.\nResults can be sorted by createdAt, updatedAt, dueDate, or priority in ascending or descending order (default: createdAt desc).\nWhen sorting by priority, ties are broken by dueDate asc, then createdAt desc.\n",
        "tags": [
          "Memory"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            },
            "description": "Page number"
          },
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 20
            },
            "description": "Items per page (clamped to 100)"
          },
          {
            "in": "query",
            "name": "status",
            "schema": {
              "type": "string",
              "enum": [
                "active",
                "done",
                "ignored",
                "overridden",
                "unprocessed"
              ]
            },
            "description": "Filter by memory status"
          },
          {
            "in": "query",
            "name": "type",
            "schema": {
              "type": "string",
              "enum": [
                "action",
                "memory",
                "fact",
                "task",
                "plan"
              ]
            },
            "description": "Filter by memory type"
          },
          {
            "in": "query",
            "name": "startDate",
            "schema": {
              "type": "string",
              "format": "date-time"
            },
            "description": "Filter by due date start (ISO 8601, filters on dueDate field)"
          },
          {
            "in": "query",
            "name": "endDate",
            "schema": {
              "type": "string",
              "format": "date-time"
            },
            "description": "Filter by due date end (ISO 8601, filters on dueDate field)"
          },
          {
            "in": "query",
            "name": "date",
            "schema": {
              "type": "string",
              "format": "date"
            },
            "description": "Filter by attribution day (user-local YYYY-MM-DD, plan_date field). Early-morning sleep tasks (due next-day before 06:00) belong to the previous day. Independent from startDate/endDate."
          },
          {
            "in": "query",
            "name": "label",
            "schema": {
              "type": "string"
            },
            "description": "Filter by a single label"
          },
          {
            "in": "query",
            "name": "keyword",
            "schema": {
              "type": "string"
            },
            "description": "Search keyword in title and content.text"
          },
          {
            "in": "query",
            "name": "sortBy",
            "schema": {
              "type": "string",
              "enum": [
                "createdAt",
                "updatedAt",
                "dueDate",
                "priority"
              ],
              "default": "createdAt"
            },
            "description": "Sort field (createdAt, updatedAt, dueDate, or priority)"
          },
          {
            "in": "query",
            "name": "sortOrder",
            "schema": {
              "type": "string",
              "enum": [
                "asc",
                "desc"
              ],
              "default": "desc"
            },
            "description": "Sort order (asc for ascending, desc for descending)"
          },
          {
            "in": "query",
            "name": "healthType",
            "schema": {
              "type": "string",
              "enum": [
                "weight",
                "diet",
                "exercise",
                "sleep",
                "other"
              ]
            },
            "description": "Filter check-in records by health type (V1.4, DEV-959/960)"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully retrieved memories",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "items": {
                          "type": "array",
                          "items": {
                            "$ref": "#/components/schemas/MemoryItem"
                          }
                        },
                        "pagination": {
                          "type": "object",
                          "properties": {
                            "page": {
                              "type": "integer"
                            },
                            "limit": {
                              "type": "integer"
                            },
                            "total": {
                              "type": "integer"
                            },
                            "totalPages": {
                              "type": "integer"
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "post": {
        "summary": "Create a new memory",
        "description": "Create a new memory record",
        "tags": [
          "Memory"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "channelLabel",
                  "refId",
                  "type",
                  "title",
                  "content",
                  "priority"
                ],
                "properties": {
                  "channelLabel": {
                    "type": "string"
                  },
                  "refId": {
                    "type": "string"
                  },
                  "type": {
                    "type": "string",
                    "enum": [
                      "action",
                      "memory",
                      "fact",
                      "task",
                      "plan"
                    ]
                  },
                  "title": {
                    "type": "string"
                  },
                  "content": {
                    "type": "object"
                  },
                  "priority": {
                    "type": "integer"
                  },
                  "status": {
                    "type": "string",
                    "enum": [
                      "active",
                      "done",
                      "ignored",
                      "overridden",
                      "unprocessed"
                    ]
                  },
                  "labels": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  },
                  "tags": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  },
                  "description": {
                    "type": "string"
                  },
                  "dueDate": {
                    "type": "string",
                    "format": "date-time"
                  },
                  "metadata": {
                    "type": "object"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successfully created memory"
          },
          "400": {
            "description": "Bad request"
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v2/analyses/daily-insight": {
      "get": {
        "summary": "当天饮食的 AI 点评(Daily Insight，Pro）",
        "description": "Analysis 页 `Daily Insight` 区块。生成在 agent-worker（每天用户本地 20:00），\nbff 只读。\n\n**Pro 门禁**：免费用户返 **402 + `error: \"UPGRADE_REQUIRED\"`**，\n`details.feature` 为 `insight.daily`。判别器是 `error` 字段（402 一码两义，\n见 `docs/PAYWALL_CLIENT_API.md`）。\n\n⚠️ 同页的 `Today's Intake`（`GET /api/v2/daily-plan`）**不卡**，只有这一条卡。\n\nPro 用户当天还没生成时返 200、`content: null` —— 客户端据此区分「今天还没生成」\n与「没付费」（后者是 402）。\n\n`date` 是用户本地日 `YYYY-MM-DD`，由客户端传，服务端信任不校验时区。\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "date",
            "required": true,
            "schema": {
              "type": "string",
              "example": "2026-09-23"
            },
            "description": "用户本地日 `YYYY-MM-DD`"
          }
        ],
        "responses": {
          "200": {
            "description": "点评状态。content 为 null 表示当天还没生成完成。",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "date": {
                          "type": "string",
                          "example": "2026-09-23"
                        },
                        "content": {
                          "type": "string",
                          "nullable": true,
                          "example": "You haven't logged any meals today…"
                        },
                        "metadata": {
                          "type": "object",
                          "nullable": true
                        },
                        "completedAt": {
                          "type": "string",
                          "nullable": true
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "date 缺失或不是合法日历日"
          },
          "401": {
            "description": "Unauthorized"
          },
          "402": {
            "description": "需要 Pro，error 为 UPGRADE_REQUIRED"
          }
        }
      }
    },
    "/api/v2/analyses/quota": {
      "get": {
        "summary": "各类分析今天还能用几次",
        "description": "响应形状是 `{ isPro, exempt, <type>: { limit, used, remaining } }` ——\n用户级的两个标志在顶层，每个受限的分析类型各一份。目前只有 `diet`\n（卡路里识别），**将来加类型时响应体自动多一个键，客户端不用改解析**。\n\n**Pro 与首日用户免计数**（`exempt: true`，此时各类型的 `used` 恒为 0，\n别拿 `remaining` 去显示「还剩 N 次」）。\n\n`date` 是**用户本地日**，由客户端传。服务端信任它、不做时区校验 ——\n改时区刷额度的成本远高于收益，而校验会误伤真实跨时区用户。\n\n只读，不消耗额度。\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "date",
            "required": true,
            "schema": {
              "type": "string",
              "example": "2026-09-19"
            },
            "description": "用户本地日 `YYYY-MM-DD`"
          }
        ],
        "responses": {
          "200": {
            "description": "各类分析的配额状态",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "isPro": {
                          "type": "boolean",
                          "example": false
                        },
                        "exempt": {
                          "type": "boolean",
                          "example": false
                        },
                        "diet": {
                          "type": "object",
                          "properties": {
                            "limit": {
                              "type": "integer",
                              "example": 3
                            },
                            "used": {
                              "type": "integer",
                              "example": 1
                            },
                            "remaining": {
                              "type": "integer",
                              "example": 2
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "date 缺失或不是合法日历日"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      },
      "post": {
        "summary": "新增一次卡路里识别（登记 + 判定是否放行）",
        "description": "免费用户每天 3 次。**Pro 与首日用户免计数直接放行**（`exempt: true`）。\n\n超限返 **402 + `error: \"UPGRADE_REQUIRED\"`**，`details.feature` 为\n`health.diet_analysis`。\n\n⚠️ **不要期待 `QUOTA_EXCEEDED` 之类的错误码** —— 客户端按\n`status === 402 && error === 'UPGRADE_REQUIRED'` 判别（契约见\n`docs/PAYWALL_CLIENT_API.md §3`，402 一码两义）。返别的值客户端会\nfail-open 放行，不崩，但配额形同虚设。\n\n`date` 是用户本地日（`YYYY-MM-DD`），服务端信任不校验时区（见 quota 端点）。\n⚠️ 字段名与 `GET /quota` 的 query 参数一致，都叫 `date`。\n\n不做退还：识别失败不退额度。\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "type",
                  "date"
                ],
                "properties": {
                  "type": {
                    "type": "string",
                    "enum": [
                      "diet"
                    ],
                    "description": "哪一类分析。目前只有 `diet`（卡路里识别）"
                  },
                  "date": {
                    "type": "string",
                    "example": "2026-09-19",
                    "description": "用户本地日 `YYYY-MM-DD`"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "放行，响应体是消耗之后的配额状态"
          },
          "400": {
            "description": "type / date 缺失或不合法"
          },
          "401": {
            "description": "Unauthorized"
          },
          "402": {
            "description": "额度已用尽，error 为 UPGRADE_REQUIRED"
          }
        }
      }
    },
    "/api/v2/avatar/dye": {
      "post": {
        "summary": "Dye avatar slot or switch active slot",
        "description": "Available to every user (5 slots, no level requirement). With `color` →\ndye the slot (first dye free, then 100 seeds); without `color` → switch\nthe active slot for free. Changing the displayed color nulls the stored\nimageUrl (client re-uploads).\n",
        "tags": [
          "Game",
          "User",
          "Avatar",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "slot"
                ],
                "properties": {
                  "slot": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "0-based slot index (0 ≤ slot < dyeState.unlockedSlotCount)"
                  },
                  "color": {
                    "type": "string",
                    "pattern": "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$",
                    "description": "Hex color to dye the slot; omit to just switch the active slot (free)"
                  }
                }
              },
              "examples": {
                "dye": {
                  "summary": "Dye slot 0 (first free, then 100 seeds)",
                  "value": {
                    "slot": 0,
                    "color": "#ff0000"
                  }
                },
                "switch": {
                  "summary": "Switch active color to slot 1 (free)",
                  "value": {
                    "slot": 1
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Dye/switch applied; returns the updated dye state",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "dyeState": {
                          "type": "object",
                          "properties": {
                            "unlocked": {
                              "type": "boolean"
                            },
                            "unlockedSlotCount": {
                              "type": "integer",
                              "example": 1
                            },
                            "slots": {
                              "type": "array",
                              "items": {
                                "type": "string",
                                "nullable": true
                              },
                              "example": [
                                "#ff0000"
                              ]
                            },
                            "activeSlot": {
                              "type": "integer",
                              "example": 0
                            },
                            "freeDyeAvailable": {
                              "type": "boolean",
                              "example": false
                            },
                            "dyeCost": {
                              "type": "integer",
                              "example": 100
                            }
                          }
                        },
                        "balance": {
                          "type": "integer",
                          "nullable": true,
                          "description": "Wallet balance after a paid dye; null on free actions",
                          "example": 400
                        },
                        "charged": {
                          "type": "integer",
                          "description": "Seeds charged this call (0 or 100)",
                          "example": 0
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "VALIDATION_ERROR (bad slot/color) or DYE_SLOT_EMPTY (switching to an empty slot)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "402": {
            "description": "PAYMENT_REQUIRED — insufficient seeds for a paid dye",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "403": {
            "description": "DYE_SLOT_LOCKED — slot index out of range (0 ≤ slot < 5)",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "User avatar not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "delete": {
        "summary": "Restore avatar dye to factory default",
        "description": "\"恢复默认\" (DEV-1203). Available to every user. Resets the avatar body\ncolor to the shape's factory color (square #BDFF78 / circle #FFB531 /\ntriangle #8E8DF6) and clears the colors stored in the slots; slot 0\nbecomes the factory color and active. The lifetime free-dye flag is\npreserved and no seeds are ever charged. Changing the displayed color\nnulls the stored imageUrl (client re-uploads).\n",
        "tags": [
          "Game",
          "User",
          "Avatar",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Restored; returns the updated dye state",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "dyeState": {
                          "type": "object",
                          "properties": {
                            "unlocked": {
                              "type": "boolean",
                              "example": true
                            },
                            "unlockedSlotCount": {
                              "type": "integer",
                              "example": 3
                            },
                            "slots": {
                              "type": "array",
                              "items": {
                                "type": "string",
                                "nullable": true
                              },
                              "example": [
                                "#BDFF78",
                                null,
                                null
                              ]
                            },
                            "activeSlot": {
                              "type": "integer",
                              "example": 0
                            },
                            "freeDyeAvailable": {
                              "type": "boolean",
                              "example": false
                            },
                            "dyeCost": {
                              "type": "integer",
                              "example": 100
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "User avatar not found",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v2/avatar/roster": {
      "get": {
        "summary": "List the user's characters (owned + locked)",
        "description": "One row per shape, always in the same order (square, circle, triangle)\nso the client's pager dots stay stable. Owned rows carry that\ncharacter's own name / color / outfit / `dyeState` — colors are **not**\nshared between characters. Locked rows carry `unlockCost` only; buy them\nwith `POST /api/v2/avatar/unlock`. Exactly one owned row has\n`active: true` (the character the user is currently paired with).\n",
        "tags": [
          "Game",
          "User",
          "Avatar",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "The roster",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "shape": {
                            "type": "string",
                            "enum": [
                              "square",
                              "circle",
                              "triangle"
                            ]
                          },
                          "avatarId": {
                            "type": "integer",
                            "nullable": true
                          },
                          "owned": {
                            "type": "boolean"
                          },
                          "active": {
                            "type": "boolean"
                          },
                          "userAvatarId": {
                            "type": "integer",
                            "nullable": true
                          },
                          "name": {
                            "type": "string",
                            "nullable": true
                          },
                          "color": {
                            "type": "string",
                            "nullable": true,
                            "example": "#FFB531"
                          },
                          "imageUrl": {
                            "type": "string",
                            "nullable": true
                          },
                          "outfit": {
                            "type": "object",
                            "nullable": true
                          },
                          "dyeState": {
                            "type": "object",
                            "nullable": true
                          },
                          "unlockCost": {
                            "type": "integer",
                            "example": 500
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v2/avatar": {
      "post": {
        "summary": "create user avatar",
        "description": "create user avatar by paramater",
        "tags": [
          "Game",
          "User",
          "V2"
        ],
        "Security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "shape",
                  "color",
                  "name"
                ],
                "properties": {
                  "shape": {
                    "type": "string",
                    "example": "circle",
                    "description": "avatar shape",
                    "enum": [
                      "circle",
                      "square",
                      "triangle"
                    ]
                  },
                  "color": {
                    "type": "string",
                    "example": "#RRGGBB",
                    "description": "Hexadecimal color representation"
                  },
                  "name": {
                    "type": "string",
                    "example": "HeroAvatar",
                    "description": "The name of user's avatar"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The result of creating",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Avatar"
                }
              }
            }
          },
          "400": {
            "description": "Invalid request",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "404": {
            "description": "An avatar with shape could not be found.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "INTERNAL_ERROR",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "patch": {
        "summary": "Update user avatar",
        "description": "Update the name or outfit of the **currently active** avatar, and/or\nswitch which owned character is active via `shape`. Switching between\nowned characters is free and unlimited; a shape the user has not\nunlocked returns 403 `AVATAR_NOT_OWNED` (buy it with\n`POST /api/v2/avatar/unlock` first).\n",
        "tags": [
          "Game",
          "User",
          "V2"
        ],
        "Security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string",
                    "description": "New name for the avatar"
                  },
                  "shape": {
                    "type": "string",
                    "enum": [
                      "circle",
                      "square",
                      "triangle"
                    ],
                    "description": "Switch the active character to this owned shape (free)"
                  },
                  "outfit": {
                    "type": "object",
                    "description": "New outfit configuration"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successfully updated",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "type": "object"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error"
          },
          "403": {
            "description": "AVATAR_NOT_OWNED — the shape has not been unlocked yet"
          },
          "404": {
            "description": "User avatar not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "get": {
        "summary": "Get user avatar",
        "description": "Get the current user's avatar. Includes `energyState` (V1.4 燃脂力:\nenergy mapped to level per the `energy.levels` config; display only,\nthe backend does NOT gate on it). The 5-dim attributes\nremain in the response (deprecated).\n",
        "tags": [
          "Game",
          "User",
          "V2"
        ],
        "Security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully retrieved",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "$ref": "#/components/schemas/UserAvatar"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "User avatar not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v2/avatar/unlock": {
      "post": {
        "summary": "Unlock a new character with seeds",
        "description": "Buys the character for `unlockCost` seeds (500) and adds it to the\nroster. Unlocking is **not** switching: the active character is left\nuntouched and the client switches with `PATCH /api/v2/avatar` once the\nuser taps Save (only an account with no active character at all gets\nthe new one activated on the spot). The new character starts with its\nshape's factory color, its own empty dye slots and its own free-dye\nallowance; wardrobe items and the seed balance stay global, and the\nburn-level EXP carries over from the previous character. Re-buying an\nowned shape is refused (409) rather than silently charged.\n",
        "tags": [
          "Game",
          "User",
          "Avatar",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "shape"
                ],
                "properties": {
                  "shape": {
                    "type": "string",
                    "enum": [
                      "circle",
                      "square",
                      "triangle"
                    ]
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Unlocked; returns the (unchanged) active avatar and the wallet balance",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "avatar": {
                          "$ref": "#/components/schemas/UserAvatar",
                          "description": "The still-active character — unlocking does not switch"
                        },
                        "balance": {
                          "type": "integer",
                          "description": "Wallet balance after the purchase",
                          "example": 60
                        },
                        "charged": {
                          "type": "integer",
                          "example": 500
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "VALIDATION_ERROR (bad shape) or AVATAR_SHAPE_UNAVAILABLE (no template configured)"
          },
          "401": {
            "description": "Unauthorized"
          },
          "402": {
            "description": "PAYMENT_REQUIRED — insufficient seeds"
          },
          "409": {
            "description": "AVATAR_ALREADY_OWNED — the user already owns this shape"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v2/checkin/streak": {
      "get": {
        "summary": "Consecutive check-in days (饮食打卡)",
        "description": "连续打卡天数。打卡 = 当天完成了饮食 memory（healthType=diet，含饮食任务与\n快捷记餐）。按用户时区本地日计算；今天还没打卡时返回截至昨天的连续数，\n并以 todayChecked=false 标记。\n\nDEV-1393：口径自「任意 memory 完成」收窄至饮食 —— GLP 用药打卡同样是一条\n完成的 memory，旧口径下会点亮首页的饮食火苗。7 日登录签到不走这里。\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "currentStreak": {
                          "type": "integer",
                          "example": 5,
                          "description": "连续打卡天数"
                        },
                        "todayChecked": {
                          "type": "boolean",
                          "example": false,
                          "description": "今天是否已打卡"
                        },
                        "lastCheckinDate": {
                          "type": "string",
                          "format": "date",
                          "nullable": true,
                          "example": "2026-06-15",
                          "description": "最近打卡本地日；无记录为 null"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v2/chest/{id}": {
      "patch": {
        "summary": "Open a chest",
        "description": "Opens the given unopened chest, rolling its fragment rewards and\ntransitioning it to `opened`. Idempotent for an already-opened chest\n(returns the same rewards).\nIdempotent: re-opening an already-opened chest returns 200 with the same stored rewards. There is no separate 'already opened' or 'locked' error.\n",
        "tags": [
          "Game",
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            },
            "description": "Chest id"
          }
        ],
        "responses": {
          "200": {
            "description": "The opened chest with rewards",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "$ref": "#/components/schemas/Chest"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid chest id",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Chest not found, OR the chest is not owned by the caller (not-owned is indistinguishable from not-found)."
          }
        }
      }
    },
    "/api/v2/chest": {
      "get": {
        "summary": "List the current user's chests",
        "description": "By default returns the user's unopened (claimable) chests plus counts.\nPass `all=true` for the full paginated history (incl. opened).\n",
        "tags": [
          "Game",
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "all",
            "schema": {
              "type": "boolean",
              "default": false
            },
            "description": "Include opened chests and paginate the full history."
          },
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            }
          },
          {
            "in": "query",
            "name": "pageSize",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 20
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Chest list",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "chests": {
                          "type": "array",
                          "items": {
                            "$ref": "#/components/schemas/Chest"
                          }
                        },
                        "unopenedCount": {
                          "type": "integer",
                          "example": 2
                        },
                        "total": {
                          "type": "integer",
                          "example": 2
                        },
                        "pagination": {
                          "nullable": true,
                          "type": "object",
                          "properties": {
                            "page": {
                              "type": "integer"
                            },
                            "pageSize": {
                              "type": "integer"
                            },
                            "total": {
                              "type": "integer"
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      },
      "patch": {
        "summary": "Open multiple chests",
        "description": "Batch-opens the given unopened chests, rolling each one's fragment\nrewards. Best-effort and idempotent: an already-opened chest is returned\nwith its existing rewards, and ids that aren't found (or aren't owned by\nthe caller) are returned in `notFound` rather than failing the whole\nrequest. To open a single chest you can also use\n`PATCH /api/v2/chest/{id}`.\n",
        "tags": [
          "Game",
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "chestIds"
                ],
                "properties": {
                  "chestIds": {
                    "type": "array",
                    "minItems": 1,
                    "maxItems": 100,
                    "items": {
                      "type": "integer"
                    },
                    "description": "Ids of the chests to open."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The opened chests with rewards",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "chests": {
                          "type": "array",
                          "items": {
                            "$ref": "#/components/schemas/Chest"
                          }
                        },
                        "openedCount": {
                          "type": "integer",
                          "example": 2
                        },
                        "notFound": {
                          "type": "array",
                          "items": {
                            "type": "integer"
                          },
                          "description": "Requested ids that were not found / not owned."
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid or empty chestIds",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v2/contexts/calendar": {
      "post": {
        "summary": "Upload device calendar events to contexts",
        "description": "Ingest device (Expo) calendar events into app_user_contexts. Aligned\nwith POST /api/v2/contexts/health: verifySession → strict Zod → per-event\nupsert (no cron/queue). Each event is upserted on the dedup key\n(channelLabel='calendar', refId='event:{id}'); re-uploading the same\nevent id updates it in place. startDate/endDate are offset-bearing ISO\nstrings in the device's local time and are sliced directly (not\nDate-parsed) to build a human-readable `content`, so the result is\nindependent of userProfile.timezone. Rows land with status='active' and\nare injected into agent context. Empty/omitted `events` is a no-op.\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "additionalProperties": false,
                "properties": {
                  "events": {
                    "type": "array",
                    "maxItems": 500,
                    "description": "Device calendar events (unknown fields rejected).",
                    "items": {
                      "type": "object",
                      "required": [
                        "id",
                        "title",
                        "startDate",
                        "endDate",
                        "allDay"
                      ],
                      "properties": {
                        "id": {
                          "type": "string",
                          "minLength": 1,
                          "maxLength": 256,
                          "description": "Expo event id; part of the dedup key.",
                          "example": "ABCD-1234"
                        },
                        "title": {
                          "type": "string",
                          "maxLength": 500,
                          "description": "Event title; empty string allowed (backend falls back to \"(无标题)\").",
                          "example": "Dentist appointment"
                        },
                        "startDate": {
                          "type": "string",
                          "format": "date-time",
                          "description": "Offset-bearing ISO (device local time).",
                          "example": "2026-07-15T09:00:00+08:00"
                        },
                        "endDate": {
                          "type": "string",
                          "format": "date-time",
                          "description": "Offset-bearing ISO (device local time).",
                          "example": "2026-07-15T10:00:00+08:00"
                        },
                        "allDay": {
                          "type": "boolean",
                          "example": false
                        },
                        "calendarId": {
                          "type": "string",
                          "minLength": 1,
                          "maxLength": 256,
                          "description": "Owning calendar id; stored in metadata only, not part of dedup."
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Upsert result count",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "eventsUpserted": {
                          "type": "integer",
                          "description": "Number of events inserted or updated.",
                          "example": 12
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal error"
          }
        }
      }
    },
    "/api/v2/contexts/health": {
      "post": {
        "summary": "Ingest Apple Health / Google Health Connect data",
        "description": "Platform-neutral health sync. Fans out to weight_record (silent,\nsource-tagged, deduped by externalId), fill-only profile\n(height/gender/birthdate), and a rolling per-platform health summary in\napp_user_contexts. `daily` aggregates are used to build the summary and\nare NOT persisted.\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "source"
                ],
                "properties": {
                  "source": {
                    "type": "string",
                    "enum": [
                      "apple-health",
                      "health-connect"
                    ]
                  },
                  "profile": {
                    "type": "object",
                    "properties": {
                      "heightCm": {
                        "type": "number"
                      },
                      "gender": {
                        "type": "string",
                        "enum": [
                          "male",
                          "female",
                          "them",
                          "prefer_not_to_say"
                        ]
                      },
                      "birthdate": {
                        "type": "string",
                        "example": "1992-10-17"
                      }
                    }
                  },
                  "weights": {
                    "type": "array",
                    "items": {
                      "type": "object",
                      "required": [
                        "recordedAt",
                        "weightG",
                        "externalId"
                      ],
                      "properties": {
                        "recordedAt": {
                          "type": "string",
                          "format": "date-time"
                        },
                        "weightG": {
                          "type": "integer"
                        },
                        "externalId": {
                          "type": "string"
                        }
                      }
                    }
                  },
                  "daily": {
                    "type": "array",
                    "items": {
                      "type": "object",
                      "required": [
                        "localDate"
                      ],
                      "properties": {
                        "localDate": {
                          "type": "string",
                          "example": "2026-06-22"
                        },
                        "steps": {
                          "type": "integer"
                        },
                        "sleepMin": {
                          "type": "integer"
                        },
                        "workouts": {
                          "type": "integer"
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Sync result counts"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal error"
          }
        }
      }
    },
    "/api/v2/daily-plan": {
      "get": {
        "summary": "今天的目标与已摄入（卡路里 + 蛋白）",
        "description": "首页那两条指标条的唯一数据源：**目标、已摄入、达标态**一次给全。\n**纯读、无副作用**，每次打开首页都可以调。\n\n写侧是 agent-worker 的每日生成与 onboarding 认领；本端点只读。\n\n⚠️ **不要再按天缓存**（V1.7 起）——`intake` 会随用户每次打卡变化。\n此前只返预算时缓存是安全的，现在不是了。\n\nGLP 模式下首页主指标是**蛋白完成度**（`proteinTarget` / `intake.protein`），\n卡路里降为副指标；普通模式 `proteinTarget` 为 `null`，只渲染卡路里那条。\n\n⚠️ **`dailyBudget` 可能是 `null`**，而且这不是错误：worker 还没跑到这个\n用户，或者生成时缺关键资料（性别 / 出生日期 / 身高 / 体重 / 活动量）只写了\nfallback。首页应当照常渲染并显示「待完善」之类，引导用户补齐资料。\n\n⚠️ **任务列表不在这里** —— 仍从 `GET /api/v2/memory` 取。想区分「还在生成」\n与「今天就是没有」，用 `GET /api/v2/taskgen-status`。\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "今天的预算（查不到时 dailyBudget 为 null，仍返 200）",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "planDate": {
                          "type": "string",
                          "example": "2026-08-17",
                          "description": "用户本地日"
                        },
                        "dailyBudget": {
                          "type": "integer",
                          "nullable": true,
                          "example": 2160,
                          "description": "kcal。null = 当天还没有预算（不是错误）"
                        },
                        "budgetMeta": {
                          "type": "object",
                          "nullable": true,
                          "description": "预算依据（bmr / tdee / defaulted 等），结构由 worker 决定"
                        },
                        "proteinTarget": {
                          "type": "integer",
                          "nullable": true,
                          "example": 98,
                          "description": "当日蛋白目标（g）。**只有 GLP 模式才有**（V1.7）——\n普通模式为 `null`，首页据此决定渲不渲染蛋白条。\n"
                        },
                        "intake": {
                          "type": "object",
                          "description": "今天已摄入。只统计**分析已完成**的饮食打卡：还在识别中的\n（pending / processing）与被判定不是食物的（rejected）都不计。\n",
                          "properties": {
                            "calories": {
                              "type": "integer",
                              "example": 1180
                            },
                            "protein": {
                              "type": "integer",
                              "example": 68
                            },
                            "analyzedCount": {
                              "type": "integer",
                              "description": "已完成分析的打卡条数。0 时上面两个是 0 而不是「无数据」，客户端要能区分"
                            }
                          }
                        },
                        "status": {
                          "type": "object",
                          "description": "达标态。**卡路里两个模式同一套口径**：吃到预算 80% 算达标、\n超过 110% 算超标。蛋白只有 GLP 模式有，且是**单向**判定 ——\n≥ 目标即 `met`，吃超不算超标。目标缺失时对应字段为 `null`。\n",
                          "properties": {
                            "calories": {
                              "type": "string",
                              "nullable": true,
                              "enum": [
                                "under",
                                "on_track",
                                "over"
                              ]
                            },
                            "protein": {
                              "type": "string",
                              "nullable": true,
                              "enum": [
                                "under",
                                "met"
                              ]
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v2/daily-targets/recommended-change": {
      "post": {
        "summary": "Answer the \"recommended target changed\" prompt",
        "description": "`use` switches the user back to Recommended (follows future changes\nsilently, effective tomorrow). `keep` keeps the custom value and\nre-arms the prompt for the next change. No-op when nothing is pending.\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "action"
                ],
                "properties": {
                  "action": {
                    "type": "string",
                    "enum": [
                      "use",
                      "keep"
                    ]
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Daily targets after the action",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "$ref": "#/components/schemas/DailyTargets"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v2/daily-targets": {
      "get": {
        "summary": "Get the user's daily targets (calorie mode, meals, eating hours)",
        "description": "Data for the app's \"Daily targets\" settings page plus the pending\n\"recommended target changed\" prompt for the home screen.\n`recommendedCalories` is null when the budget is not computable yet\n(incomplete profile). `safeMinimum` is always present.\n`recommendedChange` is non-null only for Custom users whose\nrecommended value differs from the one they last saw.\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Daily targets",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "$ref": "#/components/schemas/DailyTargets"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      },
      "put": {
        "summary": "Save the user's daily targets (takes effect tomorrow)",
        "description": "Replaces calorie mode, meals per day and eating hours in one call.\nToday's calorie budget and meal tasks are NOT changed — the worker\npicks the new settings up when it generates tomorrow's plan.\nReturns 400 `BELOW_SAFE_MINIMUM` (with `details.safeMinimum`) when a\ncustom value is below max(BMR, 1200 female / 1500 male).\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "calorieMode",
                  "mealsPerDay",
                  "firstMealTime",
                  "lastMealTime"
                ],
                "properties": {
                  "calorieMode": {
                    "type": "string",
                    "enum": [
                      "recommended",
                      "custom"
                    ]
                  },
                  "customCalories": {
                    "type": "integer",
                    "nullable": true,
                    "maximum": 10000,
                    "description": "Required when calorieMode is custom"
                  },
                  "mealsPerDay": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 5
                  },
                  "firstMealTime": {
                    "type": "string",
                    "example": "07:00"
                  },
                  "lastMealTime": {
                    "type": "string",
                    "example": "19:00",
                    "description": "Must be later than firstMealTime"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated daily targets",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "$ref": "#/components/schemas/DailyTargets"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error or BELOW_SAFE_MINIMUM"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v2/feedback/uploads": {
      "post": {
        "summary": "Issue a signed GCS upload URL for a feedback attachment",
        "description": "Mints a short-lived signed PUT URL (Google Cloud Storage v4 signing)\nfor a feedback attachment. The client uploads the file bytes directly\nto `uploadUrl` (bypassing the function body size cap); the returned\n`objectUrl` is then included in the feedback/message `attachments`.\nObject size/contentType are re-verified authoritatively against the\nreal object when the feedback/message is later created.\n",
        "tags": [
          "Feedback",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "kind",
                  "contentType"
                ],
                "properties": {
                  "kind": {
                    "type": "string",
                    "enum": [
                      "image",
                      "video",
                      "log"
                    ]
                  },
                  "contentType": {
                    "type": "string"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Signed upload URL issued",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "uploadUrl": {
                          "type": "string"
                        },
                        "objectUrl": {
                          "type": "string"
                        },
                        "contentType": {
                          "type": "string"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad request / disallowed kind or contentType"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v2/glp/profile": {
      "get": {
        "summary": "当前用户的 GLP-1 模式档案",
        "description": "设置页与首页都读它。**从未答过 GLP 那一屏时返回 `null`**（不是错误）——\n增重目标的用户根本不会看到那一屏。\n\n`enabled=false` + `declined=true` = 用户明确答过「Not right now」；\n`enabled=false` + `declined=false` = 开过又关了，采集项仍然留着供回填。\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "GLP 档案（没有则 data 为 null）"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      },
      "patch": {
        "summary": "开启 / 关闭 GLP-1 模式，或改单项设置",
        "description": "请求体有两种形状，靠**有没有 `enabled` 键**区分：\n\n- **带 `enabled: true`** —— 开启，必须给药物、用药时长与 consent 文案\n  版本。`dose` / `shotDay` / `doseTime` 三项**都可以缺省或传 null** ——\n  采集侧那三屏各自有「Not sure yet」（D-06 / D-22）。缺 `shotDay` 的\n  注射用户拿不到首页用药卡与用药提醒（状态算不出来），补选后自动恢复。\n  **consent 时间戳由服务端盖**，客户端只传版本号；每次 off→on 都算一次\n  新的同意（二次开启也要重签）。\n- **带 `enabled: false`** —— 用户答「Not right now」或关掉模式。\n  **不删任何数据**，采集项与用药记录全部留着供回填。\n- **不带 `enabled`** —— 改单项（设置页允许单独点某一行改）。\n  改药时必须同时给 `route`，用来校验 slug 属于哪条链。\n\n剂量一律是「数字 + 单位」的字符串，例如 `\"7.5 mg\"` ——\n纯数字不通过（5 mg 与 5 units 差十倍以上）。落库拆成两列。\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "更新后的 GLP 档案"
          },
          "400": {
            "description": "校验失败"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "改单项时档案还不存在（先开启一次）"
          }
        }
      }
    },
    "/api/v2/health-profile": {
      "get": {
        "summary": "Get the current user's health profile",
        "description": "Returns the user's health profile (height / goalWeight / goal /\nbarrier / sleep & wake target times / mealFrequency /\nexerciseComfortLevel). Returns null data when no profile exists yet.\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Health profile (or null)",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "nullable": true,
                      "$ref": "#/components/schemas/HealthProfile"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      },
      "patch": {
        "summary": "Update the current user's health profile",
        "description": "Partial update of the health-profile onboarding fields. Creates the\nrow if absent (upsert). gender/birthdate are edited via\n/api/v2/profile. The body is strict: unknown keys are rejected with\n400. Enum/format constraints are enforced per field (see properties).\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "height": {
                    "type": "number",
                    "description": "Height in cm",
                    "example": 175
                  },
                  "goalWeight": {
                    "type": "integer",
                    "description": "Goal weight in grams (integer)",
                    "example": 68500
                  },
                  "goal": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "lose_weight",
                      "maintain",
                      "gain_weight"
                    ],
                    "description": "Q1 primary goal (single-select)"
                  },
                  "activityLevel": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "sedentary",
                      "lightly_active",
                      "active",
                      "very_active"
                    ],
                    "description": "V2 Q 日常活动量（单选）。worker 预算公式必需输入"
                  },
                  "dietPreference": {
                    "type": "array",
                    "nullable": true,
                    "items": {
                      "type": "string",
                      "minLength": 1,
                      "maxLength": 40
                    },
                    "maxItems": 20,
                    "description": "V2 Q 饮食风格（多选 + 自定义自由文本，DEV-1290）。预设值 balanced/high_protein/low_carb/keto/paleo/mediterranean/pescatarian/vegetarian/vegan 与自由文本混存"
                  },
                  "allergies": {
                    "type": "array",
                    "nullable": true,
                    "items": {
                      "type": "string"
                    },
                    "description": "V2 Q 忌口。8 个预设 slug（dairy/eggs/gluten/peanuts/tree_nuts/fish/shellfish/soy）与自由文本混存，单条 ≤40 字符、最多 20 条"
                  },
                  "mealsPerDay": {
                    "type": "integer",
                    "nullable": true,
                    "minimum": 1,
                    "maximum": 5,
                    "description": "V2 Q 每日餐数"
                  },
                  "mealTimes": {
                    "type": "array",
                    "nullable": true,
                    "items": {
                      "type": "string"
                    },
                    "example": [
                      "07:00",
                      "19:00"
                    ],
                    "description": "V2 Q 用餐时间点，\"HH:MM\" 用户本地，按用餐顺序排列（不是时钟顺序，跨午夜合法）。当前恒 2 项 = [首餐, 末餐]，最多 5 项"
                  },
                  "eatingChallenges": {
                    "type": "array",
                    "nullable": true,
                    "items": {
                      "type": "string",
                      "enum": [
                        "cravings_snacking",
                        "too_busy_to_cook",
                        "eating_out_a_lot",
                        "portion_control",
                        "emotional_eating",
                        "sweet_tooth"
                      ]
                    },
                    "description": "V2 Q 饮食困难（多选）"
                  },
                  "barrier": {
                    "type": "array",
                    "nullable": true,
                    "items": {
                      "type": "string",
                      "enum": [
                        "cravings",
                        "low_motivation",
                        "no_plan",
                        "bad_habits"
                      ]
                    },
                    "description": "DEPRECATED (V2 不再采集) — Q2 biggest challenge (multi-select)"
                  },
                  "sleepTargetTime": {
                    "type": "string",
                    "nullable": true,
                    "example": "23:00",
                    "description": "DEPRECATED (V2 不再采集) — Q3 target bedtime, 24h HH:MM local wall-clock"
                  },
                  "wakeTargetTime": {
                    "type": "string",
                    "nullable": true,
                    "example": "07:00",
                    "description": "DEPRECATED (V2 不再采集) — Q3 target wake-up time, 24h HH:MM"
                  },
                  "mealFrequency": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "one_to_two",
                      "three",
                      "four_plus",
                      "varies"
                    ],
                    "description": "DEPRECATED (V2 不再采集) — Q4 meal frequency (single-select)"
                  },
                  "exerciseComfortLevel": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "beginner",
                      "light",
                      "moderate",
                      "active"
                    ],
                    "description": "DEPRECATED (V2 不再采集) — Q5 exercise comfort (legacy; mapped forward to exerciseFrequency)"
                  },
                  "exerciseFrequency": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "almost_never",
                      "one_to_two",
                      "three_to_four",
                      "five_plus"
                    ],
                    "description": "DEPRECATED (V2 不再采集) — Q5 exercise frequency (DEV-1145; preferred over exerciseComfortLevel)"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated health profile",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "$ref": "#/components/schemas/HealthProfile"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "delete": {
        "summary": "Delete the current user's health profile",
        "description": "Hard-deletes the current user's health-profile row (onboarding answers\n+ height / goalWeight / weight). Idempotent: succeeds whether or not a\nrow existed; the response's `deleted` flag reports which. Removes only\napp_user_health_profile — weight records / analyses are left intact.\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Deletion result",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "deleted": {
                          "type": "boolean",
                          "description": "true if a row existed and was removed; false if none existed"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v2/memory/{id}/health-checkin": {
      "post": {
        "summary": "提交健康打卡内容（与任务完成解耦）",
        "description": "提交 weight / diet / exercise 打卡内容。`analyze:true` 走服务端同步分析\n（可返回 rejected=非食物）；`analyze:false`(默认) 直接入库客户端结果。\n不改任务状态——内容无误后再 PATCH status=done。任务已 done 返回 409。\n",
        "tags": [
          "Memory",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "打卡已记录 / 已分析 / 被拒"
          },
          "400": {
            "description": "校验失败"
          },
          "401": {
            "description": "未授权"
          },
          "404": {
            "description": "不存在或非本人"
          },
          "409": {
            "description": "任务已完成"
          }
        }
      }
    },
    "/api/v2/memory/{id}": {
      "get": {
        "summary": "Get a single memory by ID (v2)",
        "description": "Identical to `GET /api/v1/memory/{id}`. Returns the full memory row,\nincluding `healthType` and (for diet/exercise tasks) the embedded\n`analysis` check-in record.\n",
        "tags": [
          "Memory",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Memory ID"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully retrieved memory",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "$ref": "#/components/schemas/MemoryItem"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Memory not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "patch": {
        "summary": "Update / complete a memory (v2 — energy + chest)",
        "description": "Update memory fields. `status=\"done\"` is the switch that triggers\ncompletion side-effects. The reward path is energy + graded chest\n(DEV-942/943): the response may include `energy` and `chest`.\n`attributeDelta` is always the literal `null` (5-dim attribute growth\nis retired; the key is kept for wire compatibility). 完成与打卡已拆分——打卡走 POST …/health-checkin。\n",
        "tags": [
          "Memory",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Memory ID"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "title": {
                    "type": "string"
                  },
                  "description": {
                    "type": "string"
                  },
                  "status": {
                    "type": "string",
                    "enum": [
                      "active",
                      "done",
                      "ignored",
                      "overridden",
                      "unprocessed"
                    ]
                  },
                  "priority": {
                    "type": "integer"
                  },
                  "labels": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  },
                  "tags": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  },
                  "content": {
                    "type": "object"
                  },
                  "metadata": {
                    "type": "object"
                  },
                  "channelLabel": {
                    "type": "string",
                    "description": "Free-text topic label (e.g. \"Health\", \"Work\"). User-editable from UI."
                  },
                  "dueDate": {
                    "type": "string",
                    "format": "date-time"
                  },
                  "healthType": {
                    "type": "string",
                    "enum": [
                      "weight",
                      "diet",
                      "exercise",
                      "sleep",
                      "other"
                    ],
                    "description": "健康域分类（V1.4）。**省略 = 保持原值不动**;传了就改成传的值。\n非法值（含 `null`，该列 NOT NULL）返 400 而不是静默忽略。\n⚠️ 改 healthType 会按现行 dueDate **重推导归属日 `plan_date`**\n（`sleep` 取 dueDate−6h 的本地日期），所以重分类不会留下脏归属日。\n"
                  },
                  "grade": {
                    "type": "string",
                    "enum": [
                      "in_range",
                      "below",
                      "above",
                      "met",
                      "on_time",
                      "late"
                    ],
                    "description": "Optional per-completion quality verdict (V1.4 graded seeds).\ndiet: below|in_range|above · exercise: met|below ·\nsleep: on_time|late. weight/other omit it. Maps to the seed\namount server-side; absent grade → the type default.\n"
                  },
                  "clearCompletion": {
                    "type": "boolean",
                    "description": "放弃一次已提交的健康打卡（客户端在总结页点 X）。与\n`status: active` 一起传时，把 `completedAt` / `grade` 一并清空 ——\n客户端的当日卡路里与摄入清单只认 `completedAt`，只改 status\n那一餐照样会被计入。`status` 缺省或为 `done` 时忽略。\n刻意做成显式意图：避免 agent 改状态时误清真实完成记录。\n"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successfully updated memory",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "type": "array",
                      "description": "Updated memory row(s) from Drizzle `.returning()`. Take the first element.",
                      "items": {
                        "$ref": "#/components/schemas/MemoryItem"
                      }
                    },
                    "gameRewards": {
                      "type": "object",
                      "description": "Present only when this PATCH triggered a per-task seed grant.",
                      "properties": {
                        "seedsAwarded": {
                          "type": "integer"
                        },
                        "walletBalance": {
                          "type": "integer"
                        }
                      }
                    },
                    "attributeDelta": {
                      "type": "object",
                      "nullable": true,
                      "description": "Always `null`. The 5-dim attribute-growth system this\nfield used to carry is retired; the key is kept (as a\nliteral `null`) for wire compatibility with clients\nthat still read it.\n"
                    },
                    "energy": {
                      "description": "V1.4 (DEV-942) energy state after this task completion.\nPresent only on the FIRST done-transition; omitted on\nidempotent re-completion of an already-done task.\n",
                      "allOf": [
                        {
                          "$ref": "#/components/schemas/EnergyState"
                        }
                      ]
                    },
                    "chest": {
                      "nullable": true,
                      "description": "V1.4 (DEV-943) highest-tier chest unlocked by this\ncompletion. Present only when this completion crosses a\ndaily 3/4/5-completed-task threshold (bronze/silver/gold);\nomitted otherwise and on idempotent re-completion.\n",
                      "allOf": [
                        {
                          "$ref": "#/components/schemas/Chest"
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad request — channelLabel not a string, healthType not in the enum,\nor grade not in the enum.\n"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Memory not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "delete": {
        "summary": "Delete a memory (v2)",
        "description": "Identical to `DELETE /api/v1/memory/{id}`.",
        "tags": [
          "Memory",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Memory ID"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully deleted memory"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Memory not found"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v2/memory": {
      "get": {
        "summary": "Get memories with advanced filters (v2)",
        "description": "Identical to `GET /api/v1/memory`. Paginated list of memories for the\ncurrently logged in user. Supports filtering by status, type, time\nrange, label, health type, and keyword search. Results sort by\ncreatedAt, updatedAt, dueDate, or priority (asc/desc; default\ncreatedAt desc). When sorting by priority, ties break by dueDate asc,\nthen createdAt desc.\n",
        "tags": [
          "Memory",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            },
            "description": "Page number"
          },
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 20
            },
            "description": "Items per page"
          },
          {
            "in": "query",
            "name": "status",
            "schema": {
              "type": "string",
              "enum": [
                "active",
                "done",
                "ignored",
                "overridden",
                "unprocessed"
              ]
            },
            "description": "Filter by memory status"
          },
          {
            "in": "query",
            "name": "type",
            "schema": {
              "type": "string",
              "enum": [
                "action",
                "memory",
                "fact",
                "task",
                "plan"
              ]
            },
            "description": "Filter by memory type"
          },
          {
            "in": "query",
            "name": "startDate",
            "schema": {
              "type": "string",
              "format": "date-time"
            },
            "description": "Filter by due date start (ISO 8601, filters on dueDate field)"
          },
          {
            "in": "query",
            "name": "endDate",
            "schema": {
              "type": "string",
              "format": "date-time"
            },
            "description": "Filter by due date end (ISO 8601, filters on dueDate field)"
          },
          {
            "in": "query",
            "name": "date",
            "schema": {
              "type": "string",
              "format": "date"
            },
            "description": "Filter by attribution day (user-local YYYY-MM-DD, plan_date field). Early-morning sleep tasks (due next-day before 06:00) belong to the previous day. Independent from startDate/endDate."
          },
          {
            "in": "query",
            "name": "label",
            "schema": {
              "type": "string"
            },
            "description": "Filter by a single label"
          },
          {
            "in": "query",
            "name": "keyword",
            "schema": {
              "type": "string"
            },
            "description": "Search keyword in title and content.text"
          },
          {
            "in": "query",
            "name": "sortBy",
            "schema": {
              "type": "string",
              "enum": [
                "createdAt",
                "updatedAt",
                "dueDate",
                "priority"
              ],
              "default": "createdAt"
            },
            "description": "Sort field (createdAt, updatedAt, dueDate, or priority)"
          },
          {
            "in": "query",
            "name": "sortOrder",
            "schema": {
              "type": "string",
              "enum": [
                "asc",
                "desc"
              ],
              "default": "desc"
            },
            "description": "Sort order (asc for ascending, desc for descending)"
          },
          {
            "in": "query",
            "name": "healthType",
            "schema": {
              "type": "string",
              "enum": [
                "weight",
                "diet",
                "exercise",
                "sleep",
                "other"
              ]
            },
            "description": "Filter check-in records by health type (V1.4, DEV-959/960)"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully retrieved memories",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "items": {
                          "type": "array",
                          "items": {
                            "$ref": "#/components/schemas/MemoryItem"
                          }
                        },
                        "pagination": {
                          "type": "object",
                          "properties": {
                            "page": {
                              "type": "integer"
                            },
                            "limit": {
                              "type": "integer"
                            },
                            "total": {
                              "type": "integer"
                            },
                            "totalPages": {
                              "type": "integer"
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      },
      "post": {
        "summary": "Create a new memory (v2)",
        "description": "Identical to `POST /api/v1/memory`.",
        "tags": [
          "Memory",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "channelLabel",
                  "refId",
                  "type",
                  "title",
                  "content",
                  "priority"
                ],
                "properties": {
                  "channelLabel": {
                    "type": "string"
                  },
                  "refId": {
                    "type": "string"
                  },
                  "type": {
                    "type": "string",
                    "enum": [
                      "action",
                      "memory",
                      "fact",
                      "task",
                      "plan"
                    ]
                  },
                  "title": {
                    "type": "string"
                  },
                  "content": {
                    "type": "object"
                  },
                  "priority": {
                    "type": "integer"
                  },
                  "status": {
                    "type": "string",
                    "enum": [
                      "active",
                      "done",
                      "ignored",
                      "overridden",
                      "unprocessed"
                    ]
                  },
                  "labels": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  },
                  "tags": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    }
                  },
                  "description": {
                    "type": "string"
                  },
                  "dueDate": {
                    "type": "string",
                    "format": "date-time"
                  },
                  "metadata": {
                    "type": "object"
                  },
                  "healthType": {
                    "type": "string",
                    "enum": [
                      "weight",
                      "diet",
                      "exercise",
                      "sleep",
                      "other"
                    ],
                    "description": "健康域分类（V1.4）。**省略则落 `other`**;传了就按传的值落库。\n非法值返 400 而不是静默忽略。\n"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successfully created memory"
          },
          "400": {
            "description": "Bad request（缺必填字段，或 healthType 不在枚举内）"
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v2/onboarding/draft/integration": {
      "post": {
        "summary": "匿名期发起第三方设备授权（Oura / WHOOP / Fitbit）",
        "description": "登录前调用，返回第三方的授权链接，app 打开它走完同意页即可。回调由服务端\n处理：令牌先存到这份草稿上，注册成功后由 `POST /api/v2/onboarding` 认领时\n搬进正式的连接表。\n\n⚠️ 凭证走 `X-Onboarding-Draft` 请求头，**不要放进 URL**。\n\n⚠️ **非会员也能连**，但连上之后设备数据同步仍需会员 ——\n`POST /api/v2/contexts/health` 对非会员返回 200 且 `upgradeRequired: true`、\n一行不写。app 应当在连接成功后给出升级提示，别让用户以为已经在同步了。\n",
        "tags": [
          "Onboarding",
          "V2"
        ],
        "parameters": [
          {
            "in": "header",
            "name": "X-Onboarding-Draft",
            "schema": {
              "type": "string"
            },
            "required": true
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "provider"
                ],
                "properties": {
                  "provider": {
                    "type": "string",
                    "enum": [
                      "oura",
                      "whoop",
                      "fitbit",
                      "google-health"
                    ],
                    "description": "fitbit 与 google-health 等价，都落到 Fitbit (Google Health) 这一行"
                  },
                  "redirectUri": {
                    "type": "string",
                    "description": "省略时用本服务的回调地址"
                  },
                  "source": {
                    "type": "string",
                    "enum": [
                      "app",
                      "web"
                    ]
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "返回 authUrl"
          },
          "400": {
            "description": "provider 不在白名单 / 请求体校验失败"
          },
          "401": {
            "description": "缺草稿凭证"
          },
          "404": {
            "description": "凭证查不到，或该 provider 未配置"
          },
          "409": {
            "description": "该草稿已被认领（改走登录后的授权流程）"
          },
          "503": {
            "description": "签发一次性 ref 需要 Redis，当前不可用"
          }
        }
      }
    },
    "/api/v2/onboarding/draft": {
      "post": {
        "summary": "起草 / 重新生成匿名 onboarding 计划",
        "description": "未登录即可调用。首次不带 `X-Onboarding-Draft` 头 → 建一份 draft 并返回\n凭证；之后每次都必须带上该头。同一份答案不会重复生成（幂等）；答案变了\n则原地更新并重新生成。\n\n**`startGeneration`（可选，默认 true）** —— 传 `false` 只建行、不开始\n生成，`status` 落在 `pending`。给设计稿那个屏序用：「连设备」两屏排在\nLoader 之前，而连设备必须先有草稿行（凭证要有地方挂）。走完设备屏后再\n发一次**同样的答案**（这次不传或传 `true`）即开始生成。\n",
        "tags": [
          "Onboarding",
          "V2"
        ],
        "parameters": [
          {
            "in": "header",
            "name": "X-Onboarding-Draft",
            "schema": {
              "type": "string"
            },
            "required": false,
            "description": "已有 draft 的凭证。**只走请求头，不要放进 URL。**"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "sessionId",
                  "timezone",
                  "answers"
                ],
                "properties": {
                  "sessionId": {
                    "type": "string"
                  },
                  "timezone": {
                    "type": "string",
                    "example": "Asia/Shanghai"
                  },
                  "locale": {
                    "type": "string"
                  },
                  "location": {
                    "type": "object",
                    "properties": {
                      "latitude": {
                        "type": "number"
                      },
                      "longitude": {
                        "type": "number"
                      }
                    }
                  },
                  "answers": {
                    "type": "object",
                    "description": "字段集与 POST /api/v2/onboarding 的请求体相同"
                  },
                  "startGeneration": {
                    "type": "boolean",
                    "default": true,
                    "description": "传 false 只建行不生成（status=pending），走完设备屏后再发一次开始生成"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "202": {
            "description": "已受理（pending / 生成中 / 原样返回）"
          },
          "400": {
            "description": "契约校验失败"
          },
          "404": {
            "description": "凭证查不到"
          },
          "409": {
            "description": "该 draft 已被认领"
          },
          "429": {
            "description": "限流或超出重新生成次数上限"
          }
        }
      },
      "get": {
        "summary": "轮询匿名 onboarding 计划",
        "description": "驱动 Loader 页。`status` 为 `pending` | `generating` | `ready` | `fallback`。\n`pending` = 已建行但还没开始生成（用 `startGeneration:false` 建的），\n这时不该在 Loader 页轮询 —— 先走完设备屏、再发一次开始生成。\n⚠️ `fallback` 且 `tasks: []` 是**合法展示态**（有预算、无餐次），不是错误。\n",
        "tags": [
          "Onboarding",
          "V2"
        ],
        "parameters": [
          {
            "in": "header",
            "name": "X-Onboarding-Draft",
            "schema": {
              "type": "string"
            },
            "required": true
          }
        ],
        "responses": {
          "200": {
            "description": "draft 当前状态与计划"
          },
          "401": {
            "description": "缺凭证"
          },
          "404": {
            "description": "凭证查不到"
          }
        }
      }
    },
    "/api/v2/onboarding": {
      "post": {
        "summary": "Submit health onboarding",
        "description": "Creates the user's avatar and writes onboarding answers across three\ntables (avatar + profile demographics + health profile). All health\nfields are optional. Idempotent on re-submit (reuses an existing avatar).\n\n带 `X-Onboarding-Draft` 头时还会**认领**那份匿名草稿：把用户登录前\n已经看到的预算与餐食任务原样搬成正式数据（不重算、不重新生成）。\n认领失败不会让本接口失败 —— 降级为「当天没有计划」，由个性化生成兜底。\n",
        "tags": [
          "Onboarding",
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "header",
            "name": "X-Onboarding-Draft",
            "schema": {
              "type": "string"
            },
            "required": false,
            "description": "匿名期 `POST /api/v2/onboarding/draft` 返回的凭证。带上它，登录后\n看到的计划与登录前完全一致；不带则走纯注册 + 个性化生成。\n"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "shape": {
                    "type": "string",
                    "enum": [
                      "circle",
                      "square",
                      "triangle"
                    ],
                    "description": "Optional (V2) — the app no longer collects this at onboarding (moved in-app); defaults to 'square' when omitted."
                  },
                  "color": {
                    "type": "string",
                    "example": "#5B5EF2",
                    "description": "Optional (V2) — the app no longer collects this at onboarding (moved in-app); defaults to '#BDFF78' when omitted."
                  },
                  "name": {
                    "type": "string"
                  },
                  "userName": {
                    "type": "string",
                    "description": "Preferred display name the AI uses. Persisted to customField.userName; defaults to 'Bestie' when omitted (never the auth name)."
                  },
                  "personality": {
                    "type": "object",
                    "additionalProperties": {
                      "type": "string"
                    },
                    "description": "Optional avatar personality traits (key→value)"
                  },
                  "attribute": {
                    "type": "object",
                    "description": "Optional initial 5-dim attributes",
                    "properties": {
                      "logic": {
                        "type": "number"
                      },
                      "discipline": {
                        "type": "number"
                      },
                      "fitness": {
                        "type": "number"
                      },
                      "empathy": {
                        "type": "number"
                      },
                      "creativity": {
                        "type": "number"
                      }
                    }
                  },
                  "scenario": {
                    "type": "string",
                    "description": "Optional onboarding scenario hint"
                  },
                  "gender": {
                    "type": "string",
                    "enum": [
                      "male",
                      "female",
                      "other"
                    ],
                    "description": "V1.7 起收窄成三值；旧值 them / prefer_not_to_say 仍接受，写入时归一成 other"
                  },
                  "birthdate": {
                    "type": "string",
                    "example": "1995-03-01"
                  },
                  "height": {
                    "type": "number",
                    "example": 168
                  },
                  "goalWeight": {
                    "type": "integer",
                    "example": 55000
                  },
                  "weight": {
                    "type": "integer",
                    "description": "Current weight in grams; recorded as a weight check-in (denormalized onto the health profile, which the worker budget formula reads) on every onboarding submit — including re-onboarding (V2 forces existing users back through this screen).",
                    "example": 74200
                  },
                  "goal": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "lose_weight",
                      "maintain",
                      "gain_weight"
                    ],
                    "description": "Q1 primary goal (single-select)"
                  },
                  "activityLevel": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "sedentary",
                      "lightly_active",
                      "active",
                      "very_active"
                    ],
                    "description": "V2 Q 日常活动量（单选）。worker 预算公式必需输入"
                  },
                  "dietPreference": {
                    "type": "array",
                    "nullable": true,
                    "items": {
                      "type": "string",
                      "minLength": 1,
                      "maxLength": 40
                    },
                    "maxItems": 20,
                    "description": "V2 Q 饮食风格（多选 + 自定义自由文本，DEV-1290）。预设值 balanced/high_protein/low_carb/keto/paleo/mediterranean/pescatarian/vegetarian/vegan 与自由文本混存"
                  },
                  "allergies": {
                    "type": "array",
                    "nullable": true,
                    "items": {
                      "type": "string"
                    },
                    "description": "V2 Q 忌口。8 个预设 slug（dairy/eggs/gluten/peanuts/tree_nuts/fish/shellfish/soy）与自由文本混存，单条 ≤40 字符、最多 20 条"
                  },
                  "mealsPerDay": {
                    "type": "integer",
                    "nullable": true,
                    "minimum": 1,
                    "maximum": 5,
                    "description": "V2 Q 每日餐数"
                  },
                  "mealTimes": {
                    "type": "array",
                    "nullable": true,
                    "items": {
                      "type": "string"
                    },
                    "example": [
                      "07:00",
                      "19:00"
                    ],
                    "description": "V2 Q 用餐时间点，\"HH:MM\" 用户本地，按用餐顺序排列（不是时钟顺序，跨午夜合法）。当前恒 2 项 = [首餐, 末餐]，最多 5 项"
                  },
                  "eatingChallenges": {
                    "type": "array",
                    "nullable": true,
                    "items": {
                      "type": "string",
                      "enum": [
                        "cravings_snacking",
                        "too_busy_to_cook",
                        "eating_out_a_lot",
                        "portion_control",
                        "emotional_eating",
                        "sweet_tooth"
                      ]
                    },
                    "description": "V2 Q 饮食困难（多选）"
                  },
                  "barrier": {
                    "type": "array",
                    "nullable": true,
                    "items": {
                      "type": "string",
                      "enum": [
                        "cravings",
                        "low_motivation",
                        "no_plan",
                        "bad_habits"
                      ]
                    },
                    "description": "DEPRECATED (V2 不再采集) — Q2 biggest challenge (multi-select)"
                  },
                  "sleepTargetTime": {
                    "type": "string",
                    "nullable": true,
                    "example": "23:00",
                    "description": "DEPRECATED (V2 不再采集) — Q3 target bedtime, 24h HH:MM local wall-clock"
                  },
                  "wakeTargetTime": {
                    "type": "string",
                    "nullable": true,
                    "example": "07:00",
                    "description": "DEPRECATED (V2 不再采集) — Q3 target wake-up time, 24h HH:MM"
                  },
                  "mealFrequency": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "one_to_two",
                      "three",
                      "four_plus",
                      "varies"
                    ],
                    "description": "DEPRECATED (V2 不再采集) — Q4 meal frequency (single-select)"
                  },
                  "exerciseComfortLevel": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "beginner",
                      "light",
                      "moderate",
                      "active"
                    ],
                    "description": "DEPRECATED (V2 不再采集) — Q5 exercise comfort (legacy; mapped forward to exerciseFrequency)"
                  },
                  "exerciseFrequency": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "almost_never",
                      "one_to_two",
                      "three_to_four",
                      "five_plus"
                    ],
                    "description": "DEPRECATED (V2 不再采集) — Q5 exercise frequency (DEV-1145; preferred over exerciseComfortLevel)"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Created (or existing) user avatar",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "$ref": "#/components/schemas/UserAvatar"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Avatar shape not found"
          }
        }
      }
    },
    "/api/v2/profile": {
      "get": {
        "summary": "Get current user profile",
        "description": "Get personal profile information for the currently logged in user.\nIf no profile exists, returns null.\nTimezone and location are automatically populated on first login via browser APIs.\n",
        "tags": [
          "User",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully retrieved user profile",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "nullable": true,
                      "properties": {
                        "userId": {
                          "type": "string",
                          "example": "user_123"
                        },
                        "avatarUrl": {
                          "type": "string",
                          "nullable": true,
                          "example": "https://example.com/avatar.jpg"
                        },
                        "bio": {
                          "type": "string",
                          "nullable": true
                        },
                        "gender": {
                          "type": "string",
                          "nullable": true,
                          "enum": [
                            "male",
                            "female",
                            "them",
                            "prefer_not_to_say"
                          ],
                          "example": "female"
                        },
                        "birthdate": {
                          "type": "string",
                          "nullable": true,
                          "format": "date",
                          "example": "1995-08-20"
                        },
                        "locale": {
                          "type": "string",
                          "example": "zh-CN",
                          "description": "User locale (e.g., en, zh-CN, ja)"
                        },
                        "timezone": {
                          "type": "string",
                          "nullable": true,
                          "example": "Asia/Shanghai",
                          "description": "IANA timezone, auto-detected from browser on first login"
                        },
                        "location": {
                          "type": "object",
                          "nullable": true,
                          "description": "GPS coordinates, auto-detected from browser on first login",
                          "properties": {
                            "latitude": {
                              "type": "number",
                              "example": 39.9042
                            },
                            "longitude": {
                              "type": "number",
                              "example": 116.4074
                            }
                          }
                        },
                        "notificationSettings": {
                          "type": "object",
                          "nullable": true,
                          "properties": {
                            "push": {
                              "type": "boolean"
                            },
                            "whatsapp": {
                              "type": "boolean"
                            },
                            "phone": {
                              "type": "boolean"
                            }
                          }
                        },
                        "personalizedSettings": {
                          "type": "object",
                          "nullable": true,
                          "additionalProperties": true
                        },
                        "metadata": {
                          "type": "object",
                          "nullable": true,
                          "additionalProperties": true
                        },
                        "createdAt": {
                          "type": "string",
                          "format": "date-time"
                        },
                        "updatedAt": {
                          "type": "string",
                          "format": "date-time"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string",
                      "example": "Unauthorized"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "put": {
        "summary": "Partially update user profile",
        "description": "Update specific fields of the current user's profile.\nAll fields are optional - only provided fields will be updated.\nValidates notification settings keys (push, whatsapp, phone) and personalized settings.\n",
        "tags": [
          "User",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "avatarUrl": {
                    "type": "string",
                    "nullable": true,
                    "example": "https://example.com/avatar.jpg",
                    "description": "User avatar image URL"
                  },
                  "bio": {
                    "type": "string",
                    "nullable": true,
                    "example": "User bio description",
                    "description": "User biography or description"
                  },
                  "gender": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "male",
                      "female",
                      "them",
                      "prefer_not_to_say"
                    ],
                    "description": "User gender (V1.4 health revamp)"
                  },
                  "birthdate": {
                    "type": "string",
                    "nullable": true,
                    "example": "1995-03-01",
                    "description": "Birthdate YYYY-MM-DD (V1.4 health revamp)"
                  },
                  "locale": {
                    "type": "string",
                    "example": "zh-CN",
                    "description": "User locale preference (e.g., zh-CN, en-US)"
                  },
                  "timezone": {
                    "type": "string",
                    "nullable": true,
                    "example": "Asia/Shanghai",
                    "description": "User timezone (IANA timezone format)"
                  },
                  "location": {
                    "type": "object",
                    "nullable": true,
                    "description": "User location coordinates",
                    "properties": {
                      "latitude": {
                        "type": "number",
                        "example": 39.9042
                      },
                      "longitude": {
                        "type": "number",
                        "example": 116.4074
                      }
                    }
                  },
                  "notificationSettings": {
                    "type": "object",
                    "nullable": true,
                    "description": "Notification preferences",
                    "properties": {
                      "push": {
                        "type": "boolean",
                        "example": false
                      },
                      "whatsapp": {
                        "type": "boolean",
                        "example": false
                      },
                      "phone": {
                        "type": "boolean",
                        "example": false
                      }
                    }
                  },
                  "personalizedSettings": {
                    "type": "object",
                    "nullable": true,
                    "additionalProperties": true,
                    "description": "Personalized user settings (supports free-form fields)",
                    "properties": {
                      "labels": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        },
                        "example": [
                          "work",
                          "personal"
                        ],
                        "description": "User-defined labels"
                      },
                      "tags": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        },
                        "example": [
                          "important",
                          "urgent"
                        ],
                        "description": "User-defined tags"
                      }
                    },
                    "example": {
                      "labels": [
                        "work",
                        "personal"
                      ],
                      "tags": [
                        "important",
                        "urgent"
                      ],
                      "customField": "custom value",
                      "customNumber": 123
                    }
                  },
                  "metadata": {
                    "type": "object",
                    "nullable": true,
                    "additionalProperties": true,
                    "description": "Custom metadata object for additional profile data (supports any key-value pairs)",
                    "example": {
                      "theme": "dark",
                      "customField": "value"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Profile updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "message": {
                      "type": "string",
                      "example": "Profile updated successfully"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid request parameters - validation error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": false
                    },
                    "error": {
                      "type": "string",
                      "example": "VALIDATION_ERROR"
                    },
                    "message": {
                      "type": "string",
                      "example": "Invalid notification setting key: invalidKey"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized - Session token missing or invalid",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string",
                      "example": "Unauthorized"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": false
                    },
                    "error": {
                      "type": "string",
                      "example": "INTERNAL_ERROR"
                    },
                    "message": {
                      "type": "string",
                      "example": "Failed to update profile"
                    }
                  }
                }
              }
            }
          }
        }
      },
      "post": {
        "summary": "Create or completely update user profile",
        "description": "Create a new user profile or completely replace existing profile with provided data.\nThis endpoint performs an upsert operation - if profile exists, it will be completely replaced.\nThe locale field is required for profile creation.\n",
        "tags": [
          "User",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "locale"
                ],
                "properties": {
                  "avatarUrl": {
                    "type": "string",
                    "nullable": true,
                    "example": "https://example.com/avatar.jpg",
                    "description": "User avatar image URL"
                  },
                  "bio": {
                    "type": "string",
                    "nullable": true,
                    "example": "User bio description",
                    "description": "User biography or description"
                  },
                  "locale": {
                    "type": "string",
                    "example": "zh-CN",
                    "description": "User locale preference (required)"
                  },
                  "timezone": {
                    "type": "string",
                    "nullable": true,
                    "example": "Asia/Shanghai",
                    "description": "User timezone (IANA timezone format)"
                  },
                  "location": {
                    "type": "object",
                    "nullable": true,
                    "description": "User location coordinates",
                    "properties": {
                      "latitude": {
                        "type": "number",
                        "example": 39.9042
                      },
                      "longitude": {
                        "type": "number",
                        "example": 116.4074
                      }
                    }
                  },
                  "notificationSettings": {
                    "type": "object",
                    "nullable": true,
                    "description": "Notification preferences",
                    "properties": {
                      "push": {
                        "type": "boolean",
                        "example": false
                      },
                      "whatsapp": {
                        "type": "boolean",
                        "example": false
                      },
                      "phone": {
                        "type": "boolean",
                        "example": false
                      }
                    }
                  },
                  "personalizedSettings": {
                    "type": "object",
                    "nullable": true,
                    "additionalProperties": true,
                    "description": "Personalized user settings (supports free-form fields)",
                    "properties": {
                      "labels": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        },
                        "example": [
                          "work",
                          "personal"
                        ],
                        "description": "User-defined labels"
                      },
                      "tags": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        },
                        "example": [
                          "important",
                          "urgent"
                        ],
                        "description": "User-defined tags"
                      }
                    },
                    "example": {
                      "labels": [
                        "work",
                        "personal"
                      ],
                      "tags": [
                        "important",
                        "urgent"
                      ],
                      "customField": "custom value",
                      "customNumber": 123
                    }
                  },
                  "metadata": {
                    "type": "object",
                    "nullable": true,
                    "additionalProperties": true,
                    "description": "Custom metadata object for additional profile data (supports any key-value pairs)",
                    "example": {
                      "theme": "dark",
                      "customField": "value"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Profile created or updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "message": {
                      "type": "string",
                      "example": "Profile created/updated successfully"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized - Session token missing or invalid",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "error": {
                      "type": "string",
                      "example": "Unauthorized"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal server error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": false
                    },
                    "error": {
                      "type": "string",
                      "example": "INTERNAL_ERROR"
                    },
                    "message": {
                      "type": "string",
                      "example": "Failed to create/update profile"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v2/report/glp/{id}": {
      "patch": {
        "summary": "改一条用药记录",
        "description": "只写传了的键：**缺省 = 不动，`null` = 清空**。请求体是 `strict` 的 ——\n不认识的键直接 400，而不是静默忽略（改记录是精确操作，静默忽略更难查）。\n\n两条跨字段规则：\n\n- **`route` 与 `medication` 必须成对改。** 一条记录的药物身份是\n  `(route, slug)`，slug 只在自己那条链里唯一 —— 单改 `route` 会得到\n  根本不存在的 `(pill, ozempic)`。\n- **`doseDate` 仍然禁未来**（按用户时区判的今天）。补记历史随意。\n- **会跟着动用药任务**（DEV-1390）：改了日期就把改**之前**那天的任务放回\n  待办、改之后那天标完成；没改日期时是一次幂等的顺手修复（已完成的不动）。\n  任务状态没跟上不会让这次修改失败。\n\n改成口服链（`route=pill`）时 `injectionSite` 会被清掉 —— 口服没有注射部位。\n\n记录不存在**或不属于当前用户**都返回 404，不区分两者。\n\n**会把那天的用药任务放回待办**（DEV-1390），但只对**今天**、且只对是这条\n链自己标完成的那种（当前 done）—— 不把历史任务复活成一条逾期待办，也不\n覆盖用户手动忽略的状态。\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            },
            "description": "记录 id（`GET /api/v2/report/glp` 的 `records[].id`）"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "description": "至少给一个键。字段语义与 `POST /api/v2/report/glp` 一致。",
                "properties": {
                  "doseDate": {
                    "type": "string",
                    "example": "2026-08-26"
                  },
                  "doseTime": {
                    "type": "string",
                    "nullable": true,
                    "example": "20:15"
                  },
                  "route": {
                    "type": "string",
                    "enum": [
                      "injection",
                      "pill"
                    ]
                  },
                  "medication": {
                    "type": "string",
                    "example": "mounjaro"
                  },
                  "medicationName": {
                    "type": "string",
                    "nullable": true
                  },
                  "dose": {
                    "type": "string",
                    "example": "10 mg"
                  },
                  "injectionSite": {
                    "type": "string",
                    "nullable": true
                  },
                  "notes": {
                    "type": "string",
                    "nullable": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "更新后的记录"
          },
          "400": {
            "description": "校验失败（空 body / 未知键 / route 与 medication 没成对 / 未来日期 / 剂量缺单位）"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "记录不存在或不属于当前用户"
          }
        }
      },
      "delete": {
        "summary": "删一条用药记录",
        "description": "物理删除，不做软删 —— 这条记录是用户自己录错的一次输入，不是需要留痕的\n业务事实，且 starter 判定与剂量曲线都按记录现状算，留着反而会继续影响结果。\n\n记录不存在**或不属于当前用户**都返回 404，不区分两者。\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "已删除"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "记录不存在或不属于当前用户"
          }
        }
      }
    },
    "/api/v2/report/glp": {
      "get": {
        "summary": "GLP-1 用药报告（近 28 天记录 + 剂量曲线）",
        "description": "纯计算，无 LLM。一次返回记录页与「体重叠加剂量」那张图所需的全部数据：\n\n- `records` —— 近 **28 天**记录，按 `doseDate` **倒序**，一天最多一条\n  （表上有 `(user_id, dose_date)` 唯一约束），每条都能单独 PATCH / DELETE。\n- `doseSeries` —— 剂量时序，窗口跟着 `range`（week = 最近 7 个用户本地日、\n  month = 30），与 `GET /api/v2/report/weight` 的 `trend` **同一套分桶**，\n  前端两次调用传同一个 `range` 即可对齐 X 轴。\n- `currentMedication.doseLadder` —— 当前药的剂量阶梯，前端靠它算 Y 轴范围，\n  **不要自己硬编码**（换药阶梯会变）。\n\n三条粒度规则：\n\n1. **一个本地日一个点**。表上的唯一约束保证了这一点；分桶代码仍保留\n   「同日取最后一条」的兜底，是为了历史数据与约束之外的读路径。\n2. **区间内换过药**：`currentMedication` 取最近一条记录的药，Y 轴范围用\n   它的阶梯，**不取区间内所有药的并集**。曲线本身不因换药断开（量纲没变）。\n3. **换过单位**（mg ↔ mL / units / clicks）：`doseSeries` **分段**，\n   不做跨单位连线。`doseLadder` 恒为 mg 档位，且 Other 药返回 `null` ——\n   那一段的 Y 轴请按该段自身的历史值动态取。\n\nGLP 模式关掉也照常返回（关模式不删记录）；一条记录都没有时\n`records` / `doseSeries` 为空，`currentMedication` 回落到档案里的当前药。\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "range",
            "schema": {
              "type": "string",
              "enum": [
                "week",
                "month"
              ],
              "default": "week"
            },
            "description": "剂量曲线的窗口（`records` 恒为 28 天，不受它影响）。"
          }
        ],
        "responses": {
          "200": {
            "description": "用药报告"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      },
      "post": {
        "summary": "记一次用药",
        "description": "记一次注射 / 服药。\n\n**会把当天那条用药任务标完成**（DEV-1390）：走的是\n`PATCH /api/v2/memory/{id}` 同一条内部路径（`memoryService.updateMemory`），\n所以七日签到、`daily_task_done` 埋点、种子/能量/宝箱与用户自己点 Done\n完全一致。客户端记完药**不要**再自己 PATCH 一次 memory。\n\n- 那天还没有任务行（用户没开过首页、直接从 widget 深链进记录页）→ 顺手\n  补一条再标完成；只补**今天**，补记历史不追溯造行。\n- weekly 用户晚几天才补记 → 清掉这一针所属**排程日**那条任务\n  （判「打没打」是按周期判的，任务行的键却是精确日）。\n- 重复提交 / 只改备注不会重发奖励，`completed_at` 也不会被盖到今天。\n\n**`doseDate` 是用户自己选的本地日，不是写入时刻。** 允许补记历史，\n**禁选未来日期**（按用户时区判的今天）。28 天记录表的排序、starter 的\n换药判定、「上一条记录」的定义全部按它。\n\n**`dose` 一律是「数字 + 单位」的字符串**，例如 `\"7.5 mg\"` —— 纯数字不通过\n（5 mg 与 5 units 差十倍以上）。预设药也要传单位：查表就知道，让客户端再传\n一遍等于多一次交叉校验。落库拆 `dose` + `dose_unit` 两列，**永不换算单位**。\n允许手填不在剂量阶梯上的值 —— 阶梯是 UI 快捷选项，不是白名单。\n\n**一天一条**：同一天再 POST 一次是**更新那天的记录**，不新增行，\n返回的 `id` 与首次那条相同。由 `(user_id, dose_date)` 唯一约束在表上兜底。\n想改某一天的记录，直接对那天再 POST 一次，或用\n`PATCH /api/v2/report/glp/{id}` 按 id 改（改 `doseDate` 时同样受该约束约束）。\n\n⚠️ 这一点与被仿照的 `/api/v2/report/weight` **不同**：体重是 append-only、\n同天多条由 GET 按本地日合并。别照着体重那边预期「会多出一行」。\n代价明确接受：一天两针（分次给药、补打）只会留下后一次。\n\n口服链（`route=pill`）给了 `injectionSite` 会被忽略。\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "doseDate",
                  "route",
                  "medication",
                  "dose"
                ],
                "properties": {
                  "doseDate": {
                    "type": "string",
                    "description": "用药日期，用户本地日 `YYYY-MM-DD`。不能是未来。",
                    "example": "2026-08-27"
                  },
                  "doseTime": {
                    "type": "string",
                    "nullable": true,
                    "description": "用药时刻，24 小时制 `HH:MM`（用户本地墙钟）。",
                    "example": "20:15"
                  },
                  "route": {
                    "type": "string",
                    "enum": [
                      "injection",
                      "pill"
                    ]
                  },
                  "medication": {
                    "type": "string",
                    "description": "药物 slug（对照表里的一条，按 `route` 各自唯一）。",
                    "example": "zepbound"
                  },
                  "medicationName": {
                    "type": "string",
                    "nullable": true,
                    "description": "选了 `other` 时用户手填的药名，**必填**；预设药留空。"
                  },
                  "dose": {
                    "type": "string",
                    "description": "数字 + 单位（mg / mcg / µg / units / unit / u / mL / ml / click / clicks）。",
                    "example": "7.5 mg"
                  },
                  "injectionSite": {
                    "type": "string",
                    "nullable": true,
                    "enum": [
                      "belly_upper_left",
                      "belly_upper_right",
                      "belly_lower_left",
                      "belly_lower_right",
                      "thigh_left",
                      "thigh_right",
                      "arm_left",
                      "arm_right"
                    ],
                    "description": "只对注射链有效；口服链传了会被忽略。仅记录与回显，不做轮换建议。"
                  },
                  "notes": {
                    "type": "string",
                    "nullable": true,
                    "description": "用户备注（≤1000 字）。不会喂给模型。"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "已记录"
          },
          "400": {
            "description": "校验失败（剂量缺单位 / 未来日期 / 药物 slug 与 route 不匹配 / Other 缺手填药名）"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v2/report/weight": {
      "get": {
        "summary": "Weight progress report",
        "description": "Pure-calculation weight report (DEV-955/956). Summary\n(current/start/goal/lost/toGo/progress) is all-time; `trend` +\n`periodDelta` cover the `range` window (week = last 7 days, month = 30).\n`weekOverWeekDelta` / `monthOverMonthDelta` are calendar week-over-week /\nmonth-over-month deltas (Mon-start week / 1st-of-month, user tz),\nindependent of `range`. No LLM. Returns null summary + empty trend\nwhen the user has no records.\n",
        "tags": [
          "Game",
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "range",
            "schema": {
              "type": "string",
              "enum": [
                "week",
                "month"
              ],
              "default": "week"
            },
            "description": "Trend window (summary fields are unaffected)."
          }
        ],
        "responses": {
          "200": {
            "description": "Weight report",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "$ref": "#/components/schemas/WeightReport"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      },
      "post": {
        "summary": "Record a weight check-in (no task required)",
        "description": "手动记一次体重，**不依赖任何任务**。此前用户记体重的唯一路径是\n`POST /api/v2/memory/{id}/health-checkin`，那条路要求当天先有一条\n`healthType='weight'` 的任务 —— 没任务就记不了。\n\n与那条路的区别只有一个：**不绑任务** —— `memory_id` 落 `null`\n（表上本来就 nullable，删任务也不会带走体重历史）。\n\n⚠️ 两条路都**不发奖励**。奖励/连击来自把任务标完成\n（`PATCH /api/v2/memory/{id}` → `status='done'` → `onTaskCompleted`），\n与「记下这个体重数字」是两回事 —— 现状本来就是分开的两次调用。\n\n同一天可以记多次；`GET` 的趋势按用户本地日合并为每天一条。体重会同时\n反范式化到 `app_user_health_profile.weight`（worker 的预算公式只读那一列）。\n",
        "tags": [
          "Game",
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "weight"
                ],
                "properties": {
                  "weight": {
                    "type": "integer",
                    "description": "体重，**整数克**（不接受小数）。上限 500000（500kg）。",
                    "example": 74200
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "已记录"
          },
          "400": {
            "description": "校验失败（缺 weight / 小数 / 越界）"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v2/shop/outfit/items": {
      "get": {
        "summary": "List shop outfit items",
        "description": "List outfit items available in shop with user owned status",
        "tags": [
          "Game",
          "Shop",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "page",
            "schema": {
              "type": "integer",
              "default": 1
            }
          },
          {
            "in": "query",
            "name": "size",
            "schema": {
              "type": "integer",
              "default": 20,
              "maximum": 100
            }
          },
          {
            "in": "query",
            "name": "setId",
            "schema": {
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "owned",
            "schema": {
              "type": "boolean"
            },
            "description": "Filter by ownership status (true=owned, false=not owned, omit=all)"
          },
          {
            "in": "query",
            "name": "type",
            "schema": {
              "type": "string",
              "enum": [
                "headscarf",
                "glasses",
                "bowtie",
                "left_hand",
                "right_hand",
                "shoes"
              ]
            },
            "description": "Filter by outfit type (body part)"
          },
          {
            "in": "query",
            "name": "sortBy",
            "schema": {
              "type": "string",
              "enum": [
                "rarity",
                "price",
                "createdAt"
              ],
              "default": "rarity"
            },
            "description": "Sort field"
          },
          {
            "in": "query",
            "name": "order",
            "schema": {
              "type": "string",
              "enum": [
                "asc",
                "desc"
              ],
              "default": "desc"
            },
            "description": "Sort direction"
          },
          {
            "in": "query",
            "name": "isPurchasable",
            "schema": {
              "type": "boolean",
              "default": true
            },
            "description": "Filter by purchasable status (default true)"
          }
        ],
        "responses": {
          "200": {
            "description": "List of outfit items with owned status",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "outfitItems": {
                      "type": "array",
                      "items": {
                        "allOf": [
                          {
                            "$ref": "#/components/schemas/OutfitItem"
                          },
                          {
                            "type": "object",
                            "properties": {
                              "owned": {
                                "type": "boolean"
                              },
                              "isVariantUnlocked": {
                                "type": "boolean",
                                "description": "Whether the user has unlocked this activity-only variant item"
                              },
                              "isPurchasable": {
                                "type": "boolean",
                                "description": "Effective purchasable flag (may be overridden true for activity-unlocked variant items)"
                              }
                            }
                          }
                        ]
                      }
                    },
                    "total": {
                      "type": "integer"
                    },
                    "page": {
                      "type": "integer"
                    },
                    "size": {
                      "type": "integer"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v2/shop/purchase": {
      "post": {
        "summary": "Purchase outfit",
        "description": "Purchase an outfit item or set from the shop",
        "tags": [
          "Game",
          "Shop",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "goodsType",
                  "goodsId"
                ],
                "properties": {
                  "goodsType": {
                    "type": "string",
                    "enum": [
                      "outfit_item"
                    ],
                    "description": "Type of goods to purchase"
                  },
                  "goodsId": {
                    "type": "integer",
                    "description": "ID of the item to purchase"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Purchase successful",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "balance": {
                      "type": "integer",
                      "description": "Remaining balance after purchase"
                    },
                    "transactionId": {
                      "type": "string"
                    },
                    "purchasedGoods": {
                      "type": "object",
                      "properties": {
                        "type": {
                          "type": "string",
                          "enum": [
                            "outfit_item"
                          ]
                        },
                        "id": {
                          "type": "integer"
                        },
                        "name": {
                          "type": "string"
                        },
                        "price": {
                          "type": "integer"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error or business logic error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "402": {
            "description": "Insufficient seed balance"
          },
          "404": {
            "description": "Goods not found or unavailable"
          },
          "409": {
            "description": "Goods already owned"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/v2/subscriptions": {
      "get": {
        "summary": "列出当前用户的订阅（含已结束的）",
        "description": "返回调用者名下所有 `pay_subscription` 行（含已过期），按 `currentPeriodEnd`\n倒序。每行带一个 `badge` 供 Subscription History 页直接渲染。\n\n⚠️ **这是「一行一个订阅」，不是「一行一个计费周期」。**\n`pay_subscription` 一行一个 `(provider, userId, originalTransactionId)`，\n续订走 upsert 覆盖，表里没有按期留痕。现实中绝大多数用户只有一行。\n要按计费周期列账，Stripe 侧用 `GET /api/v0/subscription/invoices`；\nApple / Google 侧 bff 目前没有对应数据。\n\n`badge` 的三个取值：\n- `active` — 当前仍在生效。**与 `/subscription/me` 的 `isPro` 同源**\n  （由同一个 `aggregateSubscriptionState` 认定），不会出现「显示 Active\n  但调用被 402」。\n- `ended` — 停在试用期、没转正的订阅（免费试用结束）。\n- `expired` — 付费订阅已结束。\n\n⚠️ **`status` 会过期，不要拿它渲染。** prod 实测有用户三行全是\n`status: \"active\"`，而其中两行的 `currentPeriodEnd` 停在两个月前 ——\n订阅按时间失效不产生任何 webhook，这一列会永远停在最后一次事件时的值。\n`badge` 把 `currentPeriodEnd` 算进去了，渲染一律用它。\n\n`firstSeenAt` 是 bff **首次写入这一行**的时刻，不是用户下单时刻 ——\n存量订阅由 reconcile 补录，那批行的值是补录当天。别当成「订阅开始于」展示。\n",
        "tags": [
          "Subscriptions",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          },
          {
            "bearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "订阅历史列表（可能为空数组）",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "provider": {
                            "type": "string",
                            "enum": [
                              "apple",
                              "google",
                              "stripe"
                            ]
                          },
                          "productId": {
                            "type": "string"
                          },
                          "planId": {
                            "type": "string",
                            "example": "pro_monthly"
                          },
                          "status": {
                            "type": "string",
                            "example": "expired"
                          },
                          "badge": {
                            "type": "string",
                            "enum": [
                              "active",
                              "expired",
                              "ended"
                            ]
                          },
                          "currentPeriodEnd": {
                            "type": "string",
                            "format": "date-time"
                          },
                          "willRenew": {
                            "type": "boolean"
                          },
                          "isTrial": {
                            "type": "boolean"
                          },
                          "trialEnd": {
                            "type": "string",
                            "format": "date-time",
                            "nullable": true
                          },
                          "originalTransactionId": {
                            "type": "string"
                          },
                          "firstSeenAt": {
                            "type": "string",
                            "format": "date-time"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid session/JWT",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "500": {
            "description": "Internal error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/api/v2/taskgen-status": {
      "get": {
        "summary": "Today's health task-generation status",
        "description": "Returns today's (user-local) daily health-task plan state:\n- `ready` — today already has health tasks (the worker inserts a day's\n  tasks in one atomic batch).\n- `generating` — a generation is genuinely in flight: the worker holds\n  its in-flight lock for the day, or a rescue this endpoint enqueued is\n  still inside its 5-minute grace window.\n- `fallback` — nothing to show for the day: the worker gave up (the last\n  `daily-plan` agent run carries `outcome=fallback`), or it completed\n  with no readable task, or a rescue we enqueued never landed. Terminal\n  for the day — stop polling and render the empty-day state.\n\nNo LLM. Poll this when there are no tasks to show, to distinguish \"still\nworking\" from \"nothing today\". Polling also self-heals: when nothing is\nin flight the endpoint enqueues one on-demand generation for the plan\nday (at most once per user per day), so a user the per-timezone cron\nskipped gets tasks within ~1 min of opening the app.\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Daily plan status",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "status": {
                          "type": "string",
                          "enum": [
                            "generating",
                            "ready",
                            "fallback"
                          ]
                        },
                        "planDate": {
                          "type": "string",
                          "example": "2026-06-29",
                          "description": "Plan day (YYYY-MM-DD, user-local)."
                        },
                        "taskCount": {
                          "type": "integer",
                          "description": "Health tasks due today (0 unless ready)."
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v2/taskgen": {
      "post": {
        "summary": "Trigger today's daily health task generation",
        "description": "Enqueues an on-demand daily task-generation request for the\nauthenticated user onto the shared Redis queue that kicker-agent-worker\ndrains. Asynchronous and fire-and-forget: returns 202 immediately, then\nthe worker generates (~1 min) and the app polls\nGET /api/v2/taskgen-status or GET /api/v2/memory for results.\n\nIdempotent by day — the worker dedups on (userId, user-local today) and\ncollapses with the local-midnight daily cron, so repeated calls the same\nday never generate twice. No request body; the target day is the user's\nlocal today, derived by the worker from their profile timezone.\n",
        "tags": [
          "Health",
          "V2"
        ],
        "security": [
          {
            "sessionAuth": []
          }
        ],
        "responses": {
          "202": {
            "description": "Generation request enqueued",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "example": true
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "enqueued": {
                          "type": "boolean",
                          "example": true
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "402": {
            "description": "UPGRADE_REQUIRED — 每日自动生成需要 Kicker Pro。402 与「seeds 余额不足」\n共用状态码,靠响应体的 `error` 区分(UPGRADE_REQUIRED vs PAYMENT_REQUIRED)。\n"
          },
          "500": {
            "description": "Internal error"
          }
        }
      }
    },
    "/api/events/track": {
      "post": {
        "summary": "Record a tracking event (public)",
        "description": "Captures user-journey events from web + native clients for attribution.\nAnonymous events are supported — the `userId` is backfilled on signup\nby matching `sessionId`.\n",
        "tags": [
          "Public",
          "Tracking"
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "sessionId",
                  "platform",
                  "eventName"
                ],
                "properties": {
                  "sessionId": {
                    "type": "string",
                    "description": "Client-generated anonymous id (localStorage uuid / AppsFlyer UID / device id)"
                  },
                  "userId": {
                    "type": "string",
                    "description": "Optional — when already authenticated"
                  },
                  "platform": {
                    "type": "string",
                    "enum": [
                      "web",
                      "ios",
                      "android"
                    ]
                  },
                  "eventName": {
                    "type": "string",
                    "description": "Free-form, e.g. page_view / click_chat / sign_up / app_open"
                  },
                  "channel": {
                    "type": "string",
                    "description": "inpander / nexad / turbolink / facebook / google / organic / ..."
                  },
                  "clickId": {
                    "type": "string"
                  },
                  "utmSource": {
                    "type": "string"
                  },
                  "utmMedium": {
                    "type": "string"
                  },
                  "utmCampaign": {
                    "type": "string"
                  },
                  "utmContent": {
                    "type": "string"
                  },
                  "utmTerm": {
                    "type": "string"
                  },
                  "referrer": {
                    "type": "string"
                  },
                  "landingUrl": {
                    "type": "string"
                  },
                  "locale": {
                    "type": "string"
                  },
                  "scenario": {
                    "type": "string"
                  },
                  "appVersion": {
                    "type": "string",
                    "description": "native only"
                  },
                  "osVersion": {
                    "type": "string",
                    "description": "native only"
                  },
                  "deviceModel": {
                    "type": "string",
                    "description": "native only"
                  },
                  "rawParams": {
                    "type": "object",
                    "additionalProperties": {
                      "type": "string"
                    },
                    "description": "Verbatim URL query params (≤50 keys) so vendor-specific params are preserved"
                  },
                  "metadata": {
                    "type": "object",
                    "description": "Open-ended extension slot (AppsFlyer af_sub*, custom props, etc.)"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Event recorded",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "data": {
                      "type": "object",
                      "properties": {
                        "id": {
                          "type": "string"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad request or invalid payload"
          },
          "403": {
            "description": "Origin not allowed"
          },
          "429": {
            "description": "Rate limited"
          },
          "500": {
            "description": "Internal error"
          }
        }
      }
    },
    "/api/external-submissions": {
      "post": {
        "summary": "Create external submission (public)",
        "description": "Create waitlist or feedback submission without authentication.",
        "tags": [
          "Public"
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "kind"
                ],
                "properties": {
                  "kind": {
                    "type": "string",
                    "enum": [
                      "waitlist",
                      "feedback"
                    ]
                  },
                  "email": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  },
                  "message": {
                    "type": "string"
                  },
                  "source": {
                    "type": "string"
                  },
                  "metadata": {
                    "type": "object",
                    "properties": {
                      "locale": {
                        "type": "string"
                      },
                      "tags": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Created"
          },
          "400": {
            "description": "Validation error"
          },
          "429": {
            "description": "Rate limited"
          },
          "500": {
            "description": "Internal server error"
          }
        }
      }
    },
    "/api/cron/play-installs-report": {
      "get": {
        "summary": "Email the raw Google Play installs monthly reports",
        "description": "Daily cron (Cloud Scheduler, 20:00 Asia/Shanghai). Forwards the raw `installs_*_overview.csv` exports from 2026-04 through the current month to STORE_REPORT_EMAIL_TO as attachments. One send per Shanghai date; `?force=1` re-sends.",
        "tags": [
          "Cron"
        ]
      }
    },
    "/api/cron/reconcile-revenuecat": {
      "get": {
        "summary": "Reconcile RevenueCat subscription state",
        "description": "Runs on the 2-hourly compensation timer to retry RC webhook events whose first-delivery pull failed (audit rows with a non-terminal error_message). Also the manual full-compensation lever — pass `?userIds=a,b,c` to re-pull an explicit set (migration / support), or `?allActive=true` to re-pull every current Apple/Google subscriber. `?lookbackHours=` and `?limit=` override the scheduled window.\n",
        "tags": [
          "Cron"
        ]
      }
    },
    "/api/cron/reconcile-stripe": {
      "get": {
        "summary": "Re-apply subscription state for recently-paid Stripe invoices",
        "description": "Runs on the 2-hourly compensation timer to catch dropped Stripe webhooks. `?lookbackHours=` and `?limit=` override the default window (4h / 100 invoices) for a manual full-compensation deep sweep.\n",
        "tags": [
          "Cron"
        ]
      }
    },
    "/api/cron/refresh-first-touch": {
      "get": {
        "summary": "Refresh the mv_user_first_touch materialized view",
        "description": "Hourly cron (see vercel.json). Uses CONCURRENTLY so reads are not blocked during refresh.",
        "tags": [
          "Cron"
        ]
      }
    },
    "/api/cron/sync-store-metrics": {
      "get": {
        "summary": "Sync Apple/Google store metric facts into app_store_metrics",
        "description": "Daily cron (see vercel.json). Re-pulls a 9-day trailing window (or ?from=&to= for backfill). Missing creds → that platform is a no-op. Feeds funnel S1.",
        "tags": [
          "Cron"
        ]
      }
    }
  }
}