<!-- Generated file — do not edit.
     Source: docs/agent-api.md · synced by scripts/sync-public-docs.mjs -->

# Montage Agent API Reference

Use this reference to integrate with Montage programmatically via HTTP. The API is designed for reliable automation by AI agents, CLI tools, and bots.

> **Public docs:** this file is published verbatim at <https://www.usemontage.com/docs/agent-api.md> (synced by `npm run sync-public-docs`, which also runs on every build). The human-facing versions live at [/docs/agents](https://www.usemontage.com/docs/agents) (connect an agent) and [/docs/api](https://www.usemontage.com/docs/api) (endpoint reference), with an OpenAPI 3.1 spec at <https://www.usemontage.com/openapi.json>. **Edit this file, not the copy in `public/`.**

## Authentication

All API requests must include an `Authorization` header with a Bearer token:

```
Authorization: Bearer mk_live_…
```

API keys are created at https://www.usemontage.com/settings/api-keys (browser login required). Keys are shown **once** — save them immediately. Revoke keys on the same page at any time. Keys act as the user who created them.

Alternatively, use browser cookies (same auth as the web app).

## Base URL & Conventions

- **Base URL:** `https://www.usemontage.com`
- **Protocol:** HTTPS only
- **Response format:** JSON
- **Error format:** `{ "error": "<message>", ...extra fields }`

## Status Codes

| Code | Meaning |
|------|---------|
| 200  | Success |
| 400  | Validation error (bad input, missing fields) |
| 401  | Unauthorized (missing or invalid API key / session) |
| 402  | Insufficient credits or rate limit (daily publish limit); or `trial_required` — sandbox/guest accounts can't upload Tracks |
| 403  | Forbidden (needs YouTube auth, insufficient permissions) |
| 404  | Not found (job, montage, channel ID) |
| 409  | Conflict (publish intent already uploading or published; intent in the wrong state to cancel/retry) |
| 429  | Rate limited (too many active jobs, requests/hour exceeded). Includes `Retry-After` header. |
| 500  | Server error |

## Rate Limits

Enforced per API key / user:

| Limit | Value |
|-------|-------|
| Active concurrent jobs | 10 |
| Job creation rate | 20 per hour |
| Publish rate | 25 per hour |
| Audio presign rate | 200 per hour |
| Track upload rate | 200 per hour (separate bucket from audio presign) |

Hitting a limit returns 429 with `Retry-After` header (seconds to wait). Respect this header.

## End-to-end agent flow

