openapi: 3.1.0
info:
  title: Endless Pursuit API
  version: 1.0.0
  summary: Push what you do into Endless Pursuit, and read your own logs back.
  description: |
    The public API for Endless Pursuit. Anything that tracks you (a watch, a desktop timer, a gym app, a script) can
    write logs into a person's day, the same logs the app writes, so their day card, streak, circle and challenges
    follow.

    **Contract first.** This file is the contract. The `api` Edge Function (`supabase/functions/api`) implements it,
    and the app's own trackers (desktop, watch) use it too. Rules that aren't obvious from the schemas are in
    `docs/api/README.md`.

    **Auth.** Every call carries `Authorization: Bearer <token>`: a personal access token (`ep_pat_…`, made in the app
    under Settings → API access) or an OAuth access token (`ep_at_…`) an app got through the authorization code flow
    with PKCE. Each token carries scopes.

    **Writes.** Send an `Idempotency-Key` header on every POST and PATCH: a retry with the same key gets the first
    answer back. Send `external_id` with logs that come from another system: the same `external_id` from the same
    source lands once, ever.

    **The 24-hour rule.** A log can be changed for 24 hours after it reached Endless Pursuit (`editable_until`),
    then it locks (`409 log_locked`). Deleting is always allowed. Backfilling old activity is fine: a log about last
    month, sent today, is open to change until tomorrow.

    **Focus never double-counts.** The phone, a desktop tracker and a watch can all report the same hours. A focus log
    only fills time no focus log of the person already covers: untouched it lands as sent; overlapped, the free
    stretches (at least 5 minutes each) land, each with its share of the minutes (`split_into` lists the extra
    pieces); fully covered, nothing lands and the answer is `"outcome": "covered"`.

    **Privacy.** You only ever read and write the token owner's own logs. `private: true` keeps a log's numbers to its
    owner. The journal and the vision board are never reachable through the API.

    **Apps go through review.** A new OAuth app is in development: at most 2 people can connect it (the 3rd gets
    `oauth_app_in_development` on the consent screen). Ask for review with `POST /apps/{client_id}/review`; once
    approved, anyone can connect it. The quality standard every app must meet: correct idempotency and no
    duplicates (external ids), respect the rate limits, ask for the fewest scopes, publish a privacy policy, never sell
    Endless Pursuit data or use it for ads, honest naming (never present itself as Endless Pursuit), a working
    disconnect (revoke the refresh token), and graceful errors. Personal access tokens are for your own account and
    need no review.
  contact:
    name: Endless Pursuit developers
    url: https://www.endlesspursuit.app/developers
servers:
  - url: https://www.endlesspursuit.app/api/v1
    description: Production
  - url: https://xsasundibovimuzznjaf.supabase.co/functions/v1/api/v1
    description: Production, direct (same service)
security:
  - bearer: []
tags:
  - name: Me
  - name: Signals
  - name: Modules
  - name: Logs
  - name: Trackers
  - name: OAuth
  - name: Apps
