# SupStack API v1 Documentation

**Base URL:** `https://supstack.me/api/v1`

Public, read-only REST API for accessing evidence-based supplement data. Rate limited to 60 requests per minute per IP. All endpoints return JSON and support CORS.

---

## About SupStack

SupStack is an evidence-based supplement research platform that provides structured, scientifically-grounded data on **225 supplements** backed by **7,870+ peer-reviewed studies**. The project's goal is to help users make informed supplement decisions based on research evidence rather than marketing claims.

### What This API Is For

This API gives programmatic access to a comprehensive supplement knowledge base. It is designed for:

- **AI agents and assistants** that answer supplement questions, build personalized stacks, or check interactions
- **Health & wellness apps** that need structured supplement data without building their own research database
- **Developers** building recommendation engines, chatbots, or decision-support tools around supplements

### Data Coverage

The database covers 225 supplements across 9 types:

| Type | Examples |
|------|----------|
| `vitamin` | Vitamin D3, Vitamin B12, Vitamin K2 |
| `mineral` | Magnesium, Zinc, Iron |
| `amino-acid` | L-Theanine, Glycine, L-Tyrosine, Creatine |
| `botanical` | Ashwagandha, Valerian Root, Rhodiola Rosea |
| `mushroom` | Lion's Mane, Reishi, Cordyceps |
| `compound` | Melatonin, CoQ10, NMN |
| `enzyme` | Nattokinase, Serrapeptase |
| `fatty-acid` | Omega-3, Krill Oil |
| `probiotic` | Lactobacillus, Saccharomyces boulardii |

### What Data Exists Per Supplement

Each supplement has deeply structured data across multiple dimensions:

**Identification:** ID, slug, name, full name (e.g., "Magnesium (Multiple Forms)"), element code (e.g., "Mg"), icon, categories, and tags.

**Evidence quality** (0-10 score with 4 levels):
- `very-strong` (8-10): Multiple meta-analyses, strong consensus
- `strong` (6-8): Several RCTs, good evidence base
- `moderate` (4-6): Some RCTs, mixed or limited results
- `emerging` (0-4): Preliminary data, mostly preclinical

Each supplement tracks total study count, meta-analysis count, and last review date.

**Goal mappings:** Every supplement is scored against 27 health goals (0-100 relevance score) with expected improvement descriptions and time-to-effect estimates. This powers the recommendation and matching endpoints.

**Mechanisms of action:** How the supplement works biologically (e.g., "GABA Support", "Muscle Relaxation"), with both user-friendly and scientific descriptions.

**Observable effects:** What users will notice, including prevalence percentages (e.g., "Improved Sleep — 80% of users"), timelines, and whether effects are positive, neutral, or trade-offs.

