# Arete API Reference

The Arete domain ships a single Fastify-based JSON API at `apps/arete/api`.
Every endpoint requires a Bearer JWT obtained via `/v1/users/login` or
`/v1/users/register` — except the health probes, register, login, and
forgot-password routes.

## OpenAPI

The Fastify Swagger plugin generates a live OpenAPI 3.0 spec at runtime.

- Spec JSON: `GET /docs/json` (no auth)
- Interactive Swagger UI: `GET /docs` (no auth)

Both are available once the API is running locally (`pnpm nx serve arete-api`)
or in production. The spec is regenerated from the route schemas on every boot,
so the published OpenAPI is always in sync with the running server.

## Endpoint surface (95 endpoints)

All paths are relative to the `/v1` prefix unless marked otherwise.

### Health probes (no auth, no version prefix)

| Method | Path              | Purpose                           |
| ------ | ----------------- | --------------------------------- |
| GET    | `/health`         | Liveness probe                    |
| GET    | `/health/ready`   | Readiness probe (db + redis ping) |
| GET    | `/health/startup` | Startup probe                     |

### Users — authentication, profile, preferences

| Method | Path                     | Purpose                                                |
| ------ | ------------------------ | ------------------------------------------------------ |
| POST   | `/users/register`        | Create account, returns access + refresh tokens        |
| POST   | `/users/login`           | Exchange credentials for tokens                        |
| POST   | `/users/logout`          | Revoke refresh token                                   |
| GET    | `/users/me`              | Authenticated profile (incl. preferences blob)         |
| PATCH  | `/users/me`              | Update name / avatar / locale / timezone               |
| PATCH  | `/users/preferences`     | Patch notifications + privacy preferences              |
| GET    | `/users/me/export`       | JSON dump of all the user's data (download attachment) |
| DELETE | `/users/me`              | Delete account (requires password)                     |
| POST   | `/users/forgot-password` | Send password-reset email (no auth)                    |
| POST   | `/users/reset-password`  | Consume reset token to set new password                |
| POST   | `/users/change-password` | Change password while signed in                        |

### Habits

| Method | Path                      | Purpose                                                                          |
| ------ | ------------------------- | -------------------------------------------------------------------------------- |
| GET    | `/habits`                 | List habits (filter by isActive, category)                                       |
| POST   | `/habits`                 | Create habit                                                                     |
| GET    | `/habits/today`           | Today's habits with `isCompletedToday`                                           |
| GET    | `/habits/analytics`       | 30-day completion rate, weekday distribution, longest streak, recent completions |
| GET    | `/habits/:id`             | Get one habit                                                                    |
| PATCH  | `/habits/:id`             | Partial update                                                                   |
| DELETE | `/habits/:id`             | Soft-delete (sets `isActive=false`)                                              |
| POST   | `/habits/:id/complete`    | Log a completion for `:id` on a date                                             |
| GET    | `/habits/:id/completions` | Per-habit completion history                                                     |
| GET    | `/habits/:id/streak`      | Current + best streak for `:id`                                                  |
| POST   | `/habits/:id/stack`       | Stack `:id` after another habit                                                  |

### Goals

| Method | Path                   | Purpose                                       |
| ------ | ---------------------- | --------------------------------------------- |
| GET    | `/goals`               | List goals (filter by type/status/role)       |
| POST   | `/goals`               | Create goal                                   |
| GET    | `/goals/analytics`     | Goal counts by status + type + 6-month series |
| GET    | `/goals/okrs`          | List OKR cycles                               |
| POST   | `/goals/okrs`          | Create OKR with key results                   |
| GET    | `/goals/:id`           | Get one goal                                  |
| PATCH  | `/goals/:id`           | Partial update                                |
| DELETE | `/goals/:id`           | Delete                                        |
| POST   | `/goals/:id/progress`  | Update progress %                             |
| GET    | `/goals/:id/hierarchy` | Parent/child cascade                          |

### Journal

| Method | Path                   | Purpose                                            |
| ------ | ---------------------- | -------------------------------------------------- |
| GET    | `/journal/entries`     | List entries (search + tag + mood filter)          |
| POST   | `/journal/entries`     | Create entry                                       |
| GET    | `/journal/entries/:id` | Get one entry                                      |
| PATCH  | `/journal/entries/:id` | Update entry                                       |
| DELETE | `/journal/entries/:id` | Delete entry                                       |
| GET    | `/journal/prompts`     | System + custom prompts                            |
| GET    | `/journal/templates`   | Built-in templates (5-minute, morning pages, etc.) |
| GET    | `/journal/analytics`   | Lifetime totals, mood trend, top tags              |

### Vision

| Method | Path                       | Purpose                                |
| ------ | -------------------------- | -------------------------------------- |
| GET    | `/vision/boards`           | List vision boards                     |
| POST   | `/vision/boards`           | Create board                           |
| GET    | `/vision/boards/:id`       | Get one board with items               |
| PATCH  | `/vision/boards/:id`       | Update                                 |
| DELETE | `/vision/boards/:id`       | Delete                                 |
| POST   | `/vision/boards/:id/items` | Add an image / text / affirmation item |
| GET    | `/vision/mission`          | Personal mission statement             |
| PUT    | `/vision/mission`          | Replace mission statement              |
| GET    | `/vision/values`           | List user's values                     |
| PUT    | `/vision/values`           | Replace values list                    |

### Time management