paths:
  /me:
    get:
      tags: [Me]
      summary: The person the token belongs to
      operationId: getMe
      x-scopes: [profile:read]
      responses:
        '200':
          description: The token's person, and what the token may do.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Me' }
        default: { $ref: '#/components/responses/Error' }

  /modules:
    get:
      tags: [Modules]
      summary: Modules the API can write, with the person's installed ones marked
      operationId: listModules
      x-scopes: [modules:read]
      responses:
        '200':
          description: Every module the API writes to.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Module' }
        default: { $ref: '#/components/responses/Error' }

  /health/days:
    post:
      tags: [Logs]
      summary: Steps, sleep, heart and mindful minutes, one day at a time
      description: |
        One log a day per module (`steps`, `sleep`, `heart`, `mindful`), the same rows the phone keeps from Apple
        Health and Health Connect. Send a day again as its totals grow: your own day is updated in place (the 24-hour
        rule doesn't lock it). A day the phone's step counter made is taken over by yours; a day Apple Health,
        Health Connect or another source already keeps is left alone (`kept`); a day the person deleted stays out
        (`dismissed`). Daily logs never count as showing up and carry no minutes. Read them back with
        `GET /logs?module=steps` (their numbers are in `health_day`).
      operationId: postHealthDays
      x-scopes: [logs:write]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [days]
              properties:
                source: { type: string, description: As in LogInput (personal tokens; apps are always themselves). }
                days:
                  type: array
                  minItems: 1
                  maxItems: 60
                  items:
                    type: object
                    required: [day]
                    properties:
                      day: { type: string, format: date, description: The day in the person's own time zone (see /me). }
                      steps: { type: integer, minimum: 0, maximum: 200000 }
                      distance_m: { type: number, minimum: 0, maximum: 500000 }
                      flights: { type: integer, minimum: 0, maximum: 2000 }
                      active_kcal: { type: number, minimum: 0, maximum: 20000 }
                      exercise_min: { type: integer, minimum: 0, maximum: 1440 }
                      stand_hours: { type: integer, minimum: 0, maximum: 24 }
                      sleep_min: { type: integer, minimum: 0, maximum: 1440, description: 'Asleep, for the night ending on this day.' }
                      in_bed_min: { type: integer, minimum: 0, maximum: 1440 }
                      sleep_start: { type: string, format: date-time }
                      sleep_end: { type: string, format: date-time }
                      resting_hr: { type: integer, minimum: 0, maximum: 250 }
                      hrv_ms: { type: number, minimum: 0, maximum: 500 }
                      vo2max: { type: number, minimum: 0, maximum: 100 }
                      mindful_min: { type: integer, minimum: 0, maximum: 1440 }
      responses:
        '200':
          description: What happened to each module of each day (modules with nothing sent are left out).
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        day: { type: string, format: date }
                        steps: { type: string, enum: [created, updated, unchanged, kept, dismissed, paused] }
                        sleep: { type: string, enum: [created, updated, unchanged, kept, dismissed, paused] }
                        heart: { type: string, enum: [created, updated, unchanged, kept, dismissed, paused] }
                        mindful: { type: string, enum: [created, updated, unchanged, kept, dismissed, paused] }
        default: { $ref: '#/components/responses/Error' }

  /projects:
    get:
      tags: [Modules]
      summary: The person's projects still going (for a focus block's project_id)
      operationId: listProjects
      x-scopes: [modules:read]
      responses:
        '200':
          description: Projects not archived, in the person's order.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string, format: uuid }
                        name: { type: string }
                        kind: { type: [string, 'null'] }
                        shipped: { type: boolean }
                        due_on: { type: [string, 'null'], format: date }
        default: { $ref: '#/components/responses/Error' }

  /signals:
    post:
      tags: [Signals]
      summary: Send presence signals (what the person is doing, moment to moment)
      description: |
        The same signals our desktop, phone and watch trackers send (docs/product/topics/presence.md): Endless
        Pursuit turns them into prompts like "Log that hour of focus?". Up to 500 a call; the same source, kind,
        device_id and started_at update the one signal (idempotent). Signals older than 7 days or in the future are
        dropped quietly. OAuth apps always send as `api`; personal tokens and our own trackers may say `desktop`,
        `watch` or `phone`.
      operationId: postSignals
      x-scopes: [logs:write]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [signals]
              properties:
                source: { type: string, enum: [api, desktop, watch, phone], default: api }
                signals:
                  type: array
                  minItems: 1
                  maxItems: 500
                  items: { $ref: '#/components/schemas/Signal' }
      responses:
        '200':
          description: How many went in.
          content:
            application/json:
              schema:
                type: object
                properties:
                  accepted: { type: integer }
                  received: { type: integer }
        default: { $ref: '#/components/responses/Error' }

  /exercises:
    get:
      tags: [Modules]
      summary: The exercise library a workout's exercises come from
      operationId: listExercises
      x-scopes: [modules:read]
      responses:
        '200':
          description: Every exercise, with how it's tracked.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Exercise' }
        default: { $ref: '#/components/responses/Error' }

  /logs:
    get:
      tags: [Logs]
      summary: The person's own logs, newest first
      operationId: listLogs
      x-scopes: [logs:read]
      parameters:
        - { name: module, in: query, description: 'Any ModuleId, or a daily one: steps, sleep, heart, mindful.', schema: { type: string } }
        - { name: since, in: query, description: Logs that started at or after this time., schema: { type: string, format: date-time } }
        - { name: until, in: query, description: Logs that started before this time., schema: { type: string, format: date-time } }
        - { name: source, in: query, description: Only logs written by this source (see `LogInput.source`)., schema: { type: string } }
        - { name: external_id, in: query, description: With `source`, the one log carrying this id., schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 30 } }
        - { name: cursor, in: query, description: '`next_cursor` from the page before.', schema: { type: string } }
      responses:
        '200':
          description: A page of logs.
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Log' }
                  next_cursor: { type: [string, 'null'] }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Logs]
      summary: Log something
      description: |
        Creates one log. With an `external_id` that already landed from the same source, nothing changes and the
        existing log comes back with `200` and `"outcome": "already"`. If the person deleted that log in the app, it
        stays deleted: `409 log_dismissed`.
      operationId: createLog
      x-scopes: [logs:write]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/LogInput' }
            examples:
              focus: { $ref: '#/components/examples/focus' }
              workout: { $ref: '#/components/examples/workout' }
              activity: { $ref: '#/components/examples/activity' }
              meal: { $ref: '#/components/examples/meal' }
              weight: { $ref: '#/components/examples/weight' }
              reading: { $ref: '#/components/examples/reading' }
              tracker: { $ref: '#/components/examples/tracker' }
      responses:
        '201':
          description: Logged.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LogResult' }
        '200':
          description: 'Already there (same source and external_id), or outcome "covered" for focus time another focus log covers (no log).'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LogResult' }
        default: { $ref: '#/components/responses/Error' }

  /logs/batch:
    post:
      tags: [Logs]
      summary: Log up to 100 things at once
      description: |
        Each item lands or fails on its own, so one bad item never holds back the rest. The answer lists every item in
        the order sent. Made for syncing: send `external_id` with each.
      operationId: createLogs
      x-scopes: [logs:write]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [logs]
              properties:
                logs:
                  type: array
                  minItems: 1
                  maxItems: 100
                  items: { $ref: '#/components/schemas/LogInput' }
      responses:
        '200':
          description: One result per item.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      required: [index, outcome]
                      properties:
                        index: { type: integer }
                        outcome: { type: string, enum: [created, already, dismissed, covered, invalid] }
                        external_id: { type: [string, 'null'] }
                        log: { $ref: '#/components/schemas/Log' }
                        error: { $ref: '#/components/schemas/ErrorBody' }
        default: { $ref: '#/components/responses/Error' }

  /logs/{id}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
    get:
      tags: [Logs]
      summary: One of the person's logs
      operationId: getLog
      x-scopes: [logs:read]
      responses:
        '200':
          description: The log.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Log' }
        default: { $ref: '#/components/responses/Error' }
    patch:
      tags: [Logs]
      summary: Change a log (within 24 hours of it landing)
      description: |
        Send only what changes. The module's own object is merged one level deep (`{"activity": {"title": "Hills"}}`
        keeps the distance); arrays (sets, meal items) are replaced whole. The module can't change.

        An OAuth app may change only logs it wrote itself. A personal access token may change any of its owner's logs
        the API can reach.
      operationId: updateLog
      x-scopes: [logs:write]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/LogPatch' }
      responses:
        '200':
          description: The changed log.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Log' }
        default: { $ref: '#/components/responses/Error' }
    delete:
      tags: [Logs]
      summary: Delete a log (any time)
      description: |
        Same ownership rule as PATCH. A log deleted through the API can be sent again later with the same
        `external_id`; one the person deleted in the app can't (`log_dismissed`).
      operationId: deleteLog
      x-scopes: [logs:write]
      responses:
        '204': { description: Deleted. }
        default: { $ref: '#/components/responses/Error' }

  /trackers:
    get:
      tags: [Trackers]
      summary: The person's custom trackers
      operationId: listTrackers
      x-scopes: [modules:read]
      responses:
        '200':
          description: Every tracker the person has (removed ones too, marked).
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Tracker' }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Trackers]
      summary: Make a custom tracker (the app shows their logs as plain cards until it has a Trackers screen)
      description: 'Anything with a number (glasses of water, cold showers, hours of sleep, words written). Log to it with module `custom`.'
      operationId: createTracker
      x-scopes: [logs:write]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TrackerInput' }
      responses:
        '201':
          description: Made.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Tracker' }
        default: { $ref: '#/components/responses/Error' }

  /trackers/{id}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
    patch:
      tags: [Trackers]
      summary: Rename a tracker or change its unit or mode
      operationId: updateTracker
      x-scopes: [logs:write]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TrackerInput' }
      responses:
        '200':
          description: The tracker.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Tracker' }
        default: { $ref: '#/components/responses/Error' }
    delete:
      tags: [Trackers]
      summary: Remove a tracker (its logs stay)
      operationId: deleteTracker
      x-scopes: [logs:write]
      responses:
        '204': { description: Removed. }
        default: { $ref: '#/components/responses/Error' }

  /oauth/token:
    post:
      tags: [OAuth]
      summary: Swap an authorization code or a refresh token for tokens
      description: |
        RFC 6749 token endpoint. Form-encoded (`application/x-www-form-urlencoded`), or JSON. Public clients (phone and
        desktop apps) send `client_id` only and prove themselves with PKCE; confidential clients also send
        `client_secret` (in the body, or HTTP Basic). Refresh tokens rotate: each refresh gives a new one and ends the
        old; using an old one again ends the whole connection.
      operationId: oauthToken
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema: { $ref: '#/components/schemas/TokenRequest' }
          application/json:
            schema: { $ref: '#/components/schemas/TokenRequest' }
      responses:
        '200':
          description: Tokens.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TokenResponse' }
        '400':
          description: RFC 6749 error (`invalid_request`, `invalid_grant`, `unsupported_grant_type`).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OAuthError' }
        '401':
          description: '`invalid_client`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OAuthError' }

  /oauth/revoke:
    post:
      tags: [OAuth]
      summary: Revoke a token (RFC 7009)
      description: Revoking a refresh token ends the app's connection to the person. Unknown tokens answer 200 too.
      operationId: oauthRevoke
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [token, client_id]
              properties:
                token: { type: string }
                token_type_hint: { type: string, enum: [access_token, refresh_token] }
                client_id: { type: string }
                client_secret: { type: string }
      responses:
        '200': { description: Done. }

  /apps:
    get:
      tags: [Apps]
      summary: Your OAuth apps
      operationId: listApps
      x-scopes: [apps:write]
      x-personal-token-only: true
      responses:
        '200':
          description: Apps you registered.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/App' }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Apps]
      summary: Register an OAuth app
      description: |
        `confidential: true` for an app with a server that can keep a secret: the answer carries `client_secret`
        once. Leave it false for phone and desktop apps, which use PKCE alone.
      operationId: createApp
      x-scopes: [apps:write]
      x-personal-token-only: true
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/AppInput' }
      responses:
        '201':
          description: Registered.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/App' }
        default: { $ref: '#/components/responses/Error' }

  /apps/{client_id}:
    parameters:
      - { name: client_id, in: path, required: true, schema: { type: string } }
    patch:
      tags: [Apps]
      summary: Change an app's name, links or redirect URIs
      operationId: updateApp
      x-scopes: [apps:write]
      x-personal-token-only: true
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/AppInput' }
      responses:
        '200':
          description: The app.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/App' }
        default: { $ref: '#/components/responses/Error' }
    delete:
      tags: [Apps]
      summary: Delete an app (ends every person's connection to it)
      operationId: deleteApp
      x-scopes: [apps:write]
      x-personal-token-only: true
      responses:
        '204': { description: Deleted. }
        default: { $ref: '#/components/responses/Error' }

  /apps/{client_id}/review:
    parameters:
      - { name: client_id, in: path, required: true, schema: { type: string } }
    post:
      tags: [Apps]
      summary: Ask for review, to go public
      description: |
        Until it's approved an app reaches at most 2 people. The request goes to the Endless Pursuit team, who approve
        it, or reject it with notes (fix and ask again). `GET /apps` shows `status` and the latest review's notes.
      operationId: requestAppReview
      x-scopes: [apps:write]
      x-personal-token-only: true
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [description, scopes, privacy_url, media_urls, contact_email]
              properties:
                app_name: { type: string, minLength: 2, maxLength: 60, description: Defaults to the app's name. }
                description: { type: string, minLength: 20, maxLength: 2000, description: What it does, and why it needs each scope. }
                scopes: { type: array, items: { type: string }, description: The scopes it asks people for. }
                privacy_url: { type: string, format: uri, description: https. }
                media_urls: { type: array, minItems: 1, maxItems: 10, items: { type: string, format: uri }, description: https links to screenshots or a short video of the whole flow, connecting and disconnecting included. }
                contact_email: { type: string, format: email }
                notes: { type: string, maxLength: 2000, description: Anything else (test account, how to try it). }
      responses:
        '200':
          description: The app, now `in_review`.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/App' }
        default: { $ref: '#/components/responses/Error' }

  /apps/{client_id}/secret:
    parameters:
      - { name: client_id, in: path, required: true, schema: { type: string } }
    post:
      tags: [Apps]
      summary: Make a new client secret (the old one stops working)
      operationId: rotateAppSecret
      x-scopes: [apps:write]
      x-personal-token-only: true
      responses:
        '200':
          description: The app, with `client_secret` shown once.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/App' }
        default: { $ref: '#/components/responses/Error' }

components:
  securitySchemes:
    bearer:
      type: http
      scheme: bearer
      description: |
        A personal access token (`ep_pat_…`), an OAuth access token (`ep_at_…`), or, for Endless Pursuit's own apps
        (desktop and watch trackers), the person's Supabase session JWT (every scope but `apps:write`).
    oauth:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://www.endlesspursuit.app/oauth/authorize
          tokenUrl: https://www.endlesspursuit.app/api/v1/oauth/token
          refreshUrl: https://www.endlesspursuit.app/api/v1/oauth/token
          scopes:
            profile:read: Your name, username and time zone.
            modules:read: Your modules and custom trackers.
            logs:read: Read your logs.
            logs:write: Add logs, and change or delete the ones this app added.
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      description: |
        Any unique string up to 200 characters (a UUID is ideal). The same key with the same request within 24 hours
        returns the first answer (with `Idempotent-Replayed: true`); with a different request it's `422
        idempotency_mismatch`.
      schema: { type: string, maxLength: 200 }
  responses:
    Error:
      description: |
        Every error has the same shape. `400 invalid_request`, `401 token_invalid`, `403 scope_missing` /
        `account_inactive` / `not_your_log`, `404 not_found`, `409 log_locked` / `log_dismissed` /
        `idempotency_busy`, `422` validation (`fact_not_a_number`, `log_in_future`, `module_closed`, `book_not_found`,
        `project_not_found`, `exercise_unknown` …), `429 rate_limited` (see `Retry-After`), `503 api_paused`.
      headers:
        X-Request-Id: { schema: { type: string } }
      content:
        application/json:
          schema:
            type: object
            required: [error]
            properties:
              error: { $ref: '#/components/schemas/ErrorBody' }
  schemas:
    ErrorBody:
      type: object
      required: [code, message]
      properties:
        code: { type: string, examples: [log_locked] }
        message: { type: string, examples: ['This log is past its 24 hours and can no longer be changed. You can still delete it.'] }
        field: { type: string, description: The input that's wrong, as a path (`activity.distance_km`). }
        request_id: { type: string }
    OAuthError:
      type: object
      required: [error]
      properties:
        error: { type: string }
        error_description: { type: string }

    ModuleId:
      type: string
      enum: [focus, training, running, nutrition, weight, reading, custom]
      description: |
        `running` is Activities (runs, walks, hikes, rides, swims): its id predates the rename. `training` is
        workouts. `custom` is a custom tracker.

    Me:
      type: object
      required: [id, username, display_name, timezone, token]
      properties:
        id: { type: string, format: uuid }
        username: { type: string }
        display_name: { type: [string, 'null'] }
        timezone: { type: string, description: IANA zone. A log's `day` is its start in this zone. }
        token:
          type: object
          properties:
            kind: { type: string, enum: [personal, oauth] }
            scopes: { type: array, items: { type: string } }
            app: { type: [string, 'null'], description: The OAuth app's name. }

    Module:
      type: object
      required: [id, name, mode, input, facts, installed, enabled]
      properties:
        id: { $ref: '#/components/schemas/ModuleId' }
        name: { type: string, examples: [Activities] }
        mode: { type: string, enum: [body, work, mind] }
        input: { type: string, description: The object a log of this module carries in `LogInput`., examples: [activity] }
        installed: { type: boolean, description: Whether it's on the person's Today. Logging works either way. }
        enabled: { type: boolean, description: False while paused for everyone; new logs get `422 module_closed`. }
        shows_up: { type: boolean, description: Whether a log of it counts as showing up for the day (the streak). }
        facts:
          type: array
          description: The numbers the module adds to the day card. Computed from what you send; read them on each log.
          items:
            type: object
            properties:
              key: { type: string }
              label: { type: string }
              unit: { type: string }
              agg: { type: string, enum: [sum, max, last, count] }

    Exercise:
      type: object
      properties:
        id: { type: string, examples: [bench_press] }
        name: { type: string }
        kind: { type: string, enum: [strength, conditioning, mobility] }
        tracking: { type: string, enum: [weight_reps, reps, time, distance], description: Which set values count. }

    LogInput:
      type: object
      required: [module]
      description: |
        `module`, when it happened, and the module's own object (`focus`, `workout`, `activity`, `meal`, `weight`,
        `reading` or `tracker`: exactly the one `Module.input` names). Facts (`km`, `volume_kg` …) are worked out
        from it, the same way the app does.

        **When.** `started_at` and `ended_at`, or `started_at` and `minutes`, or `ended_at` and `minutes`. With
        nothing, it's now. Nothing may start more than 5 minutes in the future. `minutes` is the time spent (focused
        minutes, moving time), 0 to 1440; it defaults to the gap between start and end.
      properties:
        module: { $ref: '#/components/schemas/ModuleId' }
        started_at: { type: string, format: date-time }
        ended_at: { type: string, format: date-time }
        minutes: { type: integer, minimum: 0, maximum: 1440 }
        note: { type: string, maxLength: 280, description: Only its owner ever reads it. }
        private: { type: boolean, default: false, description: Only me. Still counts as showing up; nobody else sees its numbers. }
        source:
          type: string
          pattern: '^[a-z0-9][a-z0-9_.-]{1,39}$'
          description: |
            Where it came from, for your own de-duplication (`garmin-sync`, `my-script`). Ignored for OAuth apps,
            whose source is always the app. Defaults to `api`.
        external_id:
          type: string
          maxLength: 200
          description: The id the source knows it by. The same source and external_id land once.
        focus: { $ref: '#/components/schemas/FocusInput' }
        workout: { $ref: '#/components/schemas/WorkoutInput' }
        activity: { $ref: '#/components/schemas/ActivityInput' }
        meal: { $ref: '#/components/schemas/MealInput' }
        weight: { $ref: '#/components/schemas/WeightInput' }
        reading: { $ref: '#/components/schemas/ReadingInput' }
        tracker: { $ref: '#/components/schemas/TrackerValueInput' }

    LogPatch:
      type: object
      description: Any of `LogInput`'s fields except `module`, `source` and `external_id`.
      properties:
        started_at: { type: string, format: date-time }
        ended_at: { type: [string, 'null'], format: date-time }
        minutes: { type: integer, minimum: 0, maximum: 1440 }
        note: { type: [string, 'null'], maxLength: 280 }
        private: { type: boolean }
        focus: { $ref: '#/components/schemas/FocusInput' }
        workout: { $ref: '#/components/schemas/WorkoutInput' }
        activity: { $ref: '#/components/schemas/ActivityInput' }
        meal: { $ref: '#/components/schemas/MealInput' }
        weight: { $ref: '#/components/schemas/WeightInput' }
        reading: { $ref: '#/components/schemas/ReadingInput' }
        tracker: { $ref: '#/components/schemas/TrackerValueInput' }

    FocusInput:
      type: object
      description: A block of focused work. `minutes` is the focused time (at least 1, at most 720).
      properties:
        about: { type: string, maxLength: 60, description: What it was for ("Landing copy"). }
        project_id: { type: string, format: uuid, description: One of the person's projects. }
        task_id: { type: string, format: uuid, description: A task in that project. }
        style: { type: string, enum: [free, pomodoro, past], default: free }
        rounds: { type: integer, minimum: 1, maximum: 48, description: Pomodoro rounds done. }

    WorkoutInput:
      type: object
      required: [exercises]
      description: |
        A training session. Exercises come from `/exercises`. Volume, sets, reps and personal records are worked out
        from the sets, as in the app (warm-ups count to volume, not to sets or reps). `minutes` defaults to the
        session's length.
      properties:
        title: { type: string, maxLength: 60, default: Workout }
        exercises:
          type: array
          minItems: 1
          maxItems: 40
          items:
            type: object
            required: [id, sets]
            properties:
              id: { type: string, examples: [bench_press] }
              sets:
                type: array
                minItems: 1
                maxItems: 50
                items:
                  type: object
                  properties:
                    kg: { type: number, minimum: 0, maximum: 1000 }
                    reps: { type: integer, minimum: 0, maximum: 1000 }
                    seconds: { type: integer, minimum: 0, maximum: 86400 }
                    metres: { type: number, minimum: 0, maximum: 100000 }
                    rpe: { type: number, minimum: 1, maximum: 10 }
                    warmup: { type: boolean, default: false }
                    at: { type: string, format: date-time, description: When the set was done. }

    ActivityInput:
      type: object
      required: [sport]
      description: |
        A run, walk, hike, ride or swim. Distance in km (`distance_km`), or metres (`distance_m`, natural for swims);
        `minutes` is moving time. Runs count as runs (the km challenge, km trophies); walks, rides and swims each keep
        their own distance.
      properties:
        sport: { type: string, enum: [run, trail_run, walk, hike, ride, mountain_bike, swim] }
        distance_km: { type: number, minimum: 0, maximum: 1000 }
        distance_m: { type: number, minimum: 0, maximum: 1000000 }
        climb_m: { type: number, minimum: 0, maximum: 20000 }
        title: { type: string, maxLength: 60 }
        effort: { type: integer, minimum: 1, maximum: 10 }
        route:
          type: object
          required: [polyline]
          description: |
            The route as a Google encoded polyline (precision 5). Others who may see the log see it with 200 m cut
            off each end unless the person chose otherwise.
          properties:
            polyline: { type: string, minLength: 4, maxLength: 400000 }
            breaks: { type: array, items: { type: integer, minimum: 1 }, description: Point indexes where it starts again after a pause. }
        map_hidden: { type: boolean, description: Keep the map off the log for everyone but its owner. }

    MealInput:
      type: object
      description: |
        A meal: `items`, or one set of totals (`kcal` and the macros), which becomes one item. Totals are worked out
        from the items. A meal never counts as showing up.
      properties:
        slot: { type: string, enum: [breakfast, lunch, dinner, snack], description: Defaults from the time of day. }
        name: { type: string, maxLength: 80, description: With totals, the item's name. }
        kcal: { type: number, minimum: 0, maximum: 10000 }
        protein_g: { type: number, minimum: 0, maximum: 1000 }
        carbs_g: { type: number, minimum: 0, maximum: 1000 }
        fat_g: { type: number, minimum: 0, maximum: 1000 }
        items:
          type: array
          minItems: 1
          maxItems: 20
          items:
            type: object
            required: [name, kcal]
            properties:
              name: { type: string, maxLength: 80 }
              grams: { type: number, minimum: 0, maximum: 5000 }
              kcal: { type: number, minimum: 0, maximum: 10000 }
              protein_g: { type: number, minimum: 0, maximum: 1000 }
              carbs_g: { type: number, minimum: 0, maximum: 1000 }
              fat_g: { type: number, minimum: 0, maximum: 1000 }

    WeightInput:
      type: object
      required: [kg]
      properties:
        kg: { type: number, minimum: 20, maximum: 400 }

    ReadingInput:
      type: object
      required: [pages]
      description: Pages read. With `book_id` (one of the person's books) the book's page moves on.
      properties:
        pages: { type: integer, minimum: 0, maximum: 2000 }
        book_id: { type: string, format: uuid }

    Signal:
      type: object
      required: [kind, started_at]
      properties:
        kind: { type: string, enum: [activity, motion, steps, stand, watch, presence] }
        device_id: { type: string, maxLength: 64, description: 'Your id for the device ("mac-mini-office").' }
        started_at: { type: string, format: date-time }
        ended_at: { type: string, format: date-time, description: At most 24 hours after started_at. }
        category: { type: string, pattern: '^[a-z][a-z_]{0,23}$', examples: [coding] }
        label: { type: string, maxLength: 80, examples: [Xcode] }
        value: { type: number, minimum: 0, maximum: 999999, description: 'steps: the count; others: as the kind says.' }
        meta: { type: object, description: 'Up to 1 KB of anything else.' }

    TrackerValueInput:
      type: object
      required: [tracker_id, value]
      properties:
        tracker_id: { type: string, format: uuid }
        value: { type: number, minimum: 0, maximum: 1000000000 }

    Tracker:
      type: object
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        unit: { type: [string, 'null'] }
        mode: { type: string, enum: [body, work, mind] }
        agg: { type: string, enum: [sum, max, last] }
        removed: { type: boolean }
        created_at: { type: string, format: date-time }
    TrackerInput:
      type: object
      properties:
        name: { type: string, minLength: 1, maxLength: 40 }
        unit: { type: [string, 'null'], maxLength: 16, examples: [glasses] }
        mode: { type: string, enum: [body, work, mind], default: mind }
        agg: { type: string, enum: [sum, max, last], default: sum, description: How a day's values add up. }

    Log:
      type: object
      required: [id, module, started_at, day, minutes, private, facts, source, created_at, editable_until]
      properties:
        id: { type: string, format: uuid }
        module: { $ref: '#/components/schemas/ModuleId' }
        started_at: { type: string, format: date-time }
        ended_at: { type: [string, 'null'], format: date-time }
        day: { type: string, format: date, description: The day it counts for, in the person's time zone. }
        minutes: { type: integer }
        private: { type: boolean }
        note: { type: [string, 'null'] }
        live: { type: boolean, description: Still happening (a session in progress in the app). }
        shows_up: { type: boolean }
        facts: { type: object, additionalProperties: { type: number }, examples: [{ km: 5.2, run_minutes: 28, activity_minutes: 28 }] }
        source:
          type: object
          properties:
            kind: { type: string, enum: [manual, recorded, import, api] }
            name: { type: [string, 'null'], description: The source or app name. }
            external_id: { type: [string, 'null'] }
            yours: { type: boolean, description: Written by this token's app (or source, for personal tokens). }
        created_at: { type: string, format: date-time }
        editable_until: { type: string, format: date-time }
        editable: { type: boolean }
        focus: { $ref: '#/components/schemas/FocusInput' }
        workout: { $ref: '#/components/schemas/WorkoutInput' }
        activity: { $ref: '#/components/schemas/ActivityInput' }
        meal: { $ref: '#/components/schemas/MealInput' }
        weight: { $ref: '#/components/schemas/WeightInput' }
        reading: { $ref: '#/components/schemas/ReadingInput' }
        tracker: { $ref: '#/components/schemas/TrackerValueInput' }
        split_into: { type: array, items: { type: string, format: uuid }, description: 'Focus only: the other pieces it landed in, around time already covered.' }
        health_day:
          type: object
          description: 'Daily modules (steps, sleep, heart, mindful): the day and its numbers (steps, step_km, flights, active_kcal, exercise_minutes, stand_hours, sleep_minutes, in_bed_minutes, resting_hr, hrv_ms, vo2max, mindful_minutes), and sleep {start, end}.'
    LogResult:
      allOf:
        - $ref: '#/components/schemas/Log'
        - type: object
          properties:
            outcome: { type: string, enum: [created, already, covered] }

    TokenRequest:
      type: object
      required: [grant_type, client_id]
      properties:
        grant_type: { type: string, enum: [authorization_code, refresh_token] }
        client_id: { type: string }
        client_secret: { type: string }
        code: { type: string }
        redirect_uri: { type: string }
        code_verifier: { type: string, minLength: 43, maxLength: 128 }
        refresh_token: { type: string }
    TokenResponse:
      type: object
      required: [access_token, token_type, expires_in, refresh_token, scope]
      properties:
        access_token: { type: string, examples: [ep_at_…] }
        token_type: { type: string, enum: [Bearer] }
        expires_in: { type: integer, examples: [3600] }
        refresh_token: { type: string, examples: [ep_rt_…] }
        scope: { type: string, examples: ['logs:read logs:write'] }

    App:
      type: object
      properties:
        client_id: { type: string, examples: [epc_3f9a1c0d2b7e4a6f8c1d] }
        name: { type: string }
        description: { type: [string, 'null'] }
        homepage_url: { type: [string, 'null'] }
        logo_url: { type: [string, 'null'] }
        redirect_uris: { type: array, items: { type: string } }
        confidential: { type: boolean }
        users: { type: integer, description: People connected now. }
        status: { type: string, enum: [development, in_review, approved, rejected, revoked], description: 'development and rejected: at most dev_max_users people; approved: anyone.' }
        dev_max_users: { type: [integer, 'null'] }
        review:
          type: [object, 'null']
          description: The latest review request.
          properties:
            status: { type: string, enum: [pending, approved, rejected, withdrawn] }
            admin_notes: { type: [string, 'null'] }
            created_at: { type: string, format: date-time }
            decided_at: { type: [string, 'null'], format: date-time }
        revoked: { type: boolean, description: Switched off by Endless Pursuit. }
        created_at: { type: string, format: date-time }
        client_secret: { type: string, description: Only when just made or rotated. Shown once. }
    AppInput:
      type: object
      properties:
        name: { type: string, minLength: 2, maxLength: 60 }
        description: { type: string, maxLength: 280 }
        homepage_url: { type: string, format: uri, description: https only. }
        logo_url: { type: string, format: uri, description: https only. A square picture. }
        redirect_uris:
          type: array
          minItems: 1
          maxItems: 10
          description: Exact matches. https; http only on 127.0.0.1, localhost or [::1] (desktop apps); or an app scheme with a dot (`com.example.app:/callback`).
          items: { type: string }
        confidential: { type: boolean, default: false, description: Only when creating. }

  examples:
    focus:
      summary: 50 minutes of focused work
      value:
        module: focus
        started_at: '2026-12-03T08:00:00Z'
        ended_at: '2026-12-03T08:55:00Z'
        minutes: 50
        source: desk-timer
        external_id: session-1842
        focus: { about: Landing copy, style: pomodoro, rounds: 2 }
    workout:
      summary: A push day
      value:
        module: training
        started_at: '2026-12-03T17:00:00Z'
        ended_at: '2026-12-03T17:58:00Z'
        workout:
          title: Push day
          exercises:
            - id: bench_press
              sets: [{ kg: 60, reps: 8, warmup: true }, { kg: 100, reps: 5 }, { kg: 100, reps: 4, rpe: 9 }]
            - id: push_up
              sets: [{ reps: 20 }, { reps: 18 }]
    activity:
      summary: A 5 km run with its route
      value:
        module: running
        started_at: '2026-12-03T06:30:00Z'
        minutes: 28
        external_id: garmin-17012345
        activity: { sport: run, distance_km: 5.2, climb_m: 40, title: Morning run, route: { polyline: '_p~iF~ps|U_ulLnnqC_mqNvxq`@' } }
    meal:
      summary: Lunch from totals
      value:
        module: nutrition
        meal: { slot: lunch, name: Chicken rice bowl, kcal: 640, protein_g: 45, carbs_g: 70, fat_g: 16 }
    weight:
      summary: A weigh-in
      value: { module: weight, weight: { kg: 80.4 } }
    reading:
      summary: 18 pages in 30 minutes
      value: { module: reading, minutes: 30, reading: { pages: 18 } }
    tracker:
      summary: Two glasses of water on a custom tracker
      value: { module: custom, tracker: { tracker_id: 6a1d1d2e-6f0b-4c9e-9d6a-0f3c3f1f5b10, value: 2 } }