**Dosage protocol:** Recommended dose, minimum/maximum values, unit, and optional loading protocols (e.g., creatine's loading phase).

**Timing & form guidance:** Optimal times to take, whether to take with food, which supplement form is best for which goal (e.g., Magnesium Glycinate for sleep vs. L-Threonate for cognition), and alternative forms.

**Duration & cycling:** Minimum and optimal duration to see results, plus cycling recommendations for supplements that require breaks (e.g., caffeine, ashwagandha).

**Safety profile:** Overall safety rating (`high`, `moderate`, `caution`), max safe dose, contraindications, warnings, side effects (with frequency, severity, and mitigation tips), drug interactions (with severity levels), and special population guidance (pregnant, elderly, athletes, children).

**Synergies:** Which supplements work well together and why. Each synergy has a type describing the relationship:

| Synergy Type | Meaning | Example |
|-------------|---------|---------|
| `enhances` | Directly boosts the other's effects | Magnesium enhances Vitamin D activation |
| `essential` | Required for the other to work properly | B6 is essential for 5-HTP conversion |
| `stacks-well` | Complementary mechanisms | Magnesium + Glycine for sleep |
| `complementary` | Supports same goals via different pathways | Ashwagandha + Magnesium for stress |
| `protective` | Reduces side effects of the other | NAC protects against acetaminophen toxicity |
| `component` | One is a building block for the other | Glycine is a component of glutathione |
| `balance` | Helps maintain proper ratios | Zinc + Copper for mineral balance |
| `alternative` | Similar effects, not needed together | Melatonin vs Valerian Root |
| `caution` | Potential negative interaction | St. John's Wort + SSRIs |

**Research studies:** Key peer-reviewed studies with title, authors, journal, year, DOI, study type (RCT, meta-analysis, systematic review, observational), sample size, quality score (1-10), key quotes, and findings summaries. The database contains 820+ local studies plus 500+ AI-discovered studies from Supabase.

**Scientific glossary:** 80+ definitions of supplement-related terms (e.g., "bioavailability", "adaptogen", "meta-analysis", "loading phase") with aliases for flexible lookup.

### 21 Health Goals

Goals are organized into 7 categories. These goal IDs are used across the `/match`, `/recommend`, and `/stack/analyze` endpoints:

| Category | Goals |
|----------|-------|
| **Sleep** | `fall-asleep-faster`, `stay-asleep`, `deep-sleep`, `fix-schedule` |
| **Performance** | `build-strength`, `improve-endurance`, `speed-recovery`, `boost-energy` |
| **Mental** | `sharpen-focus`, `improve-memory`, `reduce-anxiety`, `support-mood` |
| **Health** | `reduce-inflammation`, `immune-support`, `longevity`, `improve-digestion`, `support-heart-health`, `balance-hormones`, `relieve-joint-pain`, `protect-vision`, `improve-skin-health` |

### Recommendation Algorithm

The `/match` and `/recommend` endpoints use a weighted goal-matching algorithm:
- **Goal 1:** 50% weight (highest priority)
- **Goal 2:** 30% weight
- **Goal 3:** 20% weight

The `/recommend` endpoint extends this with a 5-stage composite scoring system:
1. **Goal Match** (0-100): Weighted relevance scores across goals
2. **Synergy Bonus** (0 to +20): Boosts candidates that synergize with the user's existing stack
3. **Redundancy Penalty** (-20 to 0): Penalizes when the user's stack already covers the same goals
4. **Safety Penalty** (-10 to 0): Penalizes caution-rated supplements or negative interactions with stack
5. **Evidence Bonus** (0 to +5): Small tiebreaker favoring well-studied supplements

### Common AI Agent Workflows

Here are recommended endpoint combinations for typical use cases:

**"What supplements should I take for sleep?"**
1. `GET /goals` — Show available goals so the user can pick precisely
2. `GET /match?goals=deep-sleep,fall-asleep-faster&limit=5` — Get ranked recommendations
3. `GET /supplements/:slug` — Deep dive on top picks

**"I already take magnesium and ashwagandha. What should I add?"**
1. `GET /recommend?stack=magnesium,ashwagandha&limit=5` — Stack-aware recommendations
2. `GET /synergies?supplement=magnesium` — See what synergizes with their stack
3. `GET /interactions?supplements=magnesium,ashwagandha` — Verify no interaction concerns

**"Is it safe to combine X and Y?"**
1. `GET /interactions?supplements=X,Y` — Check supplement-supplement interactions
2. `GET /safety?supplement=X` + `GET /safety?supplement=Y` — Full safety profiles
3. `GET /synergies?supplements=X,Y` — Check if they have known synergies

**"I take medication Z. What supplements should I avoid?"**
1. `GET /interactions?supplement=X&medication=Z` — Check specific supplement against medication
2. `GET /safety?supplement=X` — Full drug interaction list and contraindications

**"Build me a complete stack for focus and anxiety"**
1. `GET /recommend?goals=sharpen-focus,reduce-anxiety&limit=5` — Top picks
2. `GET /stack/analyze?stack=X,Y,Z&goals=sharpen-focus,reduce-anxiety` — Audit the proposed stack
3. `GET /supplements/:slug/protocol` — Get dosing protocol for each supplement in the stack

**"Search for a supplement"**
1. `GET /search?q=mag` — Full-text search across name, description, categories, tags, and effects
2. `GET /supplements/:slug` — Full details once identified

### Important Notes for AI Agents

- **Supplement IDs are kebab-case** (e.g., `magnesium`, `vitamin-d3`, `omega-3`, `lions-mane`). Use `/search` if you're unsure of the exact ID.
- **Goal IDs are kebab-case** (e.g., `deep-sleep`, `reduce-anxiety`). Use `/goals` to get the full list.
- **Safety ratings** are `high` (safe for most people), `moderate` (some cautions), or `caution` (significant concerns — always flag to users).
- **Evidence scores** are on a 0-10 scale. Scores above 7 indicate strong scientific support. Below 5 means the evidence is preliminary.
- **Synergy lookups are bidirectional.** The `/synergies` endpoint checks both directions (A lists B AND B lists A) so you don't miss relationships.
- **The `/stack/analyze` endpoint is the most comprehensive** — it returns synergies, redundancies, safety concerns, gap analysis, and suggestions all in one call. Use it when a user shares their full stack.
- **All drug interaction data is informational**, not medical advice. Always remind users to consult healthcare providers, especially for medication interactions.
- **Rate limit is 60 req/min per IP.** Batch your queries where possible (e.g., use `/stack/analyze` instead of calling `/interactions` + `/synergies` + `/safety` separately).

---

## Endpoints

| # | Endpoint | Description |
|---|----------|-------------|
| 1 | `GET /supplements` | List & search supplements |
| 2 | `GET /supplements/:slug` | Full supplement detail |
| 3 | `GET /supplements/:slug/protocol` | Dosing protocol for a supplement |
| 4 | `GET /supplements/:slug/tracking` | N-of-1 experiment tracking protocol |
| 5 | `GET /goals` | Browse health goals |
| 6 | `GET /match` | Goal-based supplement matching |
| 7 | `GET /recommend` | Smart recommendations (goals + stack aware) |
| 8 | `GET /studies` | Research studies feed |
| 9 | `GET /compare` | Side-by-side comparison |
| 10 | `GET /interactions` | Drug & supplement interaction checker |
| 11 | `GET /synergies` | Synergy lookup between supplements |
| 12 | `GET /safety` | Full safety profile |
| 13 | `GET /definitions` | Scientific glossary (80+ terms) |
| 14 | `GET /stack/analyze` | Full stack audit with gap analysis |
| 15 | `GET /search` | Full-text supplement search |
| 16 | `GET /search/suggest` | Autocomplete / typeahead search |
| 17 | `GET /categories` | Category & type metadata |

---

## 1. List Supplements

```
GET /supplements
```

Browse, filter, search, and sort the full supplement library.

### Query Parameters

| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `page` | number | `1` | Page number |
| `pageSize` | number | `20` | Items per page (max 100) |
| `category` | string | — | Filter by category: `sleep`, `mental`, `physical`, `general` |
| `type` | string | — | Filter by type: `vitamin`, `mineral`, `amino-acid`, `herb`, `compound`, `other` |
| `goal` | string | — | Filter by goal ID (e.g. `deep-sleep`) |
| `minEvidence` | number | — | Minimum evidence score (1-10) |
| `safety` | string | — | Safety rating: `high`, `moderate`, `low` |
| `q` | string | — | Search by name, description, or tags |
| `sort` | string | `evidence` | Sort by: `evidence`, `name`, `safety` |
| `fields` | string | — | Comma-separated sparse fields (e.g. `id,name,slug`) |

### Example Request

```bash
curl "https://supstack.me/api/v1/supplements?category=sleep&minEvidence=7&pageSize=5"
```

### Example Response

```json
{
  "data": [
    {
      "id": "melatonin",
      "slug": "melatonin",
      "name": "Melatonin",
      "type": "compound",
      "shortDescription": "A naturally produced hormone that regulates sleep-wake cycles...",
      "categories": ["sleep"],
      "evidence": { "score": 9, "level": "strong", "totalStudies": 500 },
      "safety": { "overallRating": "high" },
      "dosage": { "recommended": "0.5-5mg" },
      "goals": [...]
    }
  ],
  "meta": {
    "total": 10,
    "page": 1,
    "pageSize": 5,
    "totalPages": 2
  }
}
```

### Sparse Fields Example

Request only the fields you need:

```bash
curl "https://supstack.me/api/v1/supplements?fields=id,name,slug,evidence&pageSize=3"
```

---

## 2. Supplement Detail

```
GET /supplements/:slug
```

Returns full supplement data including recent research studies.

### Example Request

```bash
curl "https://supstack.me/api/v1/supplements/magnesium"
```

### Example Response

```json
{
  "data": {
    "id": "magnesium",
    "slug": "magnesium",
    "name": "Magnesium",
    "fullName": "Magnesium (Multiple Forms)",
    "type": "mineral",
    "shortDescription": "An essential mineral involved in 300+ enzymatic reactions...",
    "longDescription": "...",
    "evidence": {
      "score": 8.5,
      "level": "strong",
      "totalStudies": 400,
      "metaAnalyses": 25,
      "summary": "..."
    },
    "dosage": {
      "recommended": "200-400mg",
      "range": { "min": "100mg", "max": "500mg" },
      "timing": "Evening, with food",
      "notes": "..."
    },
    "safety": {
      "overallRating": "high",
      "sideEffects": [...],
      "interactions": [...],
      "contraindications": [...]
    },
    "goals": [...],
    "recentStudies": [
      {
        "id": "...",
        "title": "Magnesium Supplementation and Blood Pressure...",
        "supplement_slug": "magnesium",
        "study_type": "meta-analysis",
        "year": 2022,
        "source": "...",
        "key_finding": "...",
        "sample_size": 2500
      }
    ]
  }
}
```

### Error Response (404)

```json
{ "error": "Supplement not found" }
```

---

## 3. Supplement Protocol

```
GET /supplements/:slug/protocol
```

Returns the complete dosing protocol for a supplement: recommended dosage, timing, form recommendations, duration, and cycling guidance.

### Example Request

```bash
curl "https://supstack.me/api/v1/supplements/magnesium/protocol"
```

### Example Response

```json
{
  "data": {
    "supplement": {
      "id": "magnesium",
      "name": "Magnesium",
      "slug": "magnesium"
    },
    "dosage": {
      "recommended": "200-400mg elemental magnesium daily",
      "minimum": 100,
      "maximum": 400,
      "unit": "mg",
      "loadingProtocol": null
    },
    "timing": {
      "optimal": [
        "Evening for sleep/relaxation (glycinate)",
        "Morning for energy (malate)",
        "Anytime (citrate)"
      ],
      "withFood": true,
      "notes": "Glycinate/threonate best in evening. Malate better in morning. Split doses if taking >200mg..."
    },
    "form": {
      "recommended": "Depends on goal - see notes",
      "alternatives": ["Glycinate", "L-Threonate", "Malate", "Citrate", "Taurate"],
      "notes": "GLYCINATE: Best for sleep and anxiety... L-THREONATE: Best for cognition... AVOID OXIDE: Very poor absorption."
    },
    "duration": {
      "minimum": 2,
      "optimal": 4,
      "unit": "weeks"
    },
    "cycling": {
      "recommended": false,
      "protocol": "Safe for continuous daily use. Most people are chronically deficient."
    }
  }
}
```

### Loading Protocol Example (Creatine)

```bash
curl "https://supstack.me/api/v1/supplements/creatine/protocol"
```

Returns `loadingProtocol` with phase details when a loading phase exists.

### Cycling Example (Caffeine)

```bash
curl "https://supstack.me/api/v1/supplements/caffeine/protocol"
```

Returns `cycling.recommended: true` with a detailed cycling protocol.

### Error Response (404)

```json
{ "error": "Supplement not found: fake-supplement" }
```

---

## 4. Experiment Tracking Protocol

```
GET /supplements/:slug/tracking
```

Returns a structured N-of-1 experiment tracking protocol for a supplement + goal combination. Includes baseline questionnaire, check-in schedule, and success criteria for automated verdict computation.

### Query Parameters

| Param | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `goal` | string | Yes | — | Goal ID (e.g., `deep-sleep`) |

### Example Request

```bash
curl "https://supstack.me/api/v1/supplements/magnesium/tracking?goal=deep-sleep"
```

### Example Response

```json
{
  "data": {
    "supplement": { "slug": "magnesium", "name": "Magnesium" },
    "goal": { "id": "deep-sleep", "name": "Improve deep sleep quality" },
    "protocol": {
      "duration": { "weeks": 4, "checkInSchedule": "weekly" },
      "dosage": { "recommended": "200-400mg", "form": "Glycinate", "timing": "Evening, with food" },
      "baseline": {
        "questions": [
          { "id": "sleep-quality", "type": "scale", "label": "Rate your current sleep quality", "min": 1, "max": 10 },
          { "id": "time-to-sleep", "type": "numeric", "label": "Minutes to fall asleep", "unit": "minutes" }
        ]
      },
      "checkIn": {
        "questions": [
          { "id": "sleep-quality", "type": "scale", "label": "Rate your sleep quality this week", "min": 1, "max": 10 },
          { "id": "side-effects", "type": "multi-select", "label": "Any side effects?", "options": ["None", "Digestive", "Drowsiness"] }
        ]
      },
      "successCriteria": [
        { "metric": "sleep-quality", "direction": "increase", "threshold": 2 }
      ]
    }
  }
}
```

### Error Response (404)

```json
{ "error": "Supplement not found: fake-supplement" }
```

---

## 5. Goals

```
GET /goals
```

List all 27 health goals, optionally grouped by category.

### Query Parameters

| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `grouped` | boolean | `false` | Group goals by category |

### Example: Flat List

```bash
curl "https://supstack.me/api/v1/goals"
```

```json
{
  "data": [
    {
      "id": "fall-asleep-faster",
      "name": "Fall asleep faster",
      "category": "sleep",
      "description": "..."
    }
  ],
  "meta": { "total": 21 }
}
```

### Example: Grouped by Category

```bash
curl "https://supstack.me/api/v1/goals?grouped=true"
```

```json
{
  "data": {
    "sleep": [
      { "id": "fall-asleep-faster", "name": "Fall asleep faster", "category": "sleep" },
      { "id": "stay-asleep", "name": "Stay asleep longer", "category": "sleep" },
      { "id": "deep-sleep", "name": "Improve deep sleep quality", "category": "sleep" },
      { "id": "fix-schedule", "name": "Fix sleep schedule / jet lag", "category": "sleep" }
    ],
    "physical": [...],
    "mental": [...],
    "general": [...]
  },
  "meta": {
    "total": 21,
    "categories": ["sleep", "performance", "mental", "health"]
  }
}
```

### Available Goal IDs (27 goals)

| ID | Name | Category |
|----|------|----------|
| `fall-asleep-faster` | Fall asleep faster | sleep |
| `stay-asleep` | Stay asleep longer | sleep |
| `deep-sleep` | Improve deep sleep quality | sleep |
| `fix-schedule` | Fix sleep schedule / jet lag | sleep |
| `build-strength` | Build strength & muscle | performance |
| `improve-endurance` | Improve endurance | performance |
| `speed-recovery` | Speed up recovery | performance |
| `boost-energy` | Boost daily energy | performance |
| `sharpen-focus` | Sharpen focus | mental |
| `improve-memory` | Improve memory & learning | mental |
| `reduce-anxiety` | Reduce anxiety & stress | mental |
| `support-mood` | Support mood | mental |
| `reduce-inflammation` | Reduce inflammation | health |
| `immune-support` | Support immune system | health |
| `longevity` | General longevity | health |
| `improve-digestion` | Improve digestion | health |
| `support-heart-health` | Support heart health | health |
| `balance-hormones` | Balance hormones | health |
| `relieve-joint-pain` | Relieve joint pain | health |
| `protect-vision` | Protect vision | health |
| `improve-skin-health` | Improve skin health | health |

---

## 6. Goal-Based Matching

```
GET /match
```

Get personalized supplement recommendations based on selected health goals. Uses a weighted matching algorithm: Goal 1 = 50%, Goal 2 = 30%, Goal 3 = 20%.

### Query Parameters

| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `goals` | string | **required** | Comma-separated goal IDs (1-3 goals) |
| `limit` | number | `10` | Max results (1-50) |
| `minScore` | number | `0` | Minimum match score (0-100) |

### Example Request

```bash
curl "https://supstack.me/api/v1/match?goals=deep-sleep,reduce-anxiety&limit=5"
```

### Example Response

```json
{
  "data": [
    {
      "supplement": {
        "id": "magnesium",
        "slug": "magnesium",
        "name": "Magnesium",
        "type": "mineral",
        "evidence": { "score": 8.5, "level": "strong" },
        "safety": { "overallRating": "high" }
      },
      "matchScore": 71,
      "goalBreakdown": [
        {
          "goalId": "deep-sleep",
          "goalName": "Improve deep sleep quality",
          "weight": 0.5,
          "relevanceScore": 85,
          "expectedImprovement": "moderate-high",
          "timeToEffect": "2-4 weeks"
        },
        {
          "goalId": "reduce-anxiety",
          "goalName": "Reduce anxiety & stress",
          "weight": 0.3,
          "relevanceScore": 78,
          "expectedImprovement": "moderate",
          "timeToEffect": "2-4 weeks"
        }
      ]
    }
  ],
  "meta": {
    "goals": [
      { "id": "deep-sleep", "name": "Improve deep sleep quality", "weight": 0.5 },
      { "id": "reduce-anxiety", "name": "Reduce anxiety & stress", "weight": 0.3 }
    ],
    "totalMatches": 5,
    "algorithm": "weighted-goal-match"
  }
}
```

---

## 7. Smart Recommendations

```
GET /recommend
```

Intelligent supplement recommendations that combine goal matching with stack awareness. Boosts supplements that synergize with your current stack, penalizes redundancy, and provides gap analysis.

### Query Parameters

| Param | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `goals` | string | No* | — | Up to 3 comma-separated goal IDs in priority order |
| `stack` | string | No* | — | Comma-separated supplement IDs already in your stack |
| `limit` | number | No | `10` | Max results (1-50) |
| `minScore` | number | No | `0` | Minimum composite score to include |

*At least one of `goals` or `stack` is required.

### Scoring Algorithm

Each recommendation gets a **composite score** (0-100) from 5 signals:

| Signal | Range | Description |
|--------|-------|-------------|
| Goal Match | 0-100 | Weighted 50/30/20 by goal priority (same as `/match`) |
| Synergy Bonus | 0 to +20 | Bonus for synergies with stack items (enhances, stacks-well, etc.) |
| Redundancy Penalty | -20 to 0 | Penalty when stack already covers the same goals |
| Safety Penalty | -10 to 0 | Penalty for caution-rated supplements or negative interactions |
| Evidence Bonus | 0 to +5 | Small tiebreaker favoring well-studied supplements |

In **stack-only mode** (no goals), synergy bonus is amplified as the primary ranking signal.

### Example: Goals + Stack

```bash
curl "https://supstack.me/api/v1/recommend?goals=deep-sleep,reduce-anxiety&stack=magnesium,ashwagandha&limit=3"
```

```json
{
  "data": {
    "recommendations": [
      {
        "supplement": {
          "id": "valerian-root",
          "slug": "valerian-root",
          "name": "Valerian Root",
          "evidence": { "score": 7, "level": "good" },
          "safety": { "overallRating": "high" },
          "dosage": { "recommended": "300-600mg" }
        },
        "scores": {
          "composite": 54.5,
          "goalMatch": 56,
          "synergyBonus": 5,
          "redundancyPenalty": -10,
          "safetyPenalty": 0,
          "evidenceBonus": 3.5
        },
        "goalBreakdown": [...],
        "stackSynergies": [
          {
            "withSupplement": "magnesium",
            "withSupplementName": "Magnesium",
            "synergyType": "complementary",
            "description": "Both support relaxation and sleep",
            "combinedBenefit": "Enhanced sleep quality through different mechanisms"
          }
        ],
        "warnings": [
          {
            "type": "redundancy",
            "severity": "info",
            "message": "Your stack already covers: Improve deep sleep quality, Reduce anxiety & stress."
          }
        ]
      }
    ],
    "gapAnalysis": {
      "coveredGoals": [
        { "goalId": "deep-sleep", "goalName": "Improve deep sleep quality", "topStackSupplement": "Magnesium", "coverageScore": 90 }
      ],
      "uncoveredGoals": [],
      "stackStrengths": ["Strong sleep support", "Strong cognitive & mental health"],
      "stackWeaknesses": []
    }
  },
  "meta": {
    "goals": [...],
    "stack": ["magnesium", "ashwagandha"],
    "totalCandidates": 210,
    "totalRecommendations": 3,
    "algorithm": "weighted-goal-match + synergy-bonus + redundancy-penalty"
  }
}
```

### Example: Stack Only (What pairs well?)

```bash
curl "https://supstack.me/api/v1/recommend?stack=creatine,caffeine&limit=5"
```

Returns supplements that synergize with your current stack, ranked by synergy strength + evidence quality.

### Example: Goals Only

```bash
curl "https://supstack.me/api/v1/recommend?goals=sharpen-focus,improve-memory&limit=5"
```

Works like `/match` but with evidence bonus factored into scoring.

---

## 8. Research Studies

```
GET /studies
```

Browse the research studies feed (7,870+ studies from local data and AI-discovered sources).

### Query Parameters

| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `page` | number | `1` | Page number |
| `pageSize` | number | `20` | Items per page (max 100) |
| `supplement` | string | — | Filter by supplement slug |
| `type` | string | — | Filter by study type (e.g. `rct`, `meta-analysis`) |
| `sort` | string | `newest` | Sort: `newest`, `relevance`, `year` |
| `q` | string | — | Search studies by keyword |

### Example Request

```bash
curl "https://supstack.me/api/v1/studies?supplement=magnesium&pageSize=3"
```

### Example Response

```json
{
  "data": [
    {
      "id": "abc123",
      "title": "Magnesium Supplementation and Blood Pressure: A Systematic Review",
      "supplement_slug": "magnesium",
      "supplement_name": "Magnesium",
      "study_type": "meta-analysis",
      "year": 2022,
      "source": "Journal of Clinical Hypertension",
      "key_finding": "Significant reduction in systolic blood pressure...",
      "sample_size": 2500,
      "published_date": "2022-03-15"
    }
  ],
  "meta": {
    "total": 6,
    "page": 1,
    "pageSize": 3,
    "totalPages": 2,
    "stats": {
      "totalStudies": 1324,
      "supplementsWithNewResearch": 156
    }
  }
}
```

---

## 9. Compare Supplements

```
GET /compare
```

Side-by-side comparison of 2-3 supplements with computed winners.

### Query Parameters

| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `supplements` | string | **required** | Comma-separated slugs (2-3 supplements) |

### Example Request

```bash
curl "https://supstack.me/api/v1/compare?supplements=magnesium,glycine"
```

### Example Response

```json
{
  "data": {
    "supplements": [
      {
        "id": "magnesium",
        "slug": "magnesium",
        "name": "Magnesium",
        "evidence": { "score": 8.5, "level": "strong", "totalStudies": 400 },
        "safety": { "overallRating": "high" },
        "dosage": { "recommended": "200-400mg" }
      },
      {
        "id": "glycine",
        "slug": "glycine",
        "name": "Glycine",
        "evidence": { "score": 7.5, "level": "good", "totalStudies": 80 },
        "safety": { "overallRating": "high" },
        "dosage": { "recommended": "3g" }
      }
    ],
    "comparison": {
      "evidence": { "category": "Evidence Score", "winner": "magnesium", "score": 8.5 },
      "safety": { "category": "Safety Rating", "winner": null, "note": "Tied" },
      "totalStudies": { "category": "Total Studies", "winner": "magnesium", "score": 400 }
    }
  }
}
```

---

## 10. Interactions

```
GET /interactions
```

Check drug-supplement and supplement-supplement interactions. Two modes available.

### Mode 1: Drug Interactions

Check a single supplement's drug interactions, contraindications, and warnings.

| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `supplement` | string | Yes | Supplement ID |
| `medication` | string | No | Filter by medication name (partial match) |

```bash
# All drug interactions for magnesium
curl "https://supstack.me/api/v1/interactions?supplement=magnesium"

# Filter by medication
curl "https://supstack.me/api/v1/interactions?supplement=magnesium&medication=antibiotic"
```

```json
{
  "data": {
    "supplement": { "id": "magnesium", "name": "Magnesium", "slug": "magnesium" },
    "drugInteractions": [
      {
        "medication": "Antibiotics (fluoroquinolones, tetracyclines)",
        "severity": "moderate",
        "description": "Take 2 hours apart; magnesium reduces antibiotic absorption"
      },
      {
        "medication": "Bisphosphonates",
        "severity": "moderate",
        "description": "Take 2 hours apart; may reduce absorption"
      },
      {
        "medication": "Diuretics",
        "severity": "mild",
        "description": "Some diuretics increase magnesium loss"
      }
    ],
    "contraindications": [
      "Severe kidney disease (reduced magnesium excretion)",
      "Myasthenia gravis",
      "Heart block (without pacemaker)"
    ],
    "warnings": [
      "Magnesium oxide has only 4% absorption - avoid this form",
      "Most people are deficient (estimated 50-80% of population)"
    ],
    "overallSafetyRating": "high"
  },
  "meta": {
    "totalDrugInteractions": 3,
    "totalContraindications": 3
  }
}
```

### Mode 2: Supplement-Supplement Interactions

Check interactions between 2+ supplements, including synergies and shared drug concerns.

| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `supplements` | string | Yes | Comma-separated supplement IDs (min 2) |

```bash
curl "https://supstack.me/api/v1/interactions?supplements=magnesium,ashwagandha"
```

```json
{
  "data": {
    "supplements": [
      { "id": "magnesium", "name": "Magnesium", "safetyRating": "high" },
      { "id": "ashwagandha", "name": "Ashwagandha", "safetyRating": "moderate" }
    ],
    "supplementInteractions": [
      {
        "between": ["magnesium", "ashwagandha"],
        "type": "complementary",
        "severity": "positive",
        "description": "Magnesium supports relaxation and sleep",
        "combinedBenefit": "Comprehensive stress and sleep support"
      }
    ],
    "sharedDrugConcerns": []
  },
  "meta": {
    "supplementCount": 2,
    "totalInteractions": 1,
    "cautionCount": 0,
    "positiveCount": 1,
    "sharedDrugConcerns": 0
  }
}
```

### Interaction Severity Values

| Severity | Meaning |
|----------|---------|
| `positive` | Beneficial interaction (enhances, complementary, stacks-well) |
| `neutral` | Alternative to each other |
| `caution` | Potential negative interaction — review before combining |

---

## 11. Synergies

```
GET /synergies
```

Direct synergy lookup between supplements. Two modes available.

### Mode 1: All Synergies for a Supplement

Returns both outgoing (listed on this supplement) and incoming (other supplements that list this one) synergies.

| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `supplement` | string | Yes | Supplement ID |

```bash
curl "https://supstack.me/api/v1/synergies?supplement=magnesium"
```

```json
{
  "data": {
    "supplement": { "id": "magnesium", "name": "Magnesium", "slug": "magnesium" },
    "synergies": [
      {
        "supplementId": "vitamin-d3",
        "supplementName": "Vitamin D3",
        "synergyType": "enhances",
        "description": "Magnesium is required to convert vitamin D to active form",
        "combinedBenefit": "Better vitamin D activation and utilization",
        "direction": "outgoing"
      },
      {
        "supplementId": "glycine",
        "supplementName": "Glycine",
        "synergyType": "stacks-well",
        "description": "Both support sleep through different mechanisms",
        "combinedBenefit": "Magnesium for relaxation, glycine for deep sleep",
        "direction": "outgoing"
      },
      {
        "supplementId": "melatonin",
        "supplementName": "Melatonin",
        "synergyType": "complementary",
        "description": "Magnesium supports relaxation while melatonin signals sleep timing",
        "combinedBenefit": "Comprehensive sleep onset and quality support",
        "direction": "outgoing"
      }
    ]
  },
  "meta": {
    "total": 8,
    "byType": [
      { "type": "enhances", "count": 1 },
      { "type": "stacks-well", "count": 2 },
      { "type": "complementary", "count": 3 }
    ]
  }
}
```

### Mode 2: Synergies Between Specific Supplements

| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `supplements` | string | Yes | Comma-separated supplement IDs (min 2) |

```bash
curl "https://supstack.me/api/v1/synergies?supplements=magnesium,glycine,vitamin-d3"
```

```json
{
  "data": {
    "supplements": [
      { "id": "magnesium", "name": "Magnesium" },
      { "id": "glycine", "name": "Glycine" },
      { "id": "vitamin-d3", "name": "Vitamin D3" }
    ],
    "synergies": [
      {
        "pair": ["magnesium", "glycine"],
        "pairNames": ["Magnesium", "Glycine"],
        "synergyType": "stacks-well",
        "description": "Both support sleep through different mechanisms",
        "combinedBenefit": "Magnesium for relaxation, glycine for deep sleep"
      }
    ]
  },
  "meta": {
    "supplementCount": 3,
    "totalSynergies": 2,
    "pairsChecked": 3
  }
}
```

### Synergy Types

| Type | Description |
|------|-------------|
| `enhances` | Directly boosts the other supplement's effects |
| `essential` | Required for the other supplement to work properly |
| `stacks-well` | Complementary mechanisms, good to take together |
| `complementary` | Supports similar goals through different pathways |
| `protective` | Reduces side effects or risks of the other |
| `component` | One is a building block for the other |
| `balance` | Helps maintain proper ratios |
| `alternative` | Similar effects, not needed together |
| `caution` | Potential negative interaction |

---

## 12. Safety Profile

```
GET /safety
```

Returns the complete safety profile for a supplement including side effects, drug interactions, contraindications, and special population guidance.

### Query Parameters

| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `supplement` | string | Yes | Supplement ID |

### Example Request

```bash
curl "https://supstack.me/api/v1/safety?supplement=ashwagandha"
```

### Example Response

```json
{
  "data": {
    "supplement": { "id": "ashwagandha", "name": "Ashwagandha", "slug": "ashwagandha" },
    "safety": {
      "overallRating": "moderate",
      "maxSafeDose": "600mg standardized extract daily is well-studied; higher doses not recommended",
      "contraindications": [
        "Thyroid disorders (can affect thyroid hormones)",
        "Autoimmune diseases",
        "Pregnancy and breastfeeding",
        "Scheduled surgery (stop 2 weeks before)"
      ],
      "warnings": [
        "May affect thyroid function - monitor if you have thyroid issues",
        "Cycle off periodically for best results",
        "Rare cases of liver issues reported - stop if you notice symptoms"
      ],
      "sideEffects": [
        {
          "effect": "Drowsiness",
          "frequency": "uncommon",
          "severity": "mild",
          "mitigation": "Take in evening or reduce dose"
        },
        {
          "effect": "GI upset",
          "frequency": "uncommon",
          "severity": "mild",
          "mitigation": "Take with food"
        }
      ],
      "drugInteractions": [
        {
          "medication": "Thyroid medications",
          "severity": "moderate",
          "description": "May alter thyroid hormone levels; monitor closely"
        },
        {
          "medication": "Sedatives/benzodiazepines",
          "severity": "moderate",
          "description": "May increase sedation effects"
        }
      ],
      "specialPopulations": [
        { "population": "Pregnant women", "recommendation": "Avoid" },
        { "population": "Children", "recommendation": "Not recommended" }
      ]
    }
  },
  "meta": {
    "sideEffectCount": 3,
    "drugInteractionCount": 4,
    "contraindicationCount": 4,
    "severeInteractions": 0
  }
}
```

---

## 13. Definitions

```
GET /definitions
```

Scientific glossary with 80+ supplement-related terms. Supports single term lookup, search, and category filtering.

### Query Parameters

| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `term` | string | No | Look up a specific term (case-insensitive, supports aliases) |
| `q` | string | No | Search terms and definitions |
| `category` | string | No | Filter by category |

### Single Term Lookup

```bash
curl "https://supstack.me/api/v1/definitions?term=bioavailability"
```

```json
{
  "data": {
    "term": "bioavailability",
    "definition": "The percentage of a substance that enters your bloodstream and is available for your body to use. Higher bioavailability means better absorption.",
    "aliases": []
  }
}
```

### Browse All Terms

```bash
curl "https://supstack.me/api/v1/definitions"
```

```json
{
  "data": [
    {
      "term": "meta-analysis",
      "definition": "A study that combines results from multiple studies...",
      "aliases": ["meta analysis"],
      "category": "study-types"
    }
  ],
  "meta": {
    "total": 83,
    "categories": ["study-types", "biological", "supplement-specific", "dosing", "safety", "delivery-absorption", "mineral-forms", "sleep", "pharmacology", "effect-types", "research", "brain-cognitive", "biological-processes", "measurement", "supplement-terms"]
  }
}
```

### Search Terms

```bash
curl "https://supstack.me/api/v1/definitions?q=sleep"
```

### Filter by Category

```bash
curl "https://supstack.me/api/v1/definitions?category=study-types"
```

---

## 14. Stack Analyze

```
GET /stack/analyze
```

Full stack audit: evaluates synergies between your supplements, identifies redundancies, flags safety concerns, suggests additions, and provides gap analysis against your goals.

### Query Parameters

| Param | Type | Required | Description |
|-------|------|----------|-------------|
| `stack` | string | Yes | Comma-separated supplement IDs |
| `goals` | string | No | Comma-separated goal IDs (up to 3) |

### Example Request

```bash
curl "https://supstack.me/api/v1/stack/analyze?stack=magnesium,ashwagandha,omega-3&goals=deep-sleep,reduce-anxiety"
```

### Example Response

```json
{
  "data": {
    "stack": [
      {
        "id": "magnesium",
        "name": "Magnesium",
        "slug": "magnesium",
        "type": "mineral",
        "categories": ["sleep", "mental", "performance"],
        "evidence": { "score": 8.5, "level": "strong" },
        "safety": { "overallRating": "high" },
        "dosage": { "recommended": "200-400mg elemental magnesium daily" }
      },
      {
        "id": "ashwagandha",
        "name": "Ashwagandha",
        "slug": "ashwagandha",
        "type": "botanical",
        "categories": ["mental", "sleep", "performance"],
        "evidence": { "score": 7.5, "level": "strong" },
        "safety": { "overallRating": "moderate" },
        "dosage": { "recommended": "300-600mg daily (standardized extract)" }
      }
    ],
    "synergies": [
      {
        "pair": ["magnesium", "ashwagandha"],
        "pairNames": ["Magnesium", "Ashwagandha"],
        "synergyType": "complementary",
        "description": "Magnesium supports relaxation and sleep",
        "combinedBenefit": "Comprehensive stress and sleep support"
      }
    ],
    "redundancies": [
      {
        "supplements": ["magnesium", "ashwagandha", "omega-3"],
        "sharedGoal": "reduce-anxiety",
        "goalName": "Reduce anxiety & stress",
        "scores": { "magnesium": 78, "ashwagandha": 95, "omega-3": 65 }
      }
    ],
    "safetyConcerns": [
      {
        "type": "caution-rating",
        "severity": "moderate",
        "message": "Ashwagandha has a \"caution\" safety rating. Review warnings before use.",
        "supplements": ["ashwagandha"]
      }
    ],
    "gapAnalysis": {
      "coveredGoals": [...],
      "uncoveredGoals": [...],
      "stackStrengths": ["Strong sleep support"],
      "stackWeaknesses": []
    },
    "suggestedAdditions": [
      {
        "id": "glycine",
        "name": "Glycine",
        "slug": "glycine",
        "reason": "Synergizes with Magnesium, Ashwagandha",
        "score": 35,
        "synergiesWith": ["Magnesium", "Ashwagandha"]
      }
    ]
  },
  "meta": {
    "stackSize": 3,
    "totalSynergies": 1,
    "totalRedundancies": 1,
    "totalSafetyConcerns": 1,
    "goalsAnalyzed": 2
  }
}
```

### Safety Concern Types

| Type | Description |
|------|-------------|
| `caution-rating` | Supplement has a "caution" overall safety rating |
| `caution-synergy` | Two stack supplements have a caution-level interaction |
| `shared-drug-interaction` | Multiple stack items interact with the same medication |

---

## 15. Search

```
GET /search
```

Full-text supplement search with additive scoring. Matches across name, full name, description, categories, effects, and tags. Multiple field matches boost the score (e.g., a supplement matching on both name and category ranks higher than name-only). Evidence score is used as a tiebreaker.

### Query Parameters

| Param | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `q` | string | Yes | — | Search query |
| `limit` | number | No | `10` | Max results (1-50) |

### Example Request

```bash
curl "https://supstack.me/api/v1/search?q=sleep&limit=5"
```

### Example Response

```json
{
  "data": [
    {
      "slug": "melatonin",
      "name": "Melatonin",
      "fullName": "Melatonin",
      "shortDescription": "A naturally produced hormone that regulates sleep-wake cycles...",
      "icon": "...",
      "categories": ["sleep"],
      "evidence": { "score": 9, "level": "very-strong" },
      "matchType": "name",
      "matchField": "name"
    },
    {
      "slug": "magnesium",
      "name": "Magnesium",
      "fullName": "Magnesium (Multiple Forms)",
      "shortDescription": "An essential mineral involved in 300+ enzymatic reactions...",
      "icon": "...",
      "categories": ["sleep", "health", "mental"],
      "evidence": { "score": 8.5, "level": "very-strong" },
      "matchType": "category",
      "matchField": "categories"
    }
  ],
  "meta": {
    "query": "sleep",
    "total": 42,
    "limit": 5
  }
}
```

### Additive Scoring

Scores are additive — a supplement matching the query in multiple fields gets a higher total score:

| Field | Points | Notes |
|-------|--------|-------|
| Exact name match | +100 | Highest priority |
| Name starts with query | +85 | |
| Name contains query | +70 | |
| Full name contains query | +60 | Only if name didn't match |
| Exact category match | +30 | Strong signal |
| Partial category match | +12 | |
| Exact tag match | +20 | |
| Partial tag match | +8 | |
| Description contains query | +15 | |
| Effect title/description match | +8 | |
| Evidence tiebreaker | +0-0.99 | Fractional bonus |

### Match Types

The `matchType` field indicates the strongest match category:

| matchType | Meaning |
|-----------|---------|
| `exact` | Exact name match |
| `name` | Name starts with or contains query |
| `fullName` | Full name contains query |
| `description` | Description contains query |
| `category` | Category match |
| `effect` | Effect title or description match |
| `tag` | Tag match |

---

## 16. Search Suggest (Autocomplete)

```
GET /search/suggest
```

Lightweight autocomplete / typeahead search for supplements. Matches against name, ID, full name, tags, and element codes. Use `/search` for richer results; use `/search/suggest` for fast typeahead in UIs.

### Query Parameters

| Param | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `q` | string | Yes | — | Search query (min 1 character) |
| `limit` | number | No | `10` | Max results (1-20) |

### Example Request

```bash
curl "https://supstack.me/api/v1/search/suggest?q=mag&limit=3"
```

### Example Response

```json
{
  "data": [
    {
      "id": "magnesium",
      "slug": "magnesium",
      "name": "Magnesium",
      "fullName": "Magnesium (Multiple Forms)",
      "type": "mineral",
      "icon": "...",
      "matchScore": 80
    }
  ],
  "meta": {
    "query": "mag",
    "total": 3
  }
}
```

---

## 17. Categories

```
GET /categories
```

Returns category and type metadata for the supplement library, including counts, associated goals, and distribution statistics.

### Example Request

```bash
curl "https://supstack.me/api/v1/categories"
```

### Example Response

```json
{
  "data": {
    "categories": [
      {
        "name": "health",
        "count": 150,
        "goals": [
          { "id": "reduce-inflammation", "name": "Reduce inflammation" },
          { "id": "immune-support", "name": "Support immune system" },
          { "id": "longevity", "name": "General longevity" }
        ]
      },
      {
        "name": "mental",
        "count": 57,
        "goals": [
          { "id": "sharpen-focus", "name": "Sharpen focus" },
          { "id": "improve-memory", "name": "Improve memory & learning" },
          { "id": "reduce-anxiety", "name": "Reduce anxiety & stress" },
          { "id": "support-mood", "name": "Support mood" }
        ]
      },
      {
        "name": "performance",
        "count": 37,
        "goals": [...]
      },
      {
        "name": "sleep",
        "count": 20,
        "goals": [...]
      }
    ],
    "types": [
      { "name": "botanical", "count": 55 },
      { "name": "amino-acid", "count": 40 },
      { "name": "vitamin", "count": 30 },
      { "name": "mineral", "count": 25 }
    ],
    "safetyDistribution": {
      "high": 150,
      "moderate": 55,
      "caution": 13
    },
    "evidenceDistribution": {
      "very-strong (8-10)": 30,
      "strong (6-8)": 80,
      "moderate (4-6)": 70,
      "emerging (0-4)": 38
    }
  },
  "meta": {
    "totalSupplements": 218,
    "totalCategories": 4,
    "totalTypes": 8,
    "totalGoals": 21
  }
}
```

---

## Rate Limiting

- **60 requests per minute** per IP address
- Exceeding the limit returns HTTP 429:

```json
{ "error": "Rate limit exceeded. Max 60 requests per minute." }
```

## CORS

All endpoints include CORS headers for cross-origin requests:

```
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, OPTIONS
Access-Control-Allow-Headers: Content-Type
```

All endpoints support `OPTIONS` preflight requests (returns 204).

---

## Common Patterns

### Pagination

List endpoints (`/supplements`, `/studies`) support `page` and `pageSize`:

```json
{
  "meta": {
    "total": 218,
    "page": 1,
    "pageSize": 20,
    "totalPages": 11
  }
}
```

### Error Format

All errors follow the same format:

```json
{ "error": "Human-readable error message" }
```

| Status | Meaning |
|--------|---------|
| 200 | Success |
| 204 | OPTIONS preflight OK |
| 400 | Bad request (missing/invalid params) |
| 404 | Resource not found |
| 429 | Rate limit exceeded |
| 500 | Server error |

---

## Quick Start

**Search for a supplement:**
```bash
curl "https://supstack.me/api/v1/search/suggest?q=ashwa"
```

**Get full detail on a supplement:**
```bash
curl "https://supstack.me/api/v1/supplements/magnesium"
```

**Get dosing protocol:**
```bash
curl "https://supstack.me/api/v1/supplements/magnesium/protocol"
```

**Check safety profile:**
```bash
curl "https://supstack.me/api/v1/safety?supplement=ashwagandha"
```

**Find the best sleep supplements:**
```bash
curl "https://supstack.me/api/v1/supplements?category=sleep&sort=evidence"
```

**Get personalized recommendations:**
```bash
curl "https://supstack.me/api/v1/match?goals=deep-sleep,reduce-anxiety&limit=5"
```

**Smart recommendations with stack awareness:**
```bash
curl "https://supstack.me/api/v1/recommend?goals=deep-sleep&stack=magnesium,ashwagandha&limit=5"
```

**What pairs well with my stack?**
```bash
curl "https://supstack.me/api/v1/recommend?stack=creatine,caffeine&limit=5"
```

**Analyze my full stack:**
```bash
curl "https://supstack.me/api/v1/stack/analyze?stack=magnesium,ashwagandha,omega-3&goals=deep-sleep"
```

**Check interactions before combining:**
```bash
curl "https://supstack.me/api/v1/interactions?supplements=magnesium,ashwagandha,melatonin"
```

**Find synergies:**
```bash
curl "https://supstack.me/api/v1/synergies?supplement=magnesium"
```

**Look up a scientific term:**
```bash
curl "https://supstack.me/api/v1/definitions?term=bioavailability"
```

**Compare two supplements:**
```bash
curl "https://supstack.me/api/v1/compare?supplements=magnesium,ashwagandha"
```

**Browse categories:**
```bash
curl "https://supstack.me/api/v1/categories"
```

**Search the research feed:**
```bash
curl "https://supstack.me/api/v1/studies?q=sleep+quality&sort=newest"
```

---

## Tracking Endpoint

### `GET /supplements/:slug/tracking`

Returns N-of-1 experiment tracking protocols for a supplement. Without a `goal` parameter, lists available protocols. With a `goal` parameter, returns the full composed protocol with baseline questions, check-in questions, success criteria, and side effect monitoring.

#### List Available Protocols

```bash
curl "https://supstack.me/api/v1/supplements/magnesium/tracking"
```

**Response:**
```json
{
  "data": {
    "supplement": { "id": "magnesium", "name": "Magnesium", "slug": "magnesium" },
    "availableProtocols": [
      {
        "goalId": "deep-sleep",
        "goalName": "Improve deep sleep quality",
        "relevanceScore": 90,
        "hasCustomProtocol": true
      }
    ]
  },
  "meta": {
    "totalProtocols": 5,
    "usage": "GET /api/v1/supplements/magnesium/tracking?goal=deep-sleep"
  }
}
```

#### Get Full Tracking Protocol

```bash
curl "https://supstack.me/api/v1/supplements/magnesium/tracking?goal=deep-sleep"
```

**Parameters:**
| Parameter | Required | Description |
|-----------|----------|-------------|
| `goal` | Yes | One of the 15 goal IDs (e.g., `deep-sleep`, `reduce-anxiety`) |

**Response (key fields):**
```json
{
  "data": {
    "supplement": { "id": "magnesium", "name": "Magnesium", "slug": "magnesium" },
    "goal": { "id": "deep-sleep", "name": "Improve deep sleep quality" },
    "protocol": {
      "recommendedDose": "300-400mg elemental magnesium (glycinate form)",
      "recommendedTiming": "30-60 minutes before bed, with food",
      "expectedOnset": { "minimum": 7, "typical": 14, "maximum": 28, "unit": "days" },
      "evaluationPoint": { "value": 28, "unit": "days", "note": "Most people see clear results by 4 weeks." },
      "minimumTrialDuration": { "value": 14, "unit": "days", "note": "Don't evaluate before 2 weeks." }
    },
    "baseline": {
      "instructions": "Answer based on the past 7 days, before starting Magnesium.",
      "questions": [
        {
          "id": "sleep-onset",
          "text": "How long does it typically take you to fall asleep?",
          "shortText": "Sleep onset time",
          "type": "number",
          "unit": "minutes",
          "range": { "min": 0, "max": 180 },
          "category": "primary"
        }
      ]
    },
    "checkIn": {
      "schedule": {
        "firstCheckIn": { "value": 7, "unit": "days" },
        "frequency": { "value": 7, "unit": "days" },
        "totalCheckIns": 4,
        "note": "Weekly check-ins for 4 weeks."
      },
      "questions": [ "..." ]
    },
    "successCriteria": {
      "primary": [
        { "metric": "sleep-quality", "condition": "increase", "threshold": 2, "description": "Sleep quality improves by 2+ points" }
      ],
      "secondary": [ "..." ],
      "verdict": {
        "clear-win": "2+ primary criteria met, no significant side effects",
        "probable-win": "1 primary + 1 secondary met",
        "inconclusive": "Some improvement but below thresholds",
        "not-effective": "No improvement after full trial",
        "stop": "Significant side effects — discontinue"
      }
    },
    "sideEffectMonitoring": {
      "watchFor": [
        { "effect": "GI discomfort", "likelihood": "common", "severity": "mild", "action": "Take with food", "stopIf": "Persists for more than 1 week" }
      ],
      "emergencyStop": "Stop immediately if you experience severe allergic reaction, irregular heartbeat, or difficulty breathing."
    },
    "confoundingFactors": ["Changes in caffeine intake", "Screen time before bed", "Alcohol consumption"]
  },
  "meta": {
    "supplementSlug": "magnesium",
    "goalId": "deep-sleep",
    "hasCustomProtocol": true,
    "baselineQuestionCount": 7,
    "checkInQuestionCount": 7,
    "totalCheckIns": 4
  }
}
```

**Question Types:**
| Type | Value Format | Fields |
|------|-------------|--------|
| `scale` | number (min-max) | `scale.min`, `scale.max`, `scale.lowLabel`, `scale.highLabel` |
| `number` | number | `unit`, `range.min`, `range.max` |
| `choice` | string (option value) | `options[].value`, `options[].label` |
| `multi` | string[] (option values) | `options[].value`, `options[].label` |
| `yesno` | boolean | — |
| `text` | string | `placeholder` |

**Question Categories:**
- `primary` — main outcome metrics used for verdict
- `secondary` — supporting metrics
- `compliance` — did they take it as directed
- `safety` — side effect monitoring
- `context` — confounding factor tracking

**Error Responses:**
- `404` — Supplement not found
- `400` — Invalid goal ID, or supplement doesn't map to that goal
- `404` — No tracking template available for that goal yet

**Coverage:** All 27 goals have templates. 20+ supplement-specific overrides with custom dosing, timing, and questions for popular combinations (Magnesium × sleep, Creatine × strength, Ashwagandha × anxiety, etc.).