| Method | Path                           | Purpose                                                                 |
| ------ | ------------------------------ | ----------------------------------------------------------------------- | ------- |
| GET    | `/time/tasks`                  | List tasks (filter by quadrant, completed, dueDate, tag)                |
| POST   | `/time/tasks`                  | Create task                                                             |
| PATCH  | `/time/tasks/:id`              | Update task (incl. `completed: true                                     | false`) |
| DELETE | `/time/tasks/:id`              | Delete task                                                             |
| GET    | `/time/weekly-plan?weekStart=` | Get weekly plan (defaults to current week)                              |
| PUT    | `/time/weekly-plan`            | Upsert weekly plan (big rocks, review, sharpen-the-saw)                 |
| GET    | `/time/daily-plan/:date`       | Get daily plan for date                                                 |
| PUT    | `/time/daily-plan/:date`       | Upsert daily plan (Big 3, time blocks, morning routine, evening review) |
| GET    | `/time/pomodoro?since=`        | List pomodoro sessions (newest first)                                   |
| POST   | `/time/pomodoro/start`         | Start a session                                                         |
| POST   | `/time/pomodoro/complete`      | Complete a session, record distractions                                 |

### Balance & wellness

| Method | Path                             | Purpose                                                   |
| ------ | -------------------------------- | --------------------------------------------------------- |
| GET    | `/balance/wheel-of-life`         | Current Wheel of Life assessment                          |
| POST   | `/balance/wheel-of-life`         | Submit a new assessment                                   |
| GET    | `/balance/wheel-of-life/history` | Historical assessments                                    |
| GET    | `/balance/mood`                  | List mood entries                                         |
| POST   | `/balance/mood`                  | Log mood entry                                            |
| GET    | `/balance/mood/analytics`        | 30-day average + weekly trend + by-day-of-week + top tags |
| GET    | `/balance/sleep`                 | List sleep entries                                        |
| POST   | `/balance/sleep`                 | Log sleep entry                                           |
| GET    | `/balance/energy`                | List energy entries                                       |
| POST   | `/balance/energy`                | Log energy entry                                          |

### Gamification

| Method | Path                                           | Purpose                           |
| ------ | ---------------------------------------------- | --------------------------------- |
| GET    | `/gamification/points`                         | Points + level summary            |
| GET    | `/gamification/points/transactions`            | Paginated transaction history     |
| GET    | `/gamification/badges`                         | Earned badges                     |
| GET    | `/gamification/badges/available`               | All badges with earned + progress |
| GET    | `/gamification/level`                          | Detailed level info               |
| GET    | `/gamification/leaderboards`                   | Top users by points               |
| GET    | `/gamification/challenges?status=`             | Available challenges              |
| POST   | `/gamification/challenges/:id/join`            | Join a challenge                  |
| GET    | `/gamification/accountability-partners`        | Partner pairs + invitations       |
| POST   | `/gamification/accountability-partners/invite` | Invite partner by email           |

### AI coach

| Method | Path                     | Purpose                                                                                          |
| ------ | ------------------------ | ------------------------------------------------------------------------------------------------ |
| POST   | `/coach/chat`            | Send message, get full coach response in one JSON payload                                        |
| POST   | `/coach/chat/stream`     | Same input as `/chat`; response streams as Server-Sent Events (`meta`, `token`, `final`, `done`) |
| GET    | `/coach/conversations`   | Paginated conversation history                                                                   |
| GET    | `/coach/recommendations` | Personalized recommendations                                                                     |
| GET    | `/coach/insights`        | AI-generated pattern insights                                                                    |
| POST   | `/coach/feedback`        | Rate a coach message                                                                             |

### Dashboard aggregator

| Method | Path                         | Purpose                                                                                                                     |
| ------ | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| GET    | `/dashboard/summary`         | Today's habits + streaks + mood + journal + active goals                                                                    |
| GET    | `/dashboard/weekly-activity` | 7-day completion / goals / journal series                                                                                   |
| GET    | `/dashboard/recent-moods`    | Last 7 days of mood entries                                                                                                 |
| POST   | `/dashboard/mood`            | Quick mood check-in                                                                                                         |
| GET    | `/dashboard/profile-stats`   | Lifetime aggregate (habits/goals/journal/days active, longest streak, best day, day-of-week record, month-over-month delta) |

## Authentication

Every authenticated endpoint expects:

```
Authorization: Bearer <accessToken>
```

Access tokens have a 15-minute TTL by default (`JWT_ACCESS_TOKEN_TTL`). The
refresh-token flow is currently a one-shot refresh — clients reuse the returned
refresh token until it expires (default 7 days, `JWT_REFRESH_TOKEN_TTL`).

Errors follow the same envelope across all endpoints:

```json
{
  "error": {
    "code": "VALIDATION_FAILED",
    "message": "...",
    "details": { ... },
    "requestId": "..."
  }
}
```

## Server-Sent Events

`POST /v1/coach/chat/stream` is the only SSE endpoint. Each line begins with
`data: ` and the body is a JSON envelope:

```
data: {"type":"meta","conversationId":"…","messageId":"…"}
data: {"type":"token","value":"Hello "}
data: {"type":"token","value":"there. "}
data: {"type":"final","message":"…","suggestions":[…],"followUp":"…"}
data: {"type":"done"}
```

Implementation lives in `apps/arete/api/src/routes/coach.ts`; the per-token
delay is configurable via `COACH_STREAM_INTERVAL_MS` (default 50 ms).