A complete run, copy-pasteable. Assumes `MONTAGE_API_KEY` is set. Every step is
explained in full under [Endpoint Reference](#endpoint-reference).

```bash
API=https://www.usemontage.com
AUTH="Authorization: Bearer $MONTAGE_API_KEY"

# 1. Preflight — confirm subscription, credits, and a connected channel.
curl -sS "$API/api/me" -H "$AUTH"
#    Proceed only if subscription.status is active|trialing,
#    credits.balance >= credits.costPerVideo, and youtubeChannels is non-empty.

# 2. Upload the audio. Under 4 MB: straight to the API domain (no storage egress).
FILE_KEY=$(curl -sS -X POST "$API/api/upload/audio" -H "$AUTH" \
  -F "audio=@beat.mp3" | jq -r .fileKey)
#    Over 4 MB: presign, then PUT to the returned URL with NO auth header —
#    see POST /api/upload/audio/presign.

# 3. (Optional) Reuse a saved metadata preset.
curl -sS "$API/api/youtube/templates" -H "$AUTH"

# 4. Schedule the render. Spends credits. NOT idempotent — persist jobId now.
JOB_ID=$(curl -sS -X POST "$API/api/montage/schedule" -H "$AUTH" \
  -H "Content-Type: application/json" \
  -d "{\"title\":\"Dark Trap Type Beat\",
       \"audioStoragePath\":\"$FILE_KEY\",
       \"video_source_type\":\"youtube\",
       \"source_youtube_url\":\"https://www.youtube.com/watch?v=VIDEO_ID\",
       \"startTime\":30,\"endTime\":150}" | jq -r .jobId)

# 5. Poll every 10s until status is complete or error (give up after 30 min).
curl -sS "$API/api/jobs/$JOB_ID" -H "$AUTH"
#    On complete, read montage.id:
MONTAGE_ID=$(curl -sS "$API/api/jobs/$JOB_ID" -H "$AUTH" | jq -r .montage.id)

# 6. (Optional) Attach a custom thumbnail before publishing.
curl -sS -X POST "$API/api/upload/thumbnail" -H "$AUTH" \
  -F "montageId=$MONTAGE_ID" -F "file=@thumb.jpg"
#    -> { "success": true, "thumbnailUrl": "https://…" }  (max 5 MB)
#    It also becomes the Visual's library thumbnail. Add -F "kind=publish" for a YouTube-only
#    thumbnail (e.g. one with text burned in) that leaves the library thumbnail as it is.

# 7. Queue the YouTube upload. Safe to retry on network errors; returns 409 once the
#    upload has started or finished, so it never publishes the same video twice.
INTENT_ID=$(curl -sS -X POST "$API/api/publish/intent" -H "$AUTH" \
  -H "Content-Type: application/json" \
  -d "{\"montageId\":\"$MONTAGE_ID\",
       \"channelId\":\"UCxxxxxxxxxxxxx\",
       \"title\":\"Dark Trap Type Beat\",
       \"description\":\"Free for non-profit use.\",
       \"tags\":\"type beat,trap\",
       \"privacy\":\"public\"}" | jq -r .intentId)

# 8. Poll every 15s until published or error. Note the param is `id`, not `intentId`.
curl -sS "$API/api/publish/intent?id=$INTENT_ID" -H "$AUTH"
#    On published: intents[0].youtubeUrl is the live video.
```

**Client requirements:** none beyond HTTP. No User-Agent gating exists on any `/api/*`
route — authenticate with `Authorization: Bearer <key>` from any standard HTTP library.
Send `Content-Type: application/json` on JSON bodies.

**Error codes, and what an agent should do:**

| Code | Meaning | Action |
|------|---------|--------|
| 400 | Validation error | Fix the request. Don't retry unchanged. |
| 401 | Bad/revoked/expired key | Stop. Tell the human. |
| 402 | Out of credits | **Permanent.** Stop. Never retry. |
| 403 | YouTube not connected (`needsAuth: true`) | **Permanent.** Send the human to `/connections`. |
| 404 | Not found or not yours | Stop. |
| 409 | Publish already uploading or live (`code`) | `already_published`: done, report `intents[].youtubeUrl`. `publish_in_progress`: keep polling. Never re-post. |
| 413 | Upload body too large | Use the presign flow. |
| 429 | Rate limited | Wait `Retry-After` seconds exactly. |
| 5xx | Server error | Retry 3× with 1s/3s/9s backoff. |

**Job status lifecycle:** `pending → downloading → processing → uploading → complete`,
or `error` from any stage. Only `complete` and `error` are terminal; `complete` populates
`montage`, `error` populates `errorMessage`. Retry a failed job with
`POST /api/jobs/retry` — no extra credits.

**Publish status lifecycle:** `queued → publishing → published`, or `error` / `cancelled`.
Only `published`, `error`, and `cancelled` are terminal. `published` populates
`youtubeVideoId` and `youtubeUrl`.

---

## Happy Path: 6 API Calls

Create and publish a video in 6 calls:

### 1. Preflight check

```bash
curl -X GET https://www.usemontage.com/api/me \
  -H "Authorization: Bearer mk_live_…"
```

Response:
```json
{
  "userId": "550e8400-e29b-41d4-a716-446655440000",
  "email": "user@example.com",
  "authMethod": "api_key",
  "subscription": {
    "status": "active",
    "currentPeriodEnd": "2026-10-07T00:00:00Z"
  },
  "credits": {
    "balance": 95,
    "costPerVideo": 5
  },
  "youtubeChannels": [
    {
      "id": "ch-uuid",
      "channelId": "UCxxxxxxxxxxxxx",
      "channelName": "My Beat Channel",
      "connectedAt": "2026-08-01T12:00:00Z"
    }
  ],
  "activeJobs": 0,
  "limits": {
    "maxConcurrentJobs": 10,
    "maxClipSeconds": 60,
    "maxAudioBytes": 209715200
  }
}
```

Check: `subscription.status` is "active" or "trialing", `credits.balance >= costPerVideo`, `youtubeChannels` is non-empty.

### 2. Get presigned URL for audio upload

```bash
curl -X POST https://www.usemontage.com/api/upload/audio/presign \
  -H "Authorization: Bearer mk_live_…" \
  -H "Content-Type: application/json" \
  -d '{
    "filename": "beat.mp3",
    "filetype": "audio/mpeg",
    "filesize": 5242880
  }'
```

Response:
```json
{
  "presignedUrl": "https://r2.example.com/uploads/…?X-Amz-Signature=…",
  "fileKey": "audio/uploads/2026/09/beat-abc123.mp3"
}
```

### 3. Upload audio to presigned URL

```bash
curl -X PUT \
  -H "Content-Type: audio/mpeg" \
  --data-binary @beat.mp3 \
  "https://r2.example.com/uploads/…?X-Amz-Signature=…"
```

No response body on success (204 No Content).

### 4. Create job (schedule render)

```bash
curl -X POST https://www.usemontage.com/api/montage/schedule \
  -H "Authorization: Bearer mk_live_…" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "My Beat #5",
    "audioStoragePath": "audio/uploads/2026/09/beat-abc123.mp3",
    "video_source_type": "youtube",
    "source_youtube_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    "startTime": 30,
    "endTime": 150
  }'
```

Response:
```json
{
  "success": true,
  "jobId": "job-uuid-here",
  "creditsRemaining": 90
}
```

### 5. Poll job status

```bash
curl -X GET https://www.usemontage.com/api/jobs/job-uuid-here \
  -H "Authorization: Bearer mk_live_…"
```

Response (polling):
```json
{
  "id": "job-uuid-here",
  "title": "My Beat #5",
  "status": "downloading",
  "progress": 45,
  "createdAt": "2026-09-07T10:00:00Z",
  "updatedAt": "2026-09-07T10:01:30Z",
  "input": {
    "videoSourceType": "youtube",
    "sourceYoutubeUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    "startTime": 30,
    "endTime": 150
  },
  "publishIntents": []
}
```

Poll every 10 seconds until `status` is `complete` or `error` (timeout: 30 minutes).

Response (complete):
```json
{
  "id": "job-uuid-here",
  "title": "My Beat #5",
  "status": "complete",
  "progress": 100,
  "createdAt": "2026-09-07T10:00:00Z",
  "updatedAt": "2026-09-07T10:15:00Z",
  "montage": {
    "id": "montage-uuid",
    "title": "My Beat #5",
    "videoUrl": "https://cdn.example.com/montages/…/video.mp4",
    "thumbnailUrl": null,
    "youtubeVideoId": null,
    "createdAt": "2026-09-07T10:15:00Z"
  },
  "input": { … },
  "publishIntents": []
}
```

### 6. Publish to YouTube

```bash
curl -X POST https://www.usemontage.com/api/publish/intent \
  -H "Authorization: Bearer mk_live_…" \
  -H "Content-Type: application/json" \
  -d '{
    "montageId": "montage-uuid",
    "channelId": "UCxxxxxxxxxxxxx",
    "title": "My Beat #5 [Prod. Me]",
    "description": "Free beat. Use at will.",
    "tags": "beat,free,lofi",
    "privacy": "public"
  }'
```

Response:
```json
{
  "success": true,
  "intentId": "intent-uuid",
  "intentIds": {
    "full": "intent-uuid"
  },
  "status": "queued"
}
```

Poll publish status:

```bash
curl -X GET 'https://www.usemontage.com/api/publish/intent?id=intent-uuid' \
  -H "Authorization: Bearer mk_live_…"
```

Response (queued):
```json
{
  "intents": [
    {
      "id": "intent-uuid",
      "kind": "youtube_full",
      "status": "queued",
      "jobId": null,
      "montageId": "montage-uuid",
      "channelId": "UCxxxxxxxxxxxxx",
      "title": "My Beat #5 [Prod. Me]",
      "privacy": "public",
      "youtubeVideoId": null,
      "youtubeUrl": null,
      "errorMessage": null,
      "attemptCount": 0,
      "createdAt": "2026-09-07T10:20:00Z",
      "updatedAt": "2026-09-07T10:20:00Z",
      "completedAt": null
    }
  ]
}
```

Poll every 15 seconds until `status` is `published` or `error` (timeout: 30 minutes). Success response:

```json
{
  "intents": [
    {
      "id": "intent-uuid",
      "kind": "youtube_full",
      "status": "published",
      "youtubeVideoId": "dQw4w9WgXcQ",
      "youtubeUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
      "completedAt": "2026-09-07T10:35:00Z",
      …
    }
  ]
}
```

---

## Endpoint Reference

### Account & Preflight

#### `GET /api/me`

Returns the current user's account, subscription, credits, and connected YouTube channels. Use this to preflight: verify subscription, check credit balance, and pick a `channelId` for publishing.

**Response:**
```json
{
  "userId": "uuid",
  "email": "user@example.com",
  "authMethod": "api_key" | "cookie",
  "subscription": {
    "status": "active" | "trialing" | "canceled" | null,
    "currentPeriodEnd": "2026-10-07T00:00:00Z" | null
  },
  "credits": {
    "balance": 95,
    "costPerVideo": 5
  },
  "youtubeChannels": [
    {
      "id": "uuid",
      "channelId": "UCxxxxxxxxxxxxx",
      "channelName": "My Channel",
      "connectedAt": "2026-08-01T12:00:00Z"
    }
  ],
  "activeJobs": 0,
  "limits": {
    "maxConcurrentJobs": 10,
    "maxClipSeconds": 60,
    "maxAudioBytes": 209715200
  }
}
```

---

#### `GET /api/youtube/accounts`

List connected YouTube channels.

**Response:**
```json
{
  "channels": [
    {
      "id": "uuid",
      "channelId": "UCxxxxxxxxxxxxx",
      "channelName": "My Channel",
      "connectedAt": "2026-08-01T12:00:00Z",
      "avatarUrl": "https://yt3.ggpht.com/…"
    }
  ]
}
```

`avatarUrl` is the channel's current YouTube avatar, read live from YouTube (cached for 10 minutes);
`null` when it can't be fetched.

---

#### `GET /api/youtube/templates`

List the caller's saved YouTube detail templates — the reusable title/description/tags
presets from the publish page. Lets an agent reuse a producer's own presets instead of
inventing metadata.

**Response:**
```json
{
  "templates": [
    {
      "id": "uuid",
      "name": "Default type beat",
      "title": "{artist} type beat - \"{name}\"",
      "description": "Free for non-profit use…",
      "tags": "type beat,trap,free beat",
      "isPublic": true,
      "allowComments": true,
      "createdAt": "2026-08-01T12:00:00Z",
      "updatedAt": "2026-08-01T12:00:00Z"
    }
  ]
}
```

`tags` is already the comma-separated string `POST /api/publish/intent` expects. Read-only —
creating and editing templates stays in the web UI.

---

#### `GET /api/credits`

Get current credit balance and recent ledger.

**Response:**
```json
{
  "balance": 95,
  "recentLedger": [
    {
      "id": "ledger-uuid",
      "delta": -5,
      "reason": "video_render",
      "created_at": "2026-09-07T10:15:00Z",
      "balance_after": 95
    }
  ]
}
```

---

#### `GET /api/profile`

Get the caller's own producer profile (requirements §26) — the page artists you've sent a pack to
see at `usemontage.com/u/<slug>`. Never 404s for a missing row: a producer who hasn't touched
Settings → Profile yet just gets empty/null fields.

**Response:**
```json
{
  "profile": {
    "id": "uuid",
    "name": "Dallas Rose",
    "avatarUrl": "https://…" ,
    "contactEmail": "dallas@dallasrose.com",
    "links": ["https://instagram.com/dallasrose", "https://dallasrose.com"],
    "pro": "BMI",
    "ipi": "00123456789",
    "slug": "dallasrose",
    "allowDownloads": false,
    "updatedAt": "2026-09-20T12:00:00Z"
  }
}
```

**Status codes:** 401 unauthorized.

---

#### `PATCH /api/profile`

Update the caller's producer profile. Every field is optional — only fields present in the body
are validated and written.

**Request** (every field optional):
```json
{
  "name": "Dallas Rose",
  "avatarUrl": "https://…" ,
  "contactEmail": "dallas@dallasrose.com",
  "links": ["https://instagram.com/dallasrose"],
  "pro": "BMI",
  "ipi": "00123456789",
  "slug": "dallasrose",
  "allowDownloads": true
}
```

**Validation:** `name` 1–120 chars. `contactEmail` a valid email, or `null` to clear it. `links`
up to 10 URLs (≤ 300 chars each). `pro` one of `BMI`, `ASCAP`, `SESAC`, `GMR`, `SOCAN`, `PRS`,
`Other`, or `null`. `ipi` ≤ 32 chars or `null`. `slug` 3–40 lowercase letters, digits or hyphens,
can't start or end with a hyphen (`^[a-z0-9](?:[a-z0-9-]{1,38}[a-z0-9])$`), unique, or `null` to
remove your profile address. Changing the slug means links already shared with the old one stop
working. `allowDownloads` a boolean (default `false`: stream-only until you opt in): whether signed-in Artists can download the
original file of any Track in their pack or on your profile; `true` turns downloads on; `false` keeps everything stream-only.

**Response — 200:** the updated profile (same shape as `GET /api/profile`).

**Status codes:** 400 invalid field, 401 unauthorized, 409 `slug_taken` — "That address is taken".

---

### Audio Upload

#### `POST /api/upload/video` and `POST /api/upload/image`

Upload a visual source for `POST /api/montage/schedule` (`video_source_type` `upload` / `image`). Send
`multipart/form-data` with the file in `file` (`upload/video` also takes a raw `video/*` body). Video
≤ 500 MB, image ≤ 20 MB (`.jpg .jpeg .png .webp .gif`, checked by content). Rate limited per user.

**Response:** `{ "success": true, "tempPath": "…" }` — pass `tempPath` as `uploaded_video_path` /
`uploaded_image_path`. **Status codes:** 400 invalid file, 401, 429.

---

#### `POST /api/upload/audio`

Upload audio bytes directly to the API domain. Use this when the caller cannot reach
`*.r2.cloudflarestorage.com` — sandboxed agents with egress allowlists usually can't.
Everything stays on `www.usemontage.com`.

**Size ceiling:** the host rejects request bodies larger than ~4.5 MB *before* this
handler runs, returning a plain-text `413 FUNCTION_PAYLOAD_TOO_LARGE` rather than JSON.
Send at most **4 MB** here (advertised as `limits.maxDirectUploadBytes` in `GET /api/me`);
use the presign flow below for anything larger. A 3-minute MP3 above ~192 kbps will
exceed this.

Two request shapes are accepted:

```bash
# multipart/form-data — field "audio" (the legacy field name "file" also works)
curl -X POST https://www.usemontage.com/api/upload/audio \
  -H "Authorization: Bearer mk_live_…" \
  -F "audio=@beat.mp3"
```

```bash
# raw body with an audio/* content type
curl -X POST https://www.usemontage.com/api/upload/audio \
  -H "Authorization: Bearer mk_live_…" \
  -H "Content-Type: audio/mpeg" \
  -H "x-filename: beat.mp3" \
  --data-binary @beat.mp3
```

**Response:**
```json
{
  "success": true,
  "fileKey": "audio/1757241600000-8f14e45f-beat.mp3",
  "audioStoragePath": "audio/1757241600000-8f14e45f-beat.mp3",
  "file": {
    "path": "audio/1757241600000-8f14e45f-beat.mp3",
    "url": "https://cdn.usemontage.com/audio/…",
    "original_name": "beat.mp3",
    "sanitized_name": "beat.mp3",
    "storage_type": "r2"
  }
}
```

`fileKey`, `audioStoragePath`, and `file.path` are all the same string — pass any of them
to `POST /api/montage/schedule` as `audioStoragePath`. **Uploading costs no credits on
either path** — only rendering does.

**Validation:** `Content-Type` (or the multipart part's type) must be an audio type —
`audio/mpeg`, `audio/mp3`, `audio/wav`, `audio/wave`, `audio/x-wav`, `audio/flac`,
`audio/x-flac`, `audio/aac`, `audio/ogg`, `audio/opus`, `audio/mp4`, `audio/m4a`,
`audio/x-m4a`. Also subject to your account storage quota. Shares the 200/hour upload
rate limit with presign.

**Status codes:** 400 invalid content type / quota exceeded, 401 unauthorized,
429 rate limited, 500 storage failure. A body over the host limit returns a plain-text
413 that never reaches this handler.

> Storage note: uploads go to R2, falling back to Supabase Storage if R2 is unavailable;
> `file.storage_type` tells you which was used. Either way the worker can read it.

---

#### `POST /api/upload/audio/presign`

Get a presigned URL to upload audio directly to storage. Client must then `PUT` raw bytes to the returned URL.

Use this for files over 4 MB, or from browsers. The `PUT` goes to an R2 host, so callers
whose network blocks third-party storage should use `POST /api/upload/audio` instead.

**Request:**
```json
{
  "filename": "beat.mp3",
  "filetype": "audio/mpeg",
  "filesize": 5242880
}
```

**Validation:**
- `filesize` ≤ 209,715,200 bytes (200 MB)
- `filename` ext in: `.mp3`, `.wav`, `.flac`, `.aac`, `.ogg`, `.m4a`, `.opus`

**Response:**
```json
{
  "presignedUrl": "https://r2.example.com/uploads/…?X-Amz-Signature=…",
  "fileKey": "audio/uploads/2026/09/beat-abc123.mp3"
}
```

**Upload to URL:**
```bash
curl -X PUT \
  -H "Content-Type: audio/mpeg" \
  --data-binary @beat.mp3 \
  "$PRESIGNED_URL"
```

Returns 204 No Content on success.

---

### Track Upload (v2)

Two-step flow for the Tracks library (architecture §4): hash the file locally, check for
duplicates and get a presigned URL, `PUT` the bytes, then confirm. **A Track row is created
only by the confirm call** — never before, so a browser tab closed mid-upload never leaves an
orphan record. `POST /api/upload/audio` and `/presign` above are unrelated: they feed the older
render pipeline and don't create Tracks.

#### `POST /api/tracks/uploads`

Hash the file client-side (SHA-256) before calling this.

**Request:**
```json
{
  "filename": "Heavy Artillery (final mix).wav",
  "bytes": 5242880,
  "mime": "audio/wav",
  "hash": "…64 lowercase hex characters…"
}
```

**Validation:**
- `filename`: 1–255 characters, extension one of `.wav`, `.mp3`, `.aif`, `.aiff`, `.flac`
- `mime`: `audio/wav`, `audio/x-wav`, `audio/wave`, `audio/mpeg`, `audio/mp3`, `audio/aiff`,
  `audio/x-aiff`, `audio/flac`, `audio/x-flac` — an empty or unrecognized mime is accepted and
  normalized from the extension instead (browsers are inconsistent about wav/aiff mimes)
- `bytes`: 1–209,715,200 (200 MB)
- `hash`: 64-character lowercase hex SHA-256
- `replaceTrackId` (optional UUID): after the user confirms replacement, pass the existing
  Track's id here and in the confirm request. You must own it. A matching hash for that Track
  then receives an upload URL instead of a duplicate verdict.

**Response — exact duplicate** (same file content already in your library; nothing to upload):
```json
{ "duplicate": { "trackId": "…", "title": "Heavy Artillery" } }
```

**Response — new upload:**
```json
{
  "upload": {
    "key": "audio/<userId>/<uuid>.wav",
    "url": "https://…?X-Amz-Signature=…",
    "expiresAt": "2026-09-27T12:15:00.000Z"
  },
  "similar": [
    { "trackId": "…", "title": "Heavy Artillery", "score": 0.82 }
  ]
}
```

`similar` lists Tracks whose cleaned title resembles this filename — **flagged, not
skipped**. `upload.url` is valid for **15 minutes**; `PUT` the raw bytes to it with
`Content-Type` set to the mime this upload normalizes to from the filename's extension —
`.wav`→`audio/wav`, `.mp3`→`audio/mpeg`, `.aif`/`.aiff`→`audio/aiff`, `.flac`→`audio/flac` — not
necessarily what you sent. The response does not echo this back; derive it from the extension
yourself (the confirm call below expects the same value).

**Status codes:** 400 invalid filename/mime/bytes/hash, 401 unauthorized, 402
`trial_required` (sandbox/guest accounts can't upload — the trial signup handles this), 429
rate limited (its own 200/hour/user limit, separate from `/api/upload/audio*`), 404 replacement
Track not found or not owned by you.

---

#### `POST /api/tracks/uploads/confirm`

Call this after the `PUT` to the presigned URL succeeds. This is the only call that creates
a Track.

**Request:**
```json
{
  "key": "audio/<userId>/<uuid>.wav",
  "filename": "Heavy Artillery (final mix).wav",
  "bytes": 5242880,
  "mime": "audio/wav",
  "hash": "…64 lowercase hex characters…",
  "title": "Heavy Artillery",
  "apply": { "genreId": "…", "tagIds": ["…"], "artistId": "…" }
}
```

`title` is optional — omit it to derive one from the filename (extension stripped,
underscores/dashes turned into spaces, whitespace collapsed). `apply` ("Apply to these") is
optional; every id in it is checked against your own Genres/Tags/Artists and silently skipped
if it doesn't belong to you or is the wrong property.

To replace existing audio, include `replaceTrackId` (the same owned Track id used for
presigning). The server confirms the uploaded file first, then updates that Track's audio
without creating another library entry. Its title, tags, artist/pack relationships and play
history stay intact; `title` and `apply` are ignored for replacement. Waveform and duration
are regenerated. No version history is created.

**Response — 200, audio replaced:**
```json
{ "track": { "id": "…existing Track id…", "title": "Heavy Artillery", "created_at": "2026-09-27T12:00:03.000Z" }, "replaced": true }
```

**Response — 201 Created:**
```json
{ "track": { "id": "…", "title": "Heavy Artillery", "created_at": "2026-09-27T12:00:03.000Z" } }
```

**Response — 200, duplicate** (another upload of the same file won a race with this one):
```json
{ "duplicate": { "trackId": "…", "title": "Heavy Artillery" } }
```

**Status codes:** 400 invalid input, or a `key` that isn't your own upload prefix, 401
unauthorized, 402 `trial_required`, 409 `upload_missing` (nothing at that key yet) or
`size_mismatch` (the object's size doesn't match `bytes`), a concurrent replacement, or audio
already used by a different Track; 404 replacement Track not found; 500 storage/database failure.

---

### Tracks (v2)

The Tracks library (architecture §7, requirements §3, §19). Filtering is generic:
`{property, op, value}` — every Track property filters the same way. Artists are added and
removed through tagging (which writes events, architecture §3.3), never by setting a list
directly.

**Common error mapping** across every route below: `artist_not_found` / `pack_not_found` /
`track_not_found` → 404, `sign_in_required` → 401 (should not happen with a valid key),
`cross_owner_reference` → 400 (an id from outside your own library). Anything else is a 500
with a generic message; the real error is only in the server log.

#### `GET /api/tracks`

List your Tracks, with filters, search, sort and keyset pagination — all server-side.

**Query parameters:**

| Param | Meaning |
|-------|---------|
| `filter` | JSON array of `{property, op, value}`. Properties: `title`, `bpm`, `key`, `scale`, `genre`, `artist`, `tag`, `uploaded`, `status`, `profile`. |
| `q` | Title search (case-insensitive substring) |
| `sort` | `created_at` (default), `title`, `bpm`, `key`, `scale`, or `genre` |
| `dir` | `asc` or `desc` (default `desc`) |
| `cursor` | Opaque; pass back the previous page's `next_cursor` |
| `limit` | Default 100, max 500 |
| `group_by` | `artist`, `genre`, `key`, `scale` or `tag`: return **folders** instead of Tracks (below). `sort`, `dir`, `cursor` and `limit` are ignored |

**Filter ops by property:**

| Property | Ops | Value |
|----------|-----|-------|
| `title` | `contains`, `is` | string |
| `bpm` | `is`, `between`, `gte`, `lte` | number, or `[min, max]` for `between` |
| `key` | `is`, `any_of`, `is_empty` | integer 0–11, or an array of them |
| `scale` | `is`, `any_of`, `is_empty` | one of the 13 scales, or an array |
| `genre` | `is`, `is_not`, `any_of`, `is_empty` | Genre id, or an array |
| `artist` | `is`, `is_not`, `any_of`, `is_empty` | Artist id, or an array |
| `tag` | `is`, `any_of`, `is_not`, `is_empty` | Tag id, or an array |
| `uploaded` | `before`, `after`, `within_days` | ISO date, or a number of days |
| `status` | `is` | `"taken"`, `"in_use"`, or `"available"` |
| `profile` | `is` | boolean |

Example: `?filter=[{"property":"artist","op":"is","value":"<artist-id>"},{"property":"bpm","op":"between","value":[120,140]}]`

An unknown property, an op that doesn't apply to it, or a malformed value is a 400 naming the
problem.

**Response:**
```json
{
  "tracks": [ { "id": "…", "title": "Private Life", "bpm": 142, "key": 6, "scale": "minor",
                "genre_id": "…", "genre": "Dark Hard Trap", "tag_ids": ["…"], "tags": ["dark", "piano"],
                "artist_ids": ["…"], "artists": ["Future"], "in_use_by": [], "removed_by": [],
                "taken_by": null, "taken_by_label": null, "show_on_profile": false,
                "favorites": 1, "duration_ms": 178000, "peaks": [0, 12, …], "audio_mime": "audio/wav",
                "audio_bytes": 5242880, "created_at": "…", "updated_at": "…" } ],
  "total": 216,
  "next_cursor": "eyJ2IjoiMjAyNi0…"
}
```

`in_use_by` and `removed_by` are owner-only fields — no other role ever receives them
(principles §2.5). `total` reflects the same filters, computed without the cursor.

**Folders — `?group_by=<property>`.** The same search and filters, grouped by one list-valued
property instead of listed (requirements §3.12). A Track with several values (Artist, Tags) counts in
each of its folders; Tracks with no value collect in one folder with `"value": null`, listed last.
Key and Scale folders are in their list order, everything else A–Z. To list a folder's Tracks, call
`GET /api/tracks` again with the folder as one more filter: `{"property": <group_by>, "op": "is",
"value": <value>}`, or `"op": "is_empty"` for the `null` folder.

```json
{
  "folders": [ { "value": "…", "label": "Future", "count": 4, "cover_track_ids": ["…", "…"] },
               { "value": null, "label": "No artist", "count": 2, "cover_track_ids": ["…"] } ],
  "total": 10,
  "counts": { "artist": 5, "genre": 3, "key": 7, "scale": 4, "tag": 8 },
  "truncated": false
}
```

`total` is the Tracks matching the filters (each counted once); `counts` is how many folders each
property would make. Only the newest 5000 matches are grouped; `truncated` says when there were more.
Folders are a view: nothing is stored, and a folder isn't a Pack.

**Status codes:** 400 invalid filter/sort/cursor/limit/group_by, 401 unauthorized, 429 rate limited.

---

#### `GET /api/tracks/:id`

One Track plus per-artist relationship detail (owner only).

**Response:**
```json
{
  "id": "…", "title": "Private Life", "…": "…all TrackRow fields…",
  "relationships": [
    { "artist_id": "…", "artist": "Future", "tagged": true, "removed_at": null,
      "favorited_at": "2026-09-20T…", "using_since": "2026-09-24T…",
      "use_source": "pack" }
  ],
  "plays": 14
}
```

`use_source` is `"profile"`, `"pack"` (from the Artist's pack), or `null`. `plays` is the all-time play count across every pack/profile the Track has been in.

**Status codes:** 401 unauthorized, 404 not found (or not yours).

---

#### `PATCH /api/tracks/:id`

Edit a Track's properties, or add/remove Artists.

**Request** (every field optional):
```json
{
  "title": "Private Life", "bpm": 142, "key": 6, "scale": "minor",
  "genre_id": "…", "tag_ids": ["…"],
  "add_artist_ids": ["…"], "remove_artist_ids": ["…"],
  "show_on_profile": true
}
```

**Validation:** `title` 1–200 chars; `bpm` 20–400 or `null`; `key` integer 0–11 or `null`;
`scale` one of the 13 scales or `null`; `genre_id`/`tag_ids` must be your own Genre/Tag values.
`genre_id` replaces the Track's single Genre; `tag_ids` replaces the whole Tag set.

`add_artist_ids` tags each Artist on this Track (`bulk_tag_artist`); an Artist who removed this
Track before is skipped, not an error (requirements §3.7) — its count comes back in `skipped`.
`remove_artist_ids` untags each Artist (`untag_artist`): the Track leaves every one of their
packs.

**Response — 200:** the updated Track (`TrackRow`), plus `skipped: {removed, taken}` when an
`add_artist_ids` entry was skipped.

**Response — 409** (only when nothing else in the request changed and every requested Artist
add was skipped because they'd removed this Track before):
```json
{ "error": "artist_removed", "artist": "<artist id>", "skipped": { "removed": 1, "taken": 0 } }
```

**Status codes:** 400 invalid field, 401 unauthorized, 404 not found, 409 `artist_removed`.

---

#### `DELETE /api/tracks/:id`

Deletes the Track. Meant to be a manual, confirmed action in the UI — Montage never deletes
Tracks automatically (principles §2.7). The audio object in storage is **not** deleted.

**Status codes:** 401 unauthorized, 404 not found.

---

#### `POST /api/tracks/bulk`

Edit many Tracks at once: everything you passed as `ids`, or everything matching `filter` (+
optional `q`) — the same filter mapping `GET /api/tracks` uses. Resolving by filter/q is capped
at 5000 Tracks.

**Request:**
```json
{
  "filter": [{ "property": "genre", "op": "is", "value": "<genre-id>" }],
  "op": "add_artist",
  "value_id": "<artist-id>"
}
```

`op` is one of `add_artist`, `remove_artist`, `add_tag`, `remove_tag`, `set_genre`,
`show_on_profile`, `hide`. `value_id` is the Artist/Tag/Genre id the op acts on — required for
every op except `show_on_profile`/`hide`, and optional for `set_genre` (omit to clear the Genre
on every matched Track).

**Response:**
```json
{ "matched": 12, "changed": 10, "skipped_removed": 2, "skipped_taken": 0 }
```

`skipped_removed`/`skipped_taken` are only present for `add_artist` (requirements §3.7: "2
skipped — Future removed these before").

**Status codes:** 400 invalid op/value_id/filter, or neither `ids` nor `filter`/`q` given, 401
unauthorized, 404 the Artist/Tag/Genre in `value_id` isn't yours.

---

#### `POST /api/tracks/:id/restore`

Owner Restore (requirements §3.4): undoes an Artist's removal of this Track. Clears the removal
**and** that Artist's old favorite/use on it — a fresh start. Does not re-tag the Artist.

**Request:** `{ "artist_id": "<artist-id>" }`

**Status codes:** 400 missing/invalid `artist_id`, 401 unauthorized, 404 Track or Artist not
found.

---

#### `POST /api/tracks/:id/taken`

Marks or clears "Taken by" (requirements §24). Ends every other Artist's in-use state on this
Track and tells every pack that currently shows it what happened.

**Request:** `{ "artist_id": "<artist-id>" }` to mark, or `{ "artist_id": null }` to clear.

**Status codes:** 400 invalid `artist_id`, 401 unauthorized, 404 Track or Artist not found.

---

#### `POST /api/tracks/:id/clear-use`

Clears one Artist's "in use" mark on a Track without taking it (architecture §19 "Owner clears an
artist's use without marking the track taken") — the small **Clear** next to **Mark taken** on
each in-use row in Track Edit.

**Request:** `{ "artist_id": "<artist-id>" }`

**Status codes:** 400 missing/invalid `artist_id`, 401 unauthorized, 404 Track or Artist not
found.

---

#### `GET /api/stream/:trackId`

Resolves a Track's audio to a **302 redirect** to a short-lived signed URL — never publicly
addressable. (An Artist's one-tap download of the original file is `POST /api/stream/:trackId/download`,
under Pack links below.) Every play (owner preview, a Pack link, a producer
profile) goes through here (architecture §4, principles §6.2).

**Query:** `?via=` required — `owner` (an agent/producer playing their own library), `owned`,
`pack:<12-char token>`, or `profile:<slug>`. An agent playing its own Track uses `via=owner`.

```bash
curl -sS -D - -o /dev/null "$API/api/stream/<trackId>?via=owner" -H "$AUTH"
# Location: https://…r2…?X-Amz-Signature=…  (valid 5 minutes)
```

**Status codes:** 302 redirect on success (`Location` header, `Cache-Control: no-store`), 404
`not_found` (bad id/via, or the RPC's own access check fails — same response either way,
principles §2.4), 429 `rate_limited` (120/min per IP; a `pack:` token also gets its own
600/hour bucket), 503 `stream_unavailable` (signing failed).

---

#### `GET /api/values`

Lists your Artist/Genre/Tag values — the growable, de-duplicated lists behind every property's
autocomplete (requirements §3.2).

**Query:** `?property=artist|genre|tag&q=<search>` — `q` matches the label or its normalized
form (case, spacing and punctuation-insensitive), limit 50, ordered by label.

**Response:** `{ "values": [{ "id": "…", "property": "artist", "label": "Future" }] }`

**Status codes:** 400 invalid `property`, 401 unauthorized.

---

#### `POST /api/values`

Adds a value, or resolves to the existing one if the label normalizes to a match already in
your list ("21 savage" / "Lil. Baby" both resolve to the same **21 Savage**).

**Request:** `{ "property": "artist", "label": "21 Savage" }` (label 1–80 chars)

**Response — 201:** `{ "value": { "id": "…", "property": "artist", "label": "21 Savage" } }`

**Status codes:** 400 invalid property/label, 401 unauthorized.

---

#### `PATCH /api/values/:id`

Renames a value. **Request:** `{ "label": "New Name" }`

**Status codes:** 400 invalid label, 401 unauthorized, 404 not found, 409 `label_taken` (another
of your values already normalizes to this label).

---

#### `DELETE /api/values/:id`

Deletes a value. An Artist can't be deleted while it has a Pack, a claim, or Tracks taken by it
(architecture §19) — the error names which:

**Status codes:** 401 unauthorized, 404 not found, 409 `artist_has_packs` / `artist_is_claimed`
/ `artist_has_taken_tracks`.

---

### Packs (v2)

A Pack is **everything you've sent one Artist, behind one private link** (requirements §5). Each
Artist has exactly one Pack: tag an Artist on a Track and it's in their Pack; untag them and it
leaves. There are no hand-made packs. These routes act as the owner/agent; the routes recipients
use are documented separately under [Public Endpoints](#public-endpoints) below — agents don't act
as Artists.

**Common error mapping** across every route below: `artist_not_found` / `pack_not_found` /
`track_not_found` → 404, `sign_in_required` → 401 (should not happen with a valid key). Anything
else is a 500 with a generic message; the real error is only in the server log.

#### `GET /api/packs`

List your Packs, newest first, from the `pack_rows` view.

**Query:** `?artist_id=<id>` narrows to one Artist's Pack.

**Response:**
```json
{ "packs": [ { "id": "…", "artist_id": "…", "artist": "Future", "title": "Future",
               "link_token": "…",
               "created_at": "…", "updated_at": "…", "claimed": true, "track_count": 9,
               "favorites": 3, "removed": 1, "opens": 12, "plays": 40,
               "last_opened_at": "2026-09-26T…" } ] }
```

`title` is the Artist's name (requirements §5: a Pack has no title of its own).

**Status codes:** 400 invalid `artist_id`, 401 unauthorized.

---

#### `POST /api/packs`

**Send to artist** — tags an Artist on Tracks, hand-picked by id or by handing it the same
`filter`/`q` the Tracks table used (architecture §8 "Send to artist from filters"), and returns
that Artist's Pack and link. The Pack is created on first use.

**Request:**
```json
{ "artist_id": "<artist-id>", "track_ids": ["…"] }
```
or
```json
{ "artist_name": "Future",
  "filter": [{ "property": "genre", "op": "is", "value": "<genre-id>" }] }
```

Name the Artist with `artist_id`, or with `artist_name` (1–80 chars; an existing Artist with that
name is reused, otherwise one is created). Provide either `track_ids` (verified as yours) or
`filter`/`q` — resolved the same way `POST /api/tracks/bulk` resolves them, capped at 5000 Tracks.
Tracks the Artist already removed, or that are taken by someone else, are skipped (requirements
§3.7, §19). Same effect as `POST /api/tracks/bulk` `op=add_artist`, plus the link.

**Response — 200:**
```json
{ "pack": { "…": "…PackRow fields…" }, "url": "https://www.usemontage.com/p/<token>",
  "added": 8, "already": 0, "skipped_removed": 1, "skipped_taken": 0 }
```

**Status codes:** 400 invalid artist/track_ids/filter, or neither `track_ids` nor `filter`/`q`
given, 401 unauthorized, 404 `artist_id` isn't yours.

---

#### `GET /api/packs/:id`

Pack detail (requirements §5.2): the Pack, its current Tracks with each one's feedback, Tracks the
Artist removed (with Restore), the claim, and its activity feed.

**Response:**
```json
{
  "…": "…PackRow fields, plus…",
  "url": "https://www.usemontage.com/p/<token>",
  "claim": { "email_hint": "future…@gmail.com", "claimed_at": "2026-09-20T…" },
  "tracks": [ { "…": "…TrackRow fields…", "plays": 4, "favorited": true, "not_played": false } ],
  "removed_tracks": [ { "track_id": "…", "title": "Private Life", "removed_at": "2026-09-24T…" } ],
  "activity": [ { "type": "favorited", "count": 1, "track_title": "Private Life", "source": "pack",
                  "at": "2026-09-26T…" },
                { "type": "tagged", "count": 12, "track_title": null, "source": "owner",
                  "at": "2026-09-20T…" } ]
}
```

`claim` is `null` when the Artist hasn't signed in on any of their links yet. `plays` on a Track is
plays of it on **this** Pack's link; `not_played` ("NEW") looks at every one of the Artist's links,
not just this one. `activity` groups actions done together (a bulk tag, one Send to artist) into
a single row with a `count`, newest first, up to 100 rows; `track_title` is only set when `count`
is 1. It also includes the Artist's pack-less events (an owner Restore, a profile favorite/use).

**Status codes:** 401 unauthorized, 404 not found (or not yours).

---

#### `POST /api/packs/:id/reset-link`

Replaces the Pack's link. The old link stops working immediately; the claim and Track data are
unaffected, because the claim lives on the Artist, not the link (requirements §7, §25).

**Response:** `{ "link_token": "…", "url": "https://www.usemontage.com/p/<token>" }`

**Status codes:** 401 unauthorized, 404 not found.

---

#### `POST /api/packs/:id/tracks`

Adds Tracks to a Pack by tagging its Artist on them (requirements §6.3).

**Request:** `{ "track_ids": ["…"] }` (1–5000 ids)

**Response:** `{ "added": 3, "already": 1, "skipped_removed": 0, "skipped_taken": 0 }`

**Status codes:** 400 invalid `track_ids`, 401 unauthorized, 404 not found.

---

#### `DELETE /api/packs/:id/tracks`

Removes Tracks from a Pack by untagging its Artist on them (requirements §6.4).

**Request:** `{ "track_ids": ["…"] }` (1–5000 ids)

**Response:** `{ "removed": 3 }`

**Status codes:** 400 invalid `track_ids`, 401 unauthorized, 404 not found.

---

#### `POST /api/artists/:id/release`

Hands an Artist's claim back — clears the account that claimed them. The next sign-in on one of
their Pack links claims it (requirements §19, §25). Use this when the wrong account claimed an
Artist (a manager, say).

**Status codes:** 401 unauthorized, 404 not found.

---

### Analytics (v2)

All-time numbers computed live from `events`/`artist_tracks` — there's no stored counter and no
date-range picker (requirements §11). Live YouTube numbers are a separate call, since they come
from Google rather than this database.

#### `GET /api/analytics`

**Response:**
```json
{
  "kpis": { "opens": 42, "plays": 1284, "favorites": 38, "removed": 17 },
  "daily_plays": [ { "date": "2026-08-29", "plays": 0 }, "…30 days, oldest first, zero-filled…" ],
  "most_favorited": [ { "track_id": "…", "title": "Shutdown", "favorites": 5 } ],
  "packs": [ { "…": "…PackRow fields, same as GET /api/packs…" } ]
}
```

`kpis` rolls up every Pack: `opens` and `plays` are events across every Pack link; `favorites` and
`removed` are current counts (a Track favorited then removed no longer counts as favorited).
`daily_plays` is always exactly 30 rows. `most_favorited` is capped at 10, most favorites first.
`packs` is every owner Pack (`pack_rows`), opens descending — the same shape `GET /api/packs`
returns, for a Packs table alongside the chart.

**Status codes:** 401 unauthorized.

---

#### `GET /api/activity`

The owner's activity feed across every Pack (used for Home's summary line and Pack activity card;
Pack detail's own activity is scoped to one Pack — `GET /api/packs/:id`).

**Query:** `?limit=` how many grouped rows to return (default 50, max 200).

**Response:**
```json
{ "activity": [
  { "type": "favorited", "count": 1, "artist": "Future", "track_title": "Private Life",
    "pack_id": "…", "pack_token": "…", "pack_title": "Future", "source": "pack",
    "at": "2026-09-26T…" },
  { "type": "removed", "count": 2, "artist": "Future", "track_title": null,
    "pack_id": "…", "pack_token": "…", "pack_title": "Future", "source": "pack",
    "at": "2026-09-26T…" },
  { "type": "tagged", "count": 12, "artist": "Future", "track_title": null,
    "pack_id": "…", "pack_token": "…", "pack_title": "Future", "source": "owner",
    "at": "2026-09-26T…" }
] }
```

`type` is a raw `events.type` value. Rows sharing the same `(type, created_at, pack, artist)` are
grouped into one, newest first — a bulk action (a bulk tag, a Send to artist, `set_taken`'s fan-out)
writes every row in one statement, so they share the exact timestamp; `track_title` is only kept
when `count` is 1. `pack_title` is the Artist's name, and is `null` for a Pack-less event (a favorite/use from the producer profile, requirements §26) —
the client shows "· from your profile" for those. `source` is `pack` / `profile` / `owner` /
`agent`; the client shows "You" instead of the Artist's name for `owner`/`agent` rows.

**Status codes:** 400 invalid `limit`, 401 unauthorized.

---

#### `GET /api/youtube/stats`

Live YouTube numbers (requirements §11.2): fetched from the YouTube Data API on every call — this
never stores a snapshot. A 60-second in-memory cache per channel keeps many open tabs from
multiplying calls; call it on load and about every 60s while the page is visible.

**Response — connected:**
```json
{
  "connected": true,
  "total_views": 18412,
  "channels": [ { "channel_id": "…", "title": "Dallas Rose Beats", "views": 16204 } ],
  "latest": [ { "visual_id": "…", "title": "Private Life", "youtube_video_id": "…",
                "views": 2118, "published_at": "2026-09-25T…", "thumbnail_url": "https://…/thumbnails/….jpg" } ]
}
```

**Response — no connected channel:** `{ "connected": false }`

`total_views` sums every connected channel's all-time `channels.list?part=statistics` view count.
`latest` is up to 8 of the owner's most recently created Visuals with a YouTube video (newest
first), with each video's own `videos.list?part=snippet,statistics` view count, batched 50 ids per
call (1 quota unit each). `thumbnail_url` is the Visual's thumbnail (a frame, or the custom one
chosen on publish), or `null`.

**Status codes:** 401 unauthorized.

---

### Job Management (Render)

#### `POST /api/montage/schedule`

Create a new render job. Returns immediately; video processing happens asynchronously.

**Request:**
```json
{
  "title": "My Beat #5",
  "audioStoragePath": "audio/uploads/2026/09/beat-abc123.mp3",
  "trackId": "optional-v2-track-uuid",
  "video_source_type": "youtube" | "upload" | "image",
  "source_youtube_url": "https://www.youtube.com/watch?v=…",
  "startTime": 30,
  "endTime": 150,
  "uploaded_video_path": "optional/path/to/video.mp4",
  "uploaded_image_path": "optional/path/to/image.jpg"
}
```

**Validation:**
- `title` required, ≤ 200 chars
- `audioStoragePath` required unless `trackId` is given; must exist in storage (from presign)
- `trackId` (v2): the id of a Track in your library (`GET /api/tracks`) to use as the render's
  audio instead of `audioStoragePath`. Must belong to you, or the request 400s with
  `"Track not found"`. When both are sent, the Track wins.
- `video_source_type` defaults to `youtube`
- For `youtube`: `source_youtube_url` required; `startTime`, `endTime` define the clip (seconds)
- For `upload`: `uploaded_video_path` required
- For `image`: `uploaded_image_path` required

**Response:**
```json
{
  "success": true,
  "jobId": "550e8400-e29b-41d4-a716-446655440000",
  "creditsRemaining": 90
}
```

**Status codes:**
- 402 if `credits.balance < costPerVideo`
- 429 if ≥10 active jobs or ≥20 jobs/hour

---

#### `GET /api/jobs/:jobId`

Get current status and details of a render job.

**Response:**
```json
{
  "id": "job-uuid",
  "title": "My Beat #5",
  "status": "pending" | "downloading" | "processing" | "uploading" | "complete" | "error",
  "progress": 45,
  "createdAt": "2026-09-07T10:00:00Z",
  "updatedAt": "2026-09-07T10:01:30Z",
  "errorMessage": "Download failed: video unavailable",
  "montage": {
    "id": "montage-uuid",
    "title": "My Beat #5",
    "videoUrl": "https://cdn.example.com/montages/…/video.mp4",
    "thumbnailUrl": null,
    "youtubeVideoId": null,
    "createdAt": "2026-09-07T10:15:00Z"
  },
  "input": {
    "videoSourceType": "youtube",
    "sourceYoutubeUrl": "https://www.youtube.com/watch?v=…",
    "startTime": 30,
    "endTime": 150
  },
  "publishIntents": [
    {
      "id": "intent-uuid",
      "kind": "youtube_full" | "youtube_short",
      "status": "queued" | "publishing" | "published" | "error" | "cancelled",
      "youtubeVideoId": "dQw4w9WgXcQ",
      "youtubeUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
      "errorMessage": null,
      "attemptCount": 1,
      "createdAt": "2026-09-07T10:20:00Z",
      "updatedAt": "2026-09-07T10:35:00Z",
      "completedAt": "2026-09-07T10:35:00Z"
    }
  ]
}
```

---

#### `POST /api/jobs/retry`

Retry a failed job from the beginning.

**Request:**
```json
{
  "jobId": "job-uuid"
}
```

**Response:**
```json
{
  "success": true
}
```

---

#### `POST /api/jobs/delete`

Delete a job (renders it unusable; does not refund credits).

**Request:**
```json
{
  "jobId": "job-uuid"
}
```

**Response:**
```json
{
  "success": true
}
```

---

### Video Library

#### `GET /api/montages`

List completed videos.

**Query params:**
- `limit` (default: 20, max: 100)
- `offset` (default: 0)
- `status` (default: "all" | "published" | "unpublished")

**Response:**
```json
{
  "montages": [
    {
      "id": "montage-uuid",
      "title": "My Beat #5",
      "videoUrl": "https://cdn.example.com/montages/…/video.mp4",
      "thumbnailUrl": null,
      "storageType": "r2",
      "youtubeVideoId": "dQw4w9WgXcQ",
      "createdAt": "2026-09-07T10:15:00Z",
      "updatedAt": "2026-09-07T10:35:00Z"
    }
  ],
  "total": 42,
  "limit": 20,
  "offset": 0
}
```

---

### Publishing

#### `POST /api/publish/intent`

Queue a video for YouTube publishing. Supports full video, YouTube Shorts (9:16 clip), or both. There is one intent per (montage, kind): re-posting while that intent is still `queued` (or after it hit `error` / `cancelled`) updates it in place and returns the same intent id. Once an intent is `publishing` or `published`, a re-post returns **409** instead of uploading the video a second time.

**Request:**
```json
{
  "montageId": "montage-uuid",
  "jobId": "job-uuid (alternative to montageId)",
  "channelId": "UCxxxxxxxxxxxxx",
  "title": "My Beat #5 [Prod. Me]",
  "description": "Free beat. Use at will.",
  "tags": "beat,free,lofi",
  "privacy": "public" | "private" | "unlisted",
  "category": "music" | "entertainment" | "educational" | …,
  "thumbnailUrl": "https://example.com/thumb.jpg",
  "overlay": {
    "text": "Free Beat",
    "opacity": 0.8,
    "color": "#FFFFFF"
  },
  "publishFull": true,
  "clip": {
    "inSeconds": 10,
    "outSeconds": 70,
    "title": "My Beat #5 - SHORT",
    "description": "60-second clip",
    "thumbnailUrl": "https://example.com/thumb-short.jpg",
    "burnIn": "My Beat #5"
  },
  "force": false
}
```

**Validation:**
- `montageId` or `jobId` required (not both)
- `channelId` optional: the `UC…` channelId (or the channel's `id`) from `GET /api/me`. Omit it to publish to the most recently connected channel
- `title` required, ≤ 100 Unicode code points; `<` and `>` are rejected
- `privacy` required, one of above
- If `clip` provided: `inSeconds` and `outSeconds` required; span ≤ 60 seconds
- `publishFull` default: true (if false and `clip` provided, publish only the Short)
- `force` default: false. `true` re-uploads an intent that is already `published`, creating a **second** YouTube video. Only set it when a human asked for a duplicate. It never overrides a `publishing` intent

**Response:**
```json
{
  "success": true,
  "intentId": "intent-uuid (for full)",
  "intentIds": {
    "full": "intent-uuid (if publishFull true)",
    "short": "intent-uuid (if clip provided)"
  },
  "status": "queued"
}
```

**Status codes:**
- 403 with `{ "needsAuth": true }` if user hasn't connected YouTube channel (`/connections`)
- 404 with `connectedChannels` if `channelId` doesn't match a connected channel. This is not an auth problem: retry with a listed `channelId`, or omit it
- 409 if an intent for this montage is already past `queued`. Nothing is written. The body carries a `code` and the blocking `intents` (same shape as `GET`):
  - `publish_in_progress`: an upload is running. Poll `GET /api/publish/intent` until it finishes; do not re-post.
  - `already_published`: the video is live; `intents[].youtubeUrl` has the link. Treat this as success. Re-post with `"force": true` only to deliberately upload a second copy.

```json
{
  "error": "This video is already published to YouTube. Pass \"force\": true to upload it again as a new video.",
  "code": "already_published",
  "intents": [{ "id": "intent-uuid", "kind": "youtube_full", "status": "published", "youtubeUrl": "https://www.youtube.com/watch?v=…", "…": "…" }]
}
```

---

#### `GET /api/publish/intent`

Query publish intent(s) by ID or by job/montage.

**Query params (one required):**
- `id=<intentId>` — single intent
- `jobId=<jobId>` — all intents for job
- `montageId=<montageId>` — all intents for montage

There is no `intentId` query param — polling with `?intentId=` returns 400.

**Response:**
```json
{
  "intents": [
    {
      "id": "intent-uuid",
      "kind": "youtube_full" | "youtube_short",
      "status": "queued" | "publishing" | "published" | "error" | "cancelled",
      "jobId": "job-uuid" | null,
      "montageId": "montage-uuid" | null,
      "channelId": "UCxxxxxxxxxxxxx" | null,
      "title": "My Beat #5 [Prod. Me]" | null,
      "privacy": "public" | null,
      "youtubeVideoId": "dQw4w9WgXcQ" | null,
      "youtubeUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ" | null,
      "errorMessage": null,
      "attemptCount": 1,
      "createdAt": "2026-09-07T10:20:00Z",
      "updatedAt": "2026-09-07T10:35:00Z",
      "completedAt": "2026-09-07T10:35:00Z" | null
    }
  ]
}
```

Ordered by `createdAt` ascending. Returns 400 if no selector given.

---

#### `POST /api/publish/intent/retry`

Retry a failed publish intent.

**Request:**
```json
{
  "intentId": "intent-uuid"
}
```

**Response:**
```json
{
  "success": true
}
```

Returns 409 if the intent is still `queued` or `publishing`.

---

#### `POST /api/publish/intent/cancel`

Cancel a publish intent that is still `queued`. Cancelling a `youtube_full` intent also cancels the queued `youtube_short` that waits on it; to publish only the Short afterwards, re-post with `"publishFull": false`.

**Request:**
```json
{
  "intentId": "intent-uuid"
}
```

**Response:**
```json
{
  "success": true,
  "cancelledIntentIds": ["intent-uuid", "short-intent-uuid"]
}
```

Cancelling an already-cancelled intent returns 200 with an empty `cancelledIntentIds`. Returns 409 (with the intent's current `status`) once the worker has started uploading or the video is published: an upload in progress can't be stopped. Returns 404 if the intent doesn't exist or isn't yours.

---

## Status Machines

### Job Statuses

```
pending → downloading → processing → uploading → complete
                                              ↘ error
```

- **pending:** Waiting to be picked up by worker
- **downloading:** Fetching YouTube segment or uploaded video
- **processing:** Running FFmpeg to combine video + audio
- **uploading:** Sending final video to Cloudflare R2
- **complete:** Success; `montage` field populated
- **error:** Failed; see `errorMessage`

### Publish Intent Statuses

```
queued → publishing → published
          ↘ error
          ↘ cancelled
```

- **queued:** Waiting in queue
- **publishing:** Uploading to YouTube
- **published:** Success; `youtubeVideoId` and `youtubeUrl` populated
- **error:** Failed; see `errorMessage`
- **cancelled:** Cancelled via `POST /api/publish/intent/cancel` while still queued

---

## Reliability Rules for Agents

Follow these rules to build reliable automation:

### 1. Preflight

Before initiating a workflow, call `GET /api/me` and verify:
- `subscription.status` is `"active"` or `"trialing"`
- `credits.balance >= credits.costPerVideo`
- `youtubeChannels` contains at least one channel (if publishing)

### 2. Job Polling

After `POST /api/montage/schedule`, poll `GET /api/jobs/:jobId` every **10 seconds**.
Timeout after **30 minutes** of polling; treat as error.

### 3. Publish Polling

After `POST /api/publish/intent`, poll `GET /api/publish/intent?jobId=…` or `?montageId=…` every **15 seconds**.
Timeout after **30 minutes**; treat as error.

Publish intents can be multiple (full + short). Check all are published/error before returning.

A slow publish is not a failed publish. If `youtubeVideoId` is still null, keep polling. Never re-post the intent to "nudge" it.

### 4. Retry Logic

- **Never retry 402 or 403:** These are permanent failures (no credits, no YouTube auth). Surface to user.
- **Retry 5xx and network errors:** Backoff strategy: 1s, 3s, 9s (3 attempts total). Respect `Retry-After` header on 429.
- **Idempotency:** `POST /api/publish/intent` is safe to retry after a network error or 5xx: it updates the one intent per (montage, kind), and returns 409 rather than uploading twice once that intent is uploading or published. On 409 `already_published`, stop and report the `youtubeUrl`. `POST /api/montage/schedule` is NOT idempotent; always persist the `jobId` before polling.

### 5. Error Handling

- **402 (insufficient credits):** Upgrade subscription or wait for credit top-up.
- **403 (no YouTube auth):** Direct user to `/connections` to authorize YouTube.
- **404:** Job/montage/intent not found (deleted or invalid ID).
- **409:** Publish conflict. See `code`: `already_published` (done, report the link), `publish_in_progress` (keep polling). From `cancel`/`retry`: the intent is in the wrong state for that action.
- **429 (rate limited):** Wait for `Retry-After` seconds; respect concurrency limits.
- **500:** Server error; retry with backoff.

---

## CLI & Scripting

Programmatic access via Node.js CLI:

```bash
node scripts/montage-cli.mjs [command] [options]
```

Set `MONTAGE_API_KEY=mk_live_…` environment variable.

**Command list** (every command prints one JSON object to stdout; exit codes: 0 ok, 1 API error, 2 usage error, 3 timeout):

- `me` / `preflight` — `GET /api/me`; `preflight` exits 1 if subscription, credits, or channel are missing
- `channels` — list connected YouTube channels
- `upload <audioFile>` — presign + PUT; prints `audioStoragePath`
- `create --audio <fileKey> --youtube <urlOrId> --start <s> --end <s> --title <t>` — schedule render. `--track-id <id>` may be given instead of `--audio` to schedule from a v2 Track; `--video-file <path>` (with `--start/--end`) or `--image-file <path>` replaces `--youtube` with an uploaded clip or an image, uploaded first via `POST /api/upload/video|image`
- `job <jobId>` / `wait-job <jobId> [--interval 10] [--timeout 1800]` / `retry-job <jobId>` (re-queue an errored job; no extra credits)
- `publish --job <jobId> --title <t> [--description <d>] [--tags "a,b"] [--privacy public|private|unlisted] [--channel <id>] [--category music] [--thumbnail <url>] [--no-full] [--clip-in <s> --clip-out <s> --clip-title <t>] [--force]` — exits 1 with `code` `already_published` / `publish_in_progress` on a 409
- `publish-status --job <jobId> | --intent <id> | --montage <id>`
- `cancel-publish <intentId>` — cancel a queued intent (and its dependent Short)
- `wait-publish --job <jobId> [--interval 15] [--timeout 1800]`
- `run --audio-file <path> --youtube <urlOrId> --start <s> --end <s> --title <t> [publish flags…] [--no-publish] [--state <path>]` — full pipeline; writes a `.montage-run-<slug>.json` state file after each step and resumes from it on re-run, so it never schedules the same beat twice

**Tracks & Packs (v2)** — everything a producer can do to their library and Packs, for agents:

- `tracks [--q text] [--filter '<json>'] [--limit n] [--group-by artist|genre|key|scale|tag]` — `GET /api/tracks`, following `next_cursor` until `--limit` (default: every matching Track). `--group-by` prints the **folders** instead (value, label, count, cover Track ids); list one folder's Tracks with a `--filter` on its value
- `track-upload <file> [--title t] [--genre label] [--tag label]… [--artist label] [--skip-similar]` — hashes the file (SHA-256), `POST /api/tracks/uploads`, `PUT`s to the presigned URL, `POST …/confirm`. An **exact duplicate** prints it and exits 0. **Likely duplicates** print to stderr and the upload proceeds unless `--skip-similar` is given (then it prints `{"skipped":"similar",…}` and exits 0 without uploading). Genre/Tag/Artist labels are resolved — and created if new — via `POST /api/values`
- `track <id>` — `GET /api/tracks/:id`
- `track-edit <id> [--title t] [--bpm n] [--key 0-11] [--scale s] [--genre label] [--add-artist label]… [--remove-artist label]… [--show-on-profile true|false]` — `PATCH /api/tracks/:id`
- `tag --artist label (--tracks id,id | --filter '<json>')` — `POST /api/tracks/bulk` `op=add_artist`; prints `skipped_removed`/`skipped_taken` counts
- `packs [--artist label]` — `GET /api/packs`
- `pack <id>` — `GET /api/packs/:id`
- `send --artist label (--tracks id,id | --filter '<json>' | --q text)` — `POST /api/packs` (Send to artist); prints the Artist's pack link `url`
- `analytics` — `GET /api/analytics`

**Everything else the web app lets a producer do** (agents act as the producer, principles §3; artist-side actions stay cookie-session only):

- `bulk --op add_artist|remove_artist|add_tag|remove_tag|set_genre|show_on_profile|hide [--value label] (--tracks id,id | --filter '<json>' | --q text)` — the Tracks bulk bar, `POST /api/tracks/bulk`
- `track-delete <id>` — `DELETE /api/tracks/:id`; `track-restore <id> --artist label` — `POST /api/tracks/:id/restore`; `track-taken <id> (--artist label | --clear)` — `POST /api/tracks/:id/taken`; `track-clear-use <id> --artist label` — `POST /api/tracks/:id/clear-use`
- `stream <trackId>` — a 5-minute signed URL for your own Track (`GET /api/stream/:id?via=owner`)
- `values --property artist|genre|tag [--q text]` / `value-add --property p --label text` / `value-rename <id> --label text` / `value-delete <id>` — `/api/values`. Commands that remove or change things look an Artist up by label **without creating it**, so a typo fails instead of inventing one
- `pack-reset-link <id>`, `pack-add <id> --tracks id,id`, `pack-remove <id> --tracks id,id`, `release (<artistId> | --artist label)` — `/api/packs/:id/reset-link`, `/api/packs/:id/tracks`, `/api/artists/:id/release`
- `profile` / `profile-edit [--name t] [--avatar-url u] [--contact-email e] [--link url]… [--clear-links] [--pro BMI|…] [--ipi n] [--slug s] [--allow-downloads true|false]` — `GET/PATCH /api/profile` (`--allow-downloads true` is Settings → Profile's "Let artists download your beats"; off by default)
- `activity [--limit n]`, `credits`, `montages [--limit n] [--offset n] [--status s]`, `job-delete <jobId>`, `retry-publish <intentId>`, `templates`, `youtube-stats` — `GET /api/activity`, `GET /api/credits`, `GET /api/montages`, `POST /api/jobs/delete`, `POST /api/publish/intent/retry`, `GET /api/youtube/templates`, `GET /api/youtube/stats`

Run `--help` for full options.

### Hermes Skill

For Hermes integration:

```bash
~/.hermes/skills/montage/SKILL.md
```

Contains pre-configured prompts and examples for Hermes agents.

---

## Public Endpoints

These do not require authentication:

- `GET /api/credits/plans` — pricing info

### Pack link (no API key)

A Pack's link (`https://www.usemontage.com/p/<token>`) is what a producer sends an Artist. It's
never an agent/API-key surface — the caller is either anonymous or a signed-in Artist's browser
session, never a Bearer key (principles §3: agents act as the producer, not as an Artist). These
routes exist so the web app's pack page can be described here alongside the rest of the API, not
because agents are expected to call them.

- **`GET /api/p/:token`** — the pack page's data: `pack: { title, genres }` (the title is the
  producer's name), the producer's name/photo, and its Tracks. The Artist
  property is never included (requirements §8.1). `favorited`/`using` on each Track are present
  only for the Artist who claimed this link. Token format `^[0-9A-Za-z]{12}$`; 404 if it doesn't
  match a Pack. `Cache-Control: no-store`. Rate limited 60/min per IP.
- **`POST /api/p/:token/events`** — `{ visit_id, type: "pack_opened" | "track_played", track_id? }`.
  Anonymous is fine, since the link identifies the Artist (requirements §8.9); de-duplicated per
  `visit_id`. Rate limited 120/min per IP.
- **`POST /api/p/:token/tracks/:trackId/:action`** — `action` one of `favorite`, `unfavorite`,
  `remove`, `undo_remove` (within 30s server-side), `use`, `unuse`. Requires a signed-in session;
  401 `sign_in_required` when signed out (the web app opens the sign-in sheet), 403
  `claimed_by_other` / `listener_only` / `owner_preview`, 410 `undo_expired`. Claims the link's
  Artist for the caller on first action, when the rules allow (requirements §25). Rate limited
  30/min per user.

- **`POST /api/stream/:trackId/download?via=pack:<token>|profile:<slug>`** — an Artist's one-tap
  download of the Track's original file (requirements §8.10). Same access as `use`: it marks the
  Track In use and favorited, logs a `downloaded` event, and returns `{ url, filename, favorited,
  using }` where `url` is a 5-minute signed URL that forces a download. Requires a signed-in
  session; 401 `sign_in_required`, 403 `claimed_by_other` / `listener_only` / `owner_preview` /
  `downloads_disabled` (the producer turned downloads off with `allowDownloads` on
  `PATCH /api/profile`), 404, 429 (30/min per user), 503 `download_unavailable`. `GET /api/p/:token`
  and `GET /api/u/:slug` report `producer.downloads` so the page knows whether to show the icon.

### Artist home (signed-in session, no API key)

Every pack a producer has sent an Artist, from every producer, in one place (requirements §25 "The
artist's home"). Like the pack link routes above, these need a signed-in **cookie session** —
never a Bearer key, since agents act as the producer, not as an Artist (principles §3). They exist
so the `/inbox`, `/inbox/activity` and `/inbox/owned` pages can be described here alongside the
rest of the API.

- **`GET /api/me/inbox`** — Packs grouped by producer: `{ producers: [ { producer: { name,
  avatar_url, profile_slug }, packs: [ { token, title, count, new } ] } ] }`. Each producer has one
  pack for this Artist, titled with the producer's name; `new` is tracks tagged
  for this Artist since they last played that pack. The Artist property tagged on each Track is
  never included (principles §2.5). 401 when signed out.
- **`GET /api/me/activity`** — `{ items: [ { producer, pack_token, pack_title, type, count,
  track_title, yours, at } ], unread }`. `type` is `tagged` / `taken` (older
  events may read `pack_created` / `pack_track_added`); actions done together (a bulk tag) come back as
  one row with a `count`, and `track_title` is only set when `count` is 1. `yours` is only
  meaningful for `taken` — it says whether **this** Artist is the one who took it, never who else
  did (requirements §25: "It says which beat was taken, but never by whom"). `unread` counts items
  newer than `profiles.activity_seen_at` (architecture §10). 401 when signed out.
- **`POST /api/me/activity/seen`** — marks the Activity tab read: sets
  `profiles.activity_seen_at = now()` and returns `{ activity_seen_at }`. Called when the artist
  opens the Activity tab, clearing its unread dot. 401 when signed out.
- **`GET /api/me/owned`** — every Track taken by any Artist this account has claimed, across every
  producer: `{ tracks: [ { …public Track fields…, producer } ] }`. Playable regardless of the
  producer's "Show on profile" setting (requirements §24, §26). 401 when signed out.

### Producer profile (signed-in Artist session, no API key)

A producer's page for the Artists they've sent a Pack to (requirements §26). Not public and not an
agent surface: reachable only by an account that holds a claim on one of this producer's Artists
(architecture §3.4 `profile_for_artist`) — signed out or without a claim, both routes respond
`404 { "error": "not_found" }` with no hint the profile exists (principles §2.4, §3). These exist
so `/u/:slug` can be described here alongside the rest of the API.

- **`GET /api/u/:slug`** — the profile's data: `{ producer: { name, avatar_url, links, contact_email,
  pro, ipi }, genres, tracks: [ { id, title, bpm, key, scale, genre, duration_ms, peaks, owned,
  favorited, using } ] }`. `tracks` is only those set to **Show on profile** and not taken by
  someone else (requirements §26); Artist tags, "in use", other Artists and stats are never
  included. 401 when signed out (middleware.ts requires a session on every `/api/u/*` route).
- **`POST /api/u/:slug/tracks/:trackId/:action`** — `action` one of `favorite`, `unfavorite`,
  `use`, `unuse`. No `remove` — there's no Remove on the profile. Clears any earlier removal and
  tags the caller's Artist, so the Track joins their Pack (requirements §19, §26). 401 signed
  out, 404 `not_found` for a bad slug, no claim here, or a hidden/taken/unknown Track id.

---

## Changelog

- **2026-10-03:** Downloads are **off by default** (`allowDownloads` defaults to `false`). The CLI now covers every producer-side ability in the app: `bulk`, `track-delete`, `track-restore`, `track-taken`, `track-clear-use`, `stream`, `values`, `value-add`, `value-rename`, `value-delete`, `pack-reset-link`, `pack-add`, `pack-remove`, `release`, `profile`, `profile-edit`, `activity`, `credits`, `montages`, `job-delete`, `retry-publish`, `templates`, `youtube-stats`, and `create --video-file/--image-file`. Documented `POST /api/upload/video` and `/api/upload/image`.
- **2026-10-03:** Artist downloads: `POST /api/stream/:trackId/download` (cookie session; marks the Track In use), `allowDownloads` on `GET/PATCH /api/profile`, and `producer.downloads` on the pack and profile reads.
- **2026-09-30:** One pack per Artist: named packs are gone. `POST /api/packs` is now **Send to
  artist** (`artist_id` or `artist_name`, plus `track_ids` or `filter`/`q`; no `title`/`description`)
  and returns 200. Removed `PATCH/DELETE /api/packs/:id` and the `kind`/`description`/`cover_key`
  fields. `POST/DELETE /api/packs/:id/tracks` tag/untag the Artist. `GET /api/p/:token` drops the
  `packs` switcher; `/api/me/inbox` packs drop `kind`. `use_source` is `"pack"` instead of
  `"pack:<title>"`. The CLI's `pack-create` is replaced by `send --artist`.
- **2026-09-28:** Documented `GET /api/stream/:trackId` (was missing from this reference and
  `openapi.json`). Corrected `POST /api/tracks/uploads`: the response does not echo back a
  normalized mime for the `PUT`'s `Content-Type` — derive it from the extension. Added the CLI's
  Tracks & Packs commands (`tracks`, `track-upload`, `track`, `track-edit`, `tag`, `packs`, `pack`,
  `pack-create`, `analytics`) and `create --track-id`.
- **2026-09-28:** Added `POST /api/tracks/:id/clear-use` and the producer profile (`GET /api/u/:slug`, `POST /api/u/:slug/tracks/:trackId/:action`) — cookie session only, 404 for anyone without a claim.
- **2026-09-27:** Added the v2 Analytics API: `GET /api/analytics` (all-time KPIs, 30-day daily plays, most favorited, packs), `GET /api/activity` (owner-wide activity feed), `GET /api/youtube/stats` (live per-channel views + latest uploads).
- **2026-09-27:** Added the artist home: `GET /api/me/inbox`, `GET /api/me/activity`, `POST /api/me/activity/seen`, `GET /api/me/owned` — cookie session only, no API key.
- **2026-09-27:** Added the v2 Packs API: `GET/POST /api/packs`, `GET/PATCH/DELETE /api/packs/:id`, `POST /api/packs/:id/reset-link`, `POST/DELETE /api/packs/:id/tracks`, `POST /api/artists/:id/release`, and the public pack link (`GET /api/p/:token`, `POST /api/p/:token/events`, `POST /api/p/:token/tracks/:trackId/:action`).
- **2026-09-14:** `POST /api/publish/intent` returns 409 (`publish_in_progress` / `already_published`) instead of re-queuing an intent that is uploading or published. Previously a re-post reset it to `queued` and the video was uploaded twice. Added `force` and `POST /api/publish/intent/cancel`. Fixed CLI `retry-job`, which sent no request body.
- **2026-09-12:** Published public docs at `/docs`. Corrected drift in this file: job/montage responses return `videoUrl`/`thumbnailUrl`/`youtubeVideoId`/`createdAt` (not `s3Path`/`s3PublicUrl`), `/api/montages` returns `limit`/`offset` and no `status` field, `/api/credits` ledger entries use `delta`/`created_at`/`balance_after`, and `GET /api/publish/intent` has no `intentId` param (use `id`).
- **2026-09-07:** API published. Bearer auth via `mk_live_` keys. Workstreams A–E complete.
