# API reference

Use the HTTP API under `/api` to work with an Alim workspace. This reference lists routes, request and response fields, and storage collections. [Set up an Alim server](/docs/self-hosting.md).

| I need to…                      | Start here                                                              |
| ------------------------------- | ----------------------------------------------------------------------- |
| Sign in or pair a Mac           | [Auth and devices](#auth-and-devices)                                   |
| Read meetings and transcripts   | [Meetings](#meetings) and [Transcript ingestion](#transcript-ingestion) |
| Add notes and files             | [Notes and attachments](#notes-and-attachments)                         |
| Find people, projects, or tasks | [Knowledge](#knowledge)                                                 |
| Connect an AI client            | [MCP and OAuth](#mcp-and-oauth)                                         |

## Conventions

| Topic                 | Rule                                                                                                                                                                                    |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Base path             | `/api` unless a table shows a full path (PocketBase `/api/collections/*`, `/.well-known/*`, `/oauth/*` and `/mcp` are full paths)                                                       |
| Auth                  | `Authorization: Bearer <pb_auth_token>` on every route marked **User**                                                                                                                  |
| Public routes         | `config`, `telemetry`, `oauth/google/callback`, `oauth/microsoft/callback`, `oauth/zoom/callback`, `auth/device/start`, `auth/device/claim`, OAuth discovery and the OAuth token routes |
| Ownership             | Every read and write is scoped to `owner = <signed-in user>`. A foreign ID returns `404` or `400`, never data                                                                           |
| Direct writes         | PocketBase collection create, update and delete rules are `nil`. Clients write only through these routes                                                                                |
| Errors                | PocketBase shape: `{ "status": 400, "message": "...", "data": {} }`                                                                                                                     |
| Relation keys         | Responses emit both `calendar_account` and `calendar_account_id`, `series` and `series_id`, `meeting` and `meeting_id`, `participant` and `participant_id`                              |
| Financial data        | Salary, income, pay, tax, bank statement and paid contract fields are rejected with `403` on every people and knowledge write                                                           |
| Default local address | `http://127.0.0.1:8090`                                                                                                                                                                 |

> [!NOTE]
> Only verified accounts listed in `OPENSCRIBE_ADMIN_EMAIL` or `OPENSCRIBE_USER_EMAIL` can sign in (linked social identities belonging to an allowlisted account are accepted). Google is the default sign-in method when configured, alongside optional Microsoft, GitHub, Apple and ChatGPT OAuth providers. A removed account keeps its records but loses app, pairing, file and MCP access.

The public web app manifest at `/site.webmanifest` uses `application/manifest+json`.

## Auth and devices

| Method   | Path                                        | Auth   | Purpose                                                                                                      |
| -------- | ------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------ |
| `GET`    | `/auth/oauth/{provider}/start`              | Public | Start same-tab OAuth sign-in or connected-account flow (`google`, `microsoft`, `github`, `apple`, `chatgpt`) |
| `POST`   | `/auth/oauth/exchange`                      | Public | Exchange a one-time OAuth redirect ticket for a session or connect proof                                     |
| `GET`    | `/auth/accounts`                            | User   | List linked social sign-in identities for the signed-in user                                                 |
| `POST`   | `/auth/accounts/connect`                    | User   | Link a verified social sign-in proof to the signed-in user                                                   |
| `DELETE` | `/auth/accounts/{id}`                       | User   | Unlink a social sign-in identity while keeping at least one                                                  |
| `GET`    | `/api/collections/users/auth-methods`       | Public | Enabled PocketBase sign-in methods                                                                           |
| `POST`   | `/api/collections/users/auth-with-oauth2`   | Public | PocketBase OAuth2 exchange                                                                                   |
| `POST`   | `/api/collections/users/auth-with-password` | Public | Optional self-hosted sign-in, with email as `identity` and a `password`                                      |
| `POST`   | `/api/collections/users/auth-refresh`       | User   | Refresh the session token                                                                                    |
| `GET`    | `/config`                                   | Public | Server capabilities for clients                                                                              |
| `GET`    | `/auth/me`                                  | User   | Current user and connected calendar accounts                                                                 |
| `PATCH`  | `/auth/me`                                  | User   | Save `meeting_languages`, `telemetry_off`, `time_format` or `meeting_join_mode`                              |
| `POST`   | `/auth/device/start`                        | Public | Start Mac app sign-in                                                                                        |
| `POST`   | `/auth/device/approve`                      | User   | Approve the Mac's request from the signed-in browser                                                         |
| `POST`   | `/auth/device/claim`                        | Public | Mac app exchanges its secret and the browser's grant for a session token                                     |

Set `OPENSCRIBE_EMAIL_SIGN_IN=true` to enable password login. OTP and public signup are disabled. The server sets `users.admin` from `OPENSCRIBE_ADMIN_EMAIL` only and enforces a minimum 30-day lifetime on `users` auth tokens (`POST /api/collections/users/auth-refresh`). Social sign-in redirect URI is `<PUBLIC_URL>/api/oauth2-redirect`, and Google Calendar, Gmail and Drive use `<PUBLIC_URL>/api/oauth/google/callback`.

### `GET /config`

```json
{
  "app_name": "Alim",
  "default_time_format": "24h",
  "public_url": "https://alim.example.com",
  "oauth_providers": {
    "google": true,
    "microsoft": false,
    "github": false,
    "apple": false,
    "chatgpt": false
  },
  "email_sign_in_enabled": false,
  "gmail_enabled": true,
  "telemetry": true,
  "elevenlabs_configured": true,
  "ai_providers": { "openai": true, "anthropic": true, "google": true },
  "drive_enabled": true,
  "drive_search_enabled": false,
  "google_picker_api_key": "browser-api-key",
  "google_cloud_project_number": "123456789012"
}
```

`telemetry` is `false` only when `OPENSCRIBE_TELEMETRY=off`. `gmail_enabled` describes Gmail availability for the requesting Alim user. With `OPENSCRIBE_GMAIL=off`, only verified, authorized users listed in `OPENSCRIBE_GMAIL_REVIEWERS` receive `true`. Anonymous requests receive the general setting.

`drive_enabled` is `true` for a signed-in user when `GOOGLE_CLIENT_ID` is set and either the Picker is configured (`GOOGLE_PICKER_API_KEY` and `GOOGLE_CLOUD_PROJECT_NUMBER`) or that user may search Drive. Anonymous requests receive `false`. `drive_search_enabled` is `true` only with `OPENSCRIBE_DRIVE_SEARCH=on` or for a verified, authorized user listed in `OPENSCRIBE_DRIVE_REVIEWERS`. `google_picker_api_key` and `google_cloud_project_number` appear only when `drive_enabled` is `true` and the Picker is configured. The key is a browser key that Google expects in page code, so restrict it to the site's referrers and the Picker API.

`default_time_format` is `12h` for requests with `CF-IPCountry: US` and `24h` otherwise, including when the header is absent. The response is private and not cached. The country and IP are not stored for this preference.

### `GET` and `PATCH /auth/me`

`GET` returns `{ "user": { "id", "email", "name", "verified", "admin", "meeting_languages": [], "telemetry_off": false, "time_format": "auto" }, "calendar_accounts": [...] }`. `PATCH` takes any of `{ "meeting_languages": ["tr", "en"], "telemetry_off": true, "time_format": "24h" }` and returns `{ "user" }`. A body with none of these fields returns `400`, and direct PocketBase record writes cannot change them. Empty `meeting_languages` means automatic language detection. `time_format` accepts `auto`, `12h` or `24h`, defaults to `auto`, and overrides `config.default_time_format` when set manually.

### Device pairing

The browser that approves a request hands its one-time grant to the Mac on the same machine through a top-level navigation to `127.0.0.1`. A request approved on another device never reaches its Mac, so `/pair` needs no code or button.

1. `start` takes `{ "device_label": "Ada's MacBook Pro", "callback_port": 48721 }`. `callback_port` is the Mac app's loopback port, from 1024 to 65535, and is required. It returns `{ "id", "secret", "verify_url", "expires", "expires_in": 600 }`. `verify_url` is `<base>/pair?id=<id>` on the request host, so a loopback or SSH-forwarded call gets a loopback URL even when `PUBLIC_URL` is a public domain. Each `start` deletes pairing rows older than a day.
2. `approve` takes `{ "id": "<request_id>" }` from the signed-in page and returns `{ "callback_url": "http://127.0.0.1:<callback_port>/api/auth/complete?id=<id>&grant=<grant>" }`. The same account may approve again, which replaces the grant. The server keeps only the grant's hash.
3. `claim` takes `{ "id", "secret", "grant" }` and returns `{ "token": "<pb_auth_jwt>", "user": {...} }` once. The row becomes `claimed` and the grant is cleared. A wrong secret or grant leaves the request waiting.

| Route     | Status | Message                                                                                                  |
| --------- | ------ | -------------------------------------------------------------------------------------------------------- |
| `start`   | `400`  | `callback_port must be the Mac app's loopback port.`                                                     |
| `approve` | `400`  | `Pairing request id is required.`                                                                        |
| `approve` | `404`  | `Device pairing request not found.` or `Device pairing request expired.`                                 |
| `approve` | `400`  | `Device pairing request was already used.` (claimed by this account, even after expiry)                  |
| `approve` | `400`  | `Device pairing request is no longer pending.` (approved or claimed by another account)                  |
| `claim`   | `404`  | `Device pairing request expired.` (unknown, expired, not approved, wrong secret, wrong grant or claimed) |
| `claim`   | `403`  | The user is no longer allowlisted                                                                        |

## Calendar

| Method   | Path                            | Auth                            | Purpose                                                                                                                                  |
| -------- | ------------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `GET`    | `/calendar/accounts`            | User                            | List connected accounts, never `encrypted_token`                                                                                         |
| `POST`   | `/calendar/connect`             | User                            | Start Google, Outlook or Zoom Calendar OAuth                                                                                             |
| `POST`   | `/meeting-links/google`         | User                            | Create a Google Meet space using an owned account with the Meet grant                                                                    |
| `GET`    | `/api/oauth/google/callback`    | Signed state and browser cookie | Finish Google Calendar, Gmail or Drive OAuth and return with `calendar_connected`, `email_connected`, `drive_connected` or `oauth_error` |
| `GET`    | `/api/oauth/microsoft/callback` | Signed state and browser cookie | Finish Outlook Calendar or Outlook mail OAuth and return with `calendar_connected`, `email_connected` or `oauth_error`                   |
| `DELETE` | `/calendar/accounts/{id}`       | User                            | Disconnect an account                                                                                                                    |
| `GET`    | `/calendar/events`              | User                            | List events, optionally syncing from connected calendars                                                                                 |
| `GET`    | `/calendar/hidden-events`       | User                            | List hidden occurrences and series, including those outside the current calendar window                                                  |
| `POST`   | `/calendar/hidden-events`       | User                            | Hide one occurrence or a recurring series in Alim                                                                                        |
| `DELETE` | `/calendar/hidden-events/{id}`  | User                            | Restore a hidden occurrence or series                                                                                                    |

When a sync fails for one account, `GET /calendar/events` still returns events from the others. Each `sync_errors` entry includes `account_id`, `email`, `error` and `code`. Use `reconnect_required` when the calendar needs fresh consent and `retry` for other refresh failures.

### `POST /calendar/connect`

Request `{ "return_to": "/settings", "login_hint": "ann@example.com", "calendar_id": "primary" }`, all optional. `create_meet_link: true` additionally requests `https://www.googleapis.com/auth/meetings.space.created` through incremental Google consent. `send_invites: true` requests `https://www.googleapis.com/auth/calendar.events.owned` for invitations and confirmed updates to organizer events. The options may be combined. Existing connections retain read-only access until a user grants additional scope. Granted scopes come from the token response. An email `login_hint` makes Google skip the account chooser (`prompt=consent` instead of `consent select_account`). Response `{ "auth_url": "https://accounts.google.com/o/oauth2/v2/auth?...", "redirect_uri": "...", "scopes": [...] }`. The URL requests `calendar.events.owned.readonly` with PKCE `S256`, `access_type=offline` and a signed state bound to the user and to an `HttpOnly` browser cookie. Returns `400` when `GOOGLE_CLIENT_ID` or `GOOGLE_CLIENT_SECRET` is missing.

Set `provider` to `microsoft` for the primary Outlook calendar or `zoom` for the unified Zoom connection. The default is `google` (which returns through `/api/oauth/google/callback`). Microsoft requests delegated `Calendars.Read` without mailbox access and returns through `/api/oauth/microsoft/callback`. Zoom uses the same grant for meeting links and optional primary Zoom Calendar sync through `/api/oauth/zoom/callback`. The Zoom callback returns `zoom_connected` and adds `calendar_connected` when it finds a native calendar. Account responses include `provider` and a Zoom calendar's `zoom_account_id`. Meet and invitations use Google accounts.

Calendar events and saved meetings with a call URL include `join_targets`. `browser` is the default HTTPS link. When the event or meeting belongs to a Google calendar account, a Google Meet `browser` link carries `authuser` set to that account's email, so Meet opens as that account instead of the browser's first Google account. Meeting lists leave the link unchanged, and the meeting detail and calendar events carry it. With the saved `meeting_join_mode: "desktop"`, the browser uses the provider's `launcher` and macOS first tries the `desktop` URL when an application handles it. The original `meeting_url` remains the meeting and provider identity.

### `POST /meeting-links/google`

Takes `{ "calendar_account_id": "owned_account_id" }`. Returns `201 { "meeting_url", "space_name", "calendar_account_id" }` from Google Meet `spaces.create`. The account must already have `meetings.space.created`. Otherwise returns `409 { "code": "meet_connection_required", "account_email" }` so the user can connect that capability. The operation creates a call space, without a Calendar write or invitation. Provider failures return `502`. Do not automatically retry an unknown provider outcome because a space might already have been created.

### `GET /api/oauth/google/callback`

Verifies the HMAC state, the browser cookie and the single-use `oauth_transactions` row, exchanges the code, encrypts the token with AES-256-GCM and upserts `calendar_accounts`, `email_accounts` (when initiated via `/email/connect`), or `drive_accounts` (when initiated via `/drive/connect`). It clears that flow's one-use browser cookie and sends `Cache-Control: no-store`. On success it links the owner's meetings without a calendar account whose `account_email` matches, sets `is_owner` on tasks of the person with that email, and redirects to `return_to?calendar_connected=<accountId>` (or `email_connected` / `drive_connected`). When cancelled (`error=access_denied`), expired or invalid, browser navigations redirect (`302`) back to the sanitized `return_to` (or `/`) with `oauth_error=cancelled`, `expired` or `failed`. The Microsoft and Zoom callbacks answer the same way. Callers with `Accept: application/json` receive `{ "account": {...} }` (`200`) or a `400` JSON error.

> [!WARNING]
> Start Google OAuth only through `/calendar/connect`, `/email/connect` or `/drive/connect` (and similarly `/zoom/connect` for Zoom). A handcrafted callback URL fails (`400` JSON for `Accept: application/json`, or a `302` redirect to `/?oauth_error=failed` for browsers) because the state signature, the browser cookie or the single-use nonce does not match. A failed callback still consumes its nonce.

### `GET /calendar/events`

| Query             | Default       | Meaning                                                                                                                                                                                                                                                                                   |
| ----------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `account_ids`     | all accounts  | Comma-separated `calendar_accounts` IDs                                                                                                                                                                                                                                                   |
| `time_min`        | 7 days ago    | RFC 3339                                                                                                                                                                                                                                                                                  |
| `time_max`        | 14 days ahead | RFC 3339                                                                                                                                                                                                                                                                                  |
| `sync`            | off           | `true` fetches events from selected accounts. Google and Zoom expand occurrences with `singleEvents=true`, and Outlook uses Microsoft Graph Calendar View. Sync upserts `meeting_series` when a provider supplies recurring identity. Google recurring descriptions can supply link notes |
| `include_hidden`  | off           | `true` retains hidden events for native recording-to-occurrence matching, with their `hidden` flag                                                                                                                                                                                        |
| `unassigned_only` | off           | `true` returns local meetings without a calendar assignment and skips provider sync                                                                                                                                                                                                       |

Returns `{ "events": [...], "accounts": [...] }`. Each event has `start` and `start_at`, `end` and `end_at`, `calendar_email` and `account_email`, `recurring_event_id`, `hidden`, and `platform` (`google_meet`, `zoom_native`, `teams_native`, or `other` without a call link). Date-only all-day boundaries remain `YYYY-MM-DD` with an exclusive end date. Sync requests regular Google events (`eventTypes=default`). Cancelled events, working locations, focus time, out-of-office blocks, birthdays and Gmail-generated events are excluded before meeting context is created. Hidden occurrences and series are excluded unless `include_hidden=true`. Google copies group by `ical_uid` and the normalized `original_start_at` for recurring events. The organizer copy wins when present. If a selected copy is hidden, the grouped occurrence is also hidden. Different recurrence dates and events with unrelated UIDs stay separate. The response also projects local scheduled meetings within the requested range, even without a connected calendar, with `origin: "alim"` and `meeting_id`. A Google event created for a scheduled meeting replaces its local projection when Google returns it, including when only an attendee calendar is selected. An unassigned local meeting remains visible when connected calendars are filtered. Opening this entry uses its existing meeting. The first actual capture sets its recording start and origin without changing its scheduled times.

### Hidden calendar events

`POST /calendar/hidden-events` takes `{ "calendar_account_id", "calendar_id", "event_id", "recurring_event_id", "scope", "title", "start_at" }`. `scope` is `event` for one occurrence or `series` for every occurrence with that Google `recurring_event_id`, including future ones. A series request requires a nonempty recurring ID. The calendar account must belong to the caller, and `calendar_id` must match it. Titles and start times are display snapshots, never matching keys.

Returns `{ "hidden_event": { "id", "calendar_account_id", "calendar_id", "event_id", "recurring_event_id", "scope", "title", "start_at", "account_email" } }` with `200`. Repeating the same target returns its existing row. `GET` returns `{ "hidden_events": [...] }` in the same shape. `DELETE` returns `204`. Hiding is scoped to the owner, connected calendar, calendar ID and event or series ID. It never changes Google Calendar or removes saved meeting notes. Separate occurrence hides remain when a series is restored. Disconnecting a calendar removes its hide preferences.

## Email connections

Gmail and Outlook access are optional and separate from Calendar and ordinary sign-in.

| Method   | Path                                   | Auth          | Purpose                                                                                                                   |
| -------- | -------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `GET`    | `/email/accounts`                      | User          | Returns `{accounts: [...]}` with account ID, email, sync status, last sync time and active `sync_progress`.               |
| `POST`   | `/email/connect`                       | User          | Starts OAuth. Accepts optional `provider`, `return_to` and `login_hint`. Returns `auth_url`, `redirect_uri` and `scopes`. |
| `POST`   | `/email/accounts/{id}/sync`            | Account owner | Starts or joins the current sync. Use `Prefer: respond-async` to return immediately.                                      |
| `GET`    | `/email/accounts/{id}/sync`            | Account owner | Polls the current run or returns its latest result for ten minutes.                                                       |
| `DELETE` | `/email/accounts/{id}`                 | Account owner | Stops sync and deletes local credentials and imported threads. Original mail and Calendar connections remain.             |
| `GET`    | `/email/threads`                       | User          | Searches retained discussions across owned mailboxes.                                                                     |
| `POST`   | `/email/threads/{id}/links`            | User          | Manually attach an owned project/topic entity to an email thread (`manual_project_ids`).                                  |
| `DELETE` | `/email/threads/{id}/links/{entityId}` | User          | Detach and exclude an entity from an email thread (`excluded_project_ids`).                                               |
| `GET`    | `/email/threads/{id}/link-suggestions` | User          | Unlinked Hybrid RRF project/topic suggestions for an email thread.                                                        |
| `GET`    | `/knowledge/entities/{id}/emails`      | Entity owner  | Returns `{threads: [...]}` for a person or project.                                                                       |

The default provider, `gmail`, returns through `/api/oauth/google/callback`. Use `microsoft` for Outlook and `/api/oauth/microsoft/callback`. Connecting or syncing Gmail returns `400` when Gmail is unavailable for that user.

### Read an email thread

`GET /email/threads` returns up to 500 matching threads, newest first, in `{threads: [...]}`. Reads use saved mail and make no provider calls.

| Field                              | Meaning                                                                                                                                                      |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `account_ids`                      | Optional comma-separated list of owned mailboxes. Omit to search all.                                                                                        |
| `q`                                | Case-insensitive search of subject, addresses, linked people’s names and message text.                                                                       |
| Thread                             | `id`, `subject`, `last_message_at`, `account_id`, `account_email`, `provider`, `classification_status` and `messages`.                                       |
| Message                            | `id`, `from`, `to`, `sent_at`, `body_text`, `direction` (`sent` or `received`) and `web_url`. Gmail also includes `gmail_url`.                               |
| `people_by_address`                | Known workspace participants, keyed by address.                                                                                                              |
| `match`                            | Search hit kind (subject, address, person or body), display text and matching message ID when applicable. A person hit includes their participating address. |
| `linked_work`                      | Associated projects and tasks or deadlines whose latest resolution cites this thread. Entries include current titles, states and due dates where available.  |
| `linked_projects`, `linked_people` | Canonical linked project/topic and person summaries (`{id, name}`) resolved from thread links and participant addresses.                                     |

Search, display, project classification and task resolution use messages that match current workspace people. They strip repeated reply history with `dedupeEmailThreadMessages`. The stored plaintext in `email_threads.messages` stays intact.

### Sync a mailbox

The web app requests a sync after OAuth or when the user chooses **Sync**. The server checks every five minutes. Scheduled and explicit requests share one run per owner and mailbox. Synchronous requests and the agent tool wait up to 90 seconds before returning progress.

| Status        | Meaning                                                                                                                      |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `202` on poll | `progress` includes address counts (`searched`, `total`), saved message count (`saved`) and Gmail’s `waiting` flag.          |
| `200` on poll | Returns `account` and `synced_messages`. A deadline or persistent Gmail rate limit after a save can return partial progress. |
| `409`         | Invalid grant or insufficient Gmail permission. The account is marked revoked.                                               |
| `410` on poll | No run is available.                                                                                                         |
| `429`         | Gmail rate limit persisted before any messages were saved.                                                                   |
| `502`         | Other Gmail API refusals return a sanitized message.                                                                         |

- **Coverage.** A newly eligible address starts with up to 500 results from the last 90 days. Later searches overlap the previous successful search by 15 minutes and fetch missing message IDs. The checkpoint stores eligible addresses, person IDs and the search start time.
- **Gmail.** The worker follows incremental pages, paces reads by [method cost](https://developers.google.com/workspace/gmail/api/reference/quota) and honors `Retry-After`. One request can retry for ten minutes within a six-hour run.
- **Outlook.** Incremental searches run by day. If a day reaches 1,000 results for an address, sync reports `partial` and keeps that cutoff. The worker checks sender and recipient headers before fetching the body, excludes the owner’s addresses from the search and skips attachments.
- **Project matching.** Saved mail and project changes wake a separate worker. It checks retained threads against active, unmerged projects even when Gmail sync is off. The worker rechecks addresses, masks sensitive details through `OPENSCRIBE_PII_URL`, then sends redacted text and opaque project labels to Decisions. A match in any section links the project.
- **Classification status.** Unfinished work (`processing`) resumes before retries. Redaction and decision failures set `pending_redaction` and `pending_classification` respectively. Thread-specific failures retry after five minutes to six hours.
- **Provider throttling.** A Decisions HTTP 429 pauses classification for that owner until `Retry-After` or the next backoff interval. Token throttling halves the next project batch. Successful full batches grow again up to 32 questions. Deferred logs contain a reason code such as `provider_http_429` or `timeout` and omit message and response text.

## Google Drive

Drive access is optional, read only and separate from sign-in, Calendar and Gmail. Alim never writes to Drive. Every user can pick files through the Google Picker with the non-sensitive `https://www.googleapis.com/auth/drive.file` scope. Server search also requests `https://www.googleapis.com/auth/drive.readonly`, which is offered only where `drive_search_enabled` is `true` (reviewers on the hosted server until Google verifies the scope).

| Method   | Path                                | Auth          | Purpose                                                                                                                                                                                                                    |
| -------- | ----------------------------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET`    | `/drive/accounts`                   | User          | Return `{accounts: [{id, email, display_name, status, search}]}`. `status` is `connected` or `reconnect_required`                                                                                                          |
| `POST`   | `/drive/connect`                    | User          | Start Drive consent with optional `return_to` and `login_hint`. Return `auth_url`, `redirect_uri` and `scopes`. `400` when Drive is off                                                                                    |
| `DELETE` | `/drive/accounts/{id}`              | Account owner | Delete the stored token and every file linked through the account. Files in Drive and other Google connections stay                                                                                                        |
| `POST`   | `/drive/accounts/{id}/picker-token` | Account owner | Return `{access_token, expires_at}` for the Google Picker. Sent with `Cache-Control: no-store`                                                                                                                             |
| `GET`    | `/drive/accounts/{id}/search`       | Account owner | Search with `q` and return up to 20 `{files: [{file_id, title, mime_type, web_view_link, modified_time}]}`. `403` without search access                                                                                    |
| `GET`    | `/drive/links`                      | Target owner  | Return `{links: [...]}` for one `meeting_id`, `entity_id` (person or project) or `email_thread_id`, newest first and once per file                                                                                         |
| `POST`   | `/drive/links`                      | Target owner  | Link `{account_id, file_id}` to one target, read its metadata and redacted text, and return `{link}`. Linking the same file again refreshes that link                                                                      |
| `POST`   | `/drive/links/from-url`             | Target owner  | Detect a pasted Drive file or folder URL for a target, auto-linking files under `drive.readonly`, returning `picker_required` under `drive.file`, or returning up to 20 direct non-folder children for folder confirmation |
| `POST`   | `/drive/links/import-folder`        | Target owner  | Link up to 20 `{account_id, file_ids}` selected from a Drive folder confirmation onto one target                                                                                                                           |
| `GET`    | `/drive/links/{id}`                 | Link owner    | Return `{link}` with its saved `text`                                                                                                                                                                                      |
| `POST`   | `/drive/links/{id}/refresh`         | Link owner    | Read the file again and update every link of it under the same account                                                                                                                                                     |
| `DELETE` | `/drive/links/{id}`                 | Link owner    | Remove one link and its saved text. The file stays in Drive                                                                                                                                                                |

Consent starts without `include_granted_scopes`, so the Drive token carries only Drive scopes and never the Gmail or Calendar ones. The callback saves only the scopes Google granted and requires `drive.file` or `drive.readonly`. A user who may not search keeps no `drive.readonly`, and search checks the reviewer list again on every call. A meeting target resolves to its root meeting, and listing a meeting includes links made on its grouped sources.

A link has `id`, `account_id`, `file_id`, `title`, `mime_type`, `web_view_link`, `modified_time`, `text_status`, `text_chars`, `fetched_at` and one of `meeting_id`, `entity_id` or `email_thread_id`. Google Docs and Slides export as plain text, Google Sheets as CSV of the first sheet, and plain text and JSON files download directly, up to 4 MB, keeping the first 32,000 characters. Extracted text passes financial keyword checks (`CheckNoFinancialData`) and redaction through `OPENSCRIBE_PII_URL` (failing closed if redaction is unavailable). `text_status` is `ready`, `truncated`, `metadata_only` (PDFs and other types) or `withheld` when financial checks match or redaction fails, in which case no text is saved. A refused or insufficient grant returns `409 { "code": "reconnect_required" }` and marks the account. A file the account cannot open returns `404`, and Google rate limits return `503`.

## Zoom connections

| Method   | Path                       | Auth                            | Purpose                                                                                                                 |
| -------- | -------------------------- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `GET`    | `/zoom/accounts`           | User                            | List owned Zoom connections with ID, email and display name                                                             |
| `POST`   | `/zoom/connect`            | User                            | Start Zoom OAuth with optional `return_to`                                                                              |
| `GET`    | `/api/oauth/zoom/callback` | Signed state and browser cookie | Save one encrypted grant, discover the native calendar if authorized, and return with `zoom_connected` or `oauth_error` |
| `DELETE` | `/zoom/accounts/{id}`      | Account owner                   | Remove the local Zoom connection                                                                                        |
| `POST`   | `/meeting-links/zoom`      | Account owner                   | Create a scheduled Zoom meeting and return `201 { "meeting_url" }`                                                      |

The link body accepts `account_id`, `title`, RFC 3339 `scheduled_start_at` and `scheduled_end_at`, an IANA `scheduled_timezone` and an optional stable `request_id` for retry. New meetings must start in the future and end within 24 hours. If the Zoom grant needs renewal, the response is `409 { "code": "zoom_connection_required", "message" }`. Repeating a successful request returns its stored participant link. A request with an uncertain result is not silently repeated.

### Editing a scheduled event

A local schedule edit uses `PATCH /meetings/{id}`. It accepts `scheduled_start_at` and `scheduled_end_at` as RFC 3339 instants, an IANA `scheduled_timezone`, `participant_emails`, a web `meeting_url`, a text `location`, and `event_notes`. The server checks calendar ownership, validates the resulting interval, and preserves the occurrence ID and capture clocks. The date, place and notes fields are also available when creating a plan. To open a listed provider event, send its account, calendar, event ID and `calendar_event_start` to `POST /meetings`. Alim reads organizer status from the provider.

Opening a calendar occurrence that already has a recording attaches its schedule to the same meeting. Calendar sync preserves the recording title, call URL, capture platform and any guest addresses already recorded.

A meeting exposes `can_edit_schedule` and, for a shared schedule, `calendar_sync` with its last sent guest list, pending fields and revision. The detail response includes `attendees` with exact-address person links when available. To notify guests explicitly, call `POST /meetings/{id}/calendar-update` with a stable `request_id`. Send the meeting’s `schedule_revision` as `expected_revision` to bind notification to the version shown, including the first send. A first send can include `calendar_account_id`. The response contains the meeting and the number notified. Google invitation consent is required.

### Preview fields from a sentence

`POST /editing/suggest` accepts an authenticated request with `scope` (`person` or `event`) and a draft `text` of up to 2048 bytes. It returns `{"changes":[{"field":"location","value":"Berlin"}]}` for a person draft such as “Moved to Berlin”. Clear field values are parsed directly. The owner's configured Decisions provider can classify ambiguous phrases. Applying an edit uses the corresponding entity or meeting endpoint.

## Meetings

| Method   | Path                                            | Auth | Purpose                                                                                                                                       |
| -------- | ----------------------------------------------- | ---- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET`    | `/search/suggestions?q=`                        | User | Filter suggestions for people, projects, tags and accounts                                                                                    |
| `GET`    | `/meetings`                                     | User | List and filter meetings, 200 rows per page                                                                                                   |
| `POST`   | `/meetings`                                     | User | Create a meeting                                                                                                                              |
| `POST`   | `/capture-sessions`                             | User | Resolve a capture session to one scheduled meeting occurrence                                                                                 |
| `PATCH`  | `/capture-sessions/{sessionId}`                 | User | Publish capture state or a presence heartbeat                                                                                                 |
| `GET`    | `/meetings/{id}`                                | User | Meeting with transcript, notes, files and series                                                                                              |
| `GET`    | `/meetings/{id}/transcript`                     | User | One complete source transcript as JSON, text or Markdown                                                                                      |
| `POST`   | `/meetings/{id}/sources/{otherId}/combine`      | User | Combine a suggested pair                                                                                                                      |
| `POST`   | `/meetings/{id}/sources/{otherId}/dismiss`      | User | Remember that these two occurrences are separate                                                                                              |
| `DELETE` | `/meetings/{id}/sources/{sourceId}`             | User | Remove one imported transcript from this occurrence                                                                                           |
| `PATCH`  | `/meetings/{id}`                                | User | Update state, language, title, summary, tags or account                                                                                       |
| `PATCH`  | `/meetings/{id}/action-items/{itemId}/assignee` | User | Set `assignee_person_id` on one saved to-do by its meeting item ID. Returns the updated meeting, or 404 if the item is gone.                  |
| `DELETE` | `/meetings/{id}`                                | User | Delete a meeting and everything that cites it                                                                                                 |
| `PATCH`  | `/series/{id}`                                  | User | Set `manual_summary`, `manual_projects`, `manual_deadlines`                                                                                   |
| `DELETE` | `/meetings/{id}/series`                         | User | Unlink a meeting from its series for good                                                                                                     |
| `POST`   | `/meetings/{id}/links`                          | User | Manually attach an owned project/topic entity to a meeting (`manual_project_ids`)                                                             |
| `DELETE` | `/meetings/{id}/links/{entityId}`               | User | Detach and exclude a project/topic entity from a meeting (`excluded_project_ids`)                                                             |
| `GET`    | `/meetings/{id}/link-suggestions`               | User | Unlinked Hybrid RRF project/topic suggestions for a meeting                                                                                   |
| `POST`   | `/meetings/{id}/summarize`                      | User | Request a detailed brief, action items, tag suggestions and a follow-up email draft. Meeting processing writes the short overview separately. |
| `POST`   | `/meetings/{id}/ask`                            | User | Ask a question about one meeting                                                                                                              |
| `GET`    | `/meetings/{id}/ask`                            | User | Saved Q&A threads for one meeting                                                                                                             |
| `POST`   | `/meetings/{id}/calendar-update`                | User | Send the reviewed Google Calendar invitations or event update                                                                                 |
| `POST`   | `/editing/suggest`                              | User | Preview fields from a person or event draft                                                                                                   |
| `GET`    | `/handoff/{kind}/{id}`                          | User | Full text context for a meeting, person, project or tag. Optional `source_id` or `version_id` selects the transcript or revision              |
| `POST`   | `/meetings/{id}/handoff`                        | User | Context bundle for an AI app                                                                                                                  |

Ending a recording and saving a later transcript batch each queue meeting processing in the same transaction as the save. If queueing fails, the request fails and the client can retry the save.

### `GET /search/suggestions`

Returns `{ "suggestions": [{ "kind", "id", "label", "subtitle", "confidence", "source" }], "query": "..." }`. `kind` is `person`, `project`, `tag` or `account`. Exact, prefix and lexical matches return with `source: "match"`. With `TYPESAFE_API_KEY` set, ambiguous queries send only the query and up to 30 candidate labels to Typesafe System One (`jev-1.14.0`, `source: "jev"`). Provider errors never block search.

### `GET /meetings`

| Query               | Matches                                                                                                                                                                                                  |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `person_ids`        | Person entity or `people_profiles` IDs, via participants, resolved imported speakers, assigned tasks, confirmed transcript references or detail evidence. Merged IDs follow the person they now identify |
| `project_ids`       | Project entity IDs, via detail evidence, confirmed transcript references, project tasks, linked `series` or an explicit project name or alias                                                            |
| `tag_ids`           | `meetings.tags` and timestamped `knowledge_tag_mentions`                                                                                                                                                 |
| `account_ids`       | Calendar account IDs                                                                                                                                                                                     |
| `emails`            | Participant or account emails                                                                                                                                                                            |
| `series_id`         | Occurrences of one series                                                                                                                                                                                |
| `q`                 | Title, overview, summaries, linked person and project names, and transcript text, including grouped sources                                                                                              |
| `verification_mode` | `real`, `controlled_test` or `fixture`                                                                                                                                                                   |
| `offset`            | Rows to skip, default `0`                                                                                                                                                                                |

Values combine with OR inside one parameter and AND across parameters. Each call reads up to 200 canonical meeting rows and checks their source records against the filters, so `items` can be short or empty while `next_offset` is nonzero. Request `offset = next_offset` until it is `0`. Returns `items` and `next_offset`, sorted by `-started_at, -created, -id`. The first page also returns legacy capture IDs in `meeting_aliases`. Each grouped occurrence appears once. Rows and meeting details include `linked_people` and `linked_projects` with canonical entity IDs and names. Every item has `import_source`, `import_label` and `import_meta` (`""`, `""` and `{}` for captured meetings).

### `POST /meetings`

```json
{
  "title": "Team sync",
  "calendar_account_id": "",
  "calendar_id": "primary",
  "calendar_event_id": "",
  "recurring_event_id": "",
  "platform": "google_meet",
  "state": "recording",
  "capture_capability": "per_participant_pcm",
  "meeting_url": "https://meet.google.com/abc-defg-hij",
  "language_mode": "auto",
  "language_code": "",
  "verification_mode": "real",
  "local_recording_meta": {
    "sample_rate": 48000,
    "channels": 1,
    "recoverable": true,
    "time_origin_epoch_ms": 1794233220000
  }
}
```

`scheduled_start_at` and `scheduled_end_at` optionally create a local scheduled meeting. Supply both as RFC 3339 instants with the end after the start. `scheduled_timezone` is an IANA timezone, defaulting to UTC. `participant_emails` is an optional array, validated, lowercased and deduplicated. A scheduled meeting defaults to `preview` with empty recording timestamps and no recording time origin. These fields are included in serialized meeting records. By default scheduling saves locally. Set `send_invites: true` with a stable `request_id`, an owned Google calendar account and at least one guest to insert an event with `sendUpdates=all`. If consent is missing, returns `409 { "code": "calendar_invite_connection_required", "account_email" }`. Repeat the same request ID and details on retry. Google sends the invitations. Alim keeps the Google event ID and iCalendar UID.

For unscheduled captures, `started_at` is optional and defaults to now. `meeting_languages` is optional and defaults to the account setting, which the meeting keeps as its snapshot. `tags` takes owned tag IDs. `calendar_account_id` plus `recurring_event_id` links or creates a `meeting_series`. Import fields and `account_email` cannot be set here. A meeting without `calendar_account_id` whose `account_email` is a connected account's email is linked to that account. Returns `201` with the meeting.

### `GET /meetings/{id}`

The canonical meeting ID opens its primary transcript. A grouped source ID opens that source on the same meeting page. Set `source_id` to choose a transcript explicitly or `segment_id` to open the source containing a cited segment record. A citation can contain comma-separated segment IDs. An explicit source takes precedence and must belong to this occurrence.

| Key                            | Content                                                                                                                                                                                                                                                                                         |
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `meeting`                      | The canonical meeting record                                                                                                                                                                                                                                                                    |
| `transcript_source_id`         | The selected transcript source meeting ID                                                                                                                                                                                                                                                       |
| `transcript_sources`           | Each source’s `id`, `provider` (such as `alim`, `tactiq` or `tldv`), `started_at` and committed `segment_count`. A grouped source can include its matching `agent_trace`. When alignment is available, add `aligned_offset_ms` to a source-local time to get the time on the primary transcript |
| `source_suggestions`           | Possible copies with `id`, `title`, `provider` and `started_at`                                                                                                                                                                                                                                 |
| `participants`                 | `meeting_participants` with linked `people_profiles`                                                                                                                                                                                                                                            |
| `segments`                     | Every segment of the selected transcript in its original clock, ordered `+start_ms, +created`, with words and `person_id`                                                                                                                                                                       |
| `people`                       | The people `person_id` links, every task assignee and the owner, keyed by entity ID: `id`, `name`, `email`, `brief`, `job_title`, `company`, `country`, `is_owner` and the owner's `photo_url`                                                                                                  |
| `segment_count`, `is_complete` | Total count, and `true` because nothing is truncated                                                                                                                                                                                                                                            |
| `transcript_text`              | Plain text, one `[MM:SS] Speaker: text` line per turn                                                                                                                                                                                                                                           |
| `transcript_markdown`          | Markdown with header, date, participants and turns                                                                                                                                                                                                                                              |
| `notes`                        | Meeting notes and inherited series notes                                                                                                                                                                                                                                                        |
| `attachments`                  | Files with a short-lived `?token=` `file_url` and an owner-scoped `download_url`                                                                                                                                                                                                                |
| `series`, `occurrences`        | The series with its `origin` and up to 100 of its meetings, this one included (`started_at DESC`), with summaries and action items                                                                                                                                                              |

`person_id` is the person entity who spoke a segment, after merges, or `""`. A captured segment takes its participant's person, and unmapped or mixed audio never gets one. An imported speaker label takes the person the meeting's extraction resolved it to, else the owner by the owner's name, else the one person with that exact full name of two or more words. Reading a meeting writes nothing. Only this route returns `person_id` and `people`. `brief` is the manual brief, or the automatic one when no role or location describes the person.

`action_items[].task_id` is the canonical task ID for task routes. Use the meeting-scoped `action_items[].id` to assign one to-do through `PATCH /meetings/{id}/action-items/{itemId}/assignee`, including older items without a task ID. A checklist edit keeps existing task assignments. Send an empty `assignee_person_id` to the assignment route to clear one.

A source decision (`combine` or `dismiss`) takes no body and returns `{ "meeting_id": "<canonical ID>" }`. Sources keep their original segment IDs and timestamps when combined. A dismissed pair stays separate.

### `GET /meetings/{id}/transcript`

| Query                     | Values                                                                                                 |
| ------------------------- | ------------------------------------------------------------------------------------------------------ |
| `format`                  | `json` (default), `text` (`text/plain`), `markdown` or `md` (`text/markdown`)                          |
| `source_id`, `segment_id` | Select the source as on the meeting detail route                                                       |
| `include_partials`        | `true` adds partial segments. Committed segments only by default, unless the meeting has only partials |

The JSON shape is `{ "meeting_id", "transcript_source_id", "title", "started_at", "ended_at", "is_complete", "segment_count", "transcript_text", "transcript_markdown", "participants", "segments" }`. `meeting_id` identifies the occurrence. The text, dates and offsets come from the selected transcript. Plain text and Markdown use the current name of a linked speaker. The JSON segment retains its original `speaker_name_snapshot`. Meeting detail includes `knowledge_job_id`, the last finished extraction receipt on the occurrence, or an empty string before its first result. The JSON transcript and meeting detail can include `segments[].entity_mentions` after extraction. Each link contains the verbatim `text`, current `entity_id`, storage `kind` (person or project), `method` (`exact_name` or `decision`), `agent_version` and `confidence`. The segment remains attributed to its original speaker. The optional `unresolved_entity_mentions` list names phrases that should stay plain text when an in-meeting speaker has the same name.

### `PATCH` and `DELETE /meetings/{id}`

`PATCH` accepts `state` (`preview`, `waiting`, `joined`, `recording`, `ended`, `failed`), `capture_capability`, `language_mode`, `language_code`, `title` (a blank one is ignored), `summary`, `manual_summary`, `action_items`, `followup_email_draft`, `manual_projects`, `manual_deadlines`, `tags`, `calendar_account_id`, `ended_at` and `local_recording_meta`. When a grouped source ID is patched, the title, summaries, tasks, tags, projects, deadlines, follow-up draft and account choice update the shared occurrence. Recording state, language, capture capability, recording metadata and end time update the addressed source. Choosing an account sets `account_email` to its email. Clearing it falls back to the Meet URL email or the import source account. A meeting whose state turns `ended` joins a series by the series rules, without an AI call ([People, projects and tasks](/docs/people-and-projects.md)).

`DELETE /meetings/{id}/series` takes the meeting out of its series and records the series in `series_kept_apart`, so no rule or model links it there again, and meetings unlinked from one series are never grouped together again. Series notes stay. The series is deleted only when no meeting, note, evidence, manual summary, project or deadline remains. Returns the updated meeting.

`DELETE /meetings/{id}` deletes the occurrence and all its source transcripts. It removes participants, notes, attachments, meeting-only tasks, tag mentions, meeting Q&A threads and meeting evidence. A canonical task cited by another occurrence keeps its ID and surviving citations. Automatic details lose only the deleted source’s evidence and are removed when their last citation disappears. Ask confirmations pass `include_related=false|true` and require the named occurrence to still be the root of a finished recording. An outdated target returns `409`. With `true`, deletion also archives exclusively linked people and projects that have no independent work, saved email address or manual edits. To remove one imported copy, use `DELETE /meetings/{id}/sources/{sourceId}`. Other sources and the occurrence URL survive. Removing the last source deletes the occurrence. Both routes return `204`.

### `POST /meetings/{id}/ask`

To ask about the current meeting only, send this JSON with the user’s session token. Add `thread_id` to continue a conversation.

```json
{
  "question": "What date did we agree on?",
  "past_meetings": 0
}
```

The server saves the question before the model call, then saves the answer or sanitized failure.

| `past_meetings`             | Evidence available to the answer                                                                                                                        |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Omitted                     | Current meeting, matching workspace evidence and earlier occurrences. The built-in agent considers the last three earlier occurrences.                  |
| `0`                         | Current meeting bundle, including its directly linked files and series notes. Earlier answers that used broader scope are excluded from model history.  |
| Positive integer or `"all"` | Current meeting and workspace evidence, plus up to that many earlier occurrences from the same series, newest first, within the agent's context budget. |

Invalid scopes return `400` before saving a turn. The answer can include the thread's completed exchanges in chronological order up to 40,000 characters. `past_meeting_ids`, `truncated_past_meeting_id` and `dropped_past_meeting_ids` describe the series excerpts included or cut. The saved answer's `context.meeting_ids` lists the current meeting followed by the earlier occurrences read.

The read-only `meeting_qa` agent configures `meeting_context_search@v1`, source kinds, search limits, context budgets and one optional follow-up search. It ranks saved people, projects, details, tasks, Drive and uploaded file text and redacted email passages in the caller's workspace. The answer model can ask for a focused second search before sending answer text. Responses include the active `agent_version` and `context_searches`. Workspace citations identify the source with `kind`, its record ID, a label and an excerpt. The meeting-only OAuth MCP tool retains its existing scope. With no configured provider, the HTTP route can return a keyword-matched transcript answer with `verification_mode: "fixture"`.

```json
{
  "answer": "Ada committed to publishing the API contract by Thursday.",
  "citations": [
    {
      "segment_id": "seg_1",
      "start_ms": 12000,
      "end_ms": 18500,
      "speaker": "Ada Lovelace",
      "quote": "I will publish the API contract by Thursday."
    }
  ],
  "provider": "anthropic",
  "model_id": "claude-sonnet-5-5",
  "verification_mode": "real",
  "thread_id": "thd_1",
  "user_message_id": "msg_1",
  "assistant_message_id": "msg_2",
  "thread": {},
  "messages": []
}
```

The first-party response includes plain answer text, resolved `citations`, and optional `parts` with the same shape as saved chat messages. Both the JSON response and the final `done` event carry them. Render `delta.text` immediately, then replace the pending turn with the saved message using `assistant_message_id`. Older replies may omit parts. Ignore unknown part types.

| Part `type`           | Client behavior                                                                                                                                                                       |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `suggested_questions` | Render up to three strings from `questions` as buttons. On tap, submit that question to the same meeting with the current scope and `thread_id`.                                      |
| `task_list`           | New lists support completion and reopening. Load current tasks by ID, then PATCH the selected task only on a user click. A saved `read_only: true` list displays its recorded states. |
| `task_status_chart`   | Display the server-resolved `counts`, grouped by state.                                                                                                                               |
| `bar_chart`           | Plot the labelled numeric values with their unit. Selecting a bar reveals its supporting passage.                                                                                     |
| `diagram`             | Draw the nodes in `items` and the labelled connections in `edges`. Select a node to inspect its evidence.                                                                             |
| `meeting_moments`     | Open the current or earlier occurrence at the cited segment and millisecond offset.                                                                                                   |
| `entity_cards`        | Display the saved name and summary and open the named person or project in Mind.                                                                                                      |

Rich items have `id`, `label` and optional `summary`, numeric `value` and typed `target`. Edges link item IDs with `from`, `to` and an optional `label`.

| Target             | How to open it                                                                                                                  |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| Transcript passage | Use the canonical `meeting_id`, original `source_meeting_id`, `segment_id` and source-local `start_ms`. Zero is a valid offset. |
| Mind record        | Use the stored `entity_id` and `entity_kind` on the current workspace host.                                                     |

The model chooses a presentation and cites the passages it saw. The server resolves destinations, task rows and counts. This saved part opens a passage twelve seconds into an earlier meeting.

```json
{
  "type": "meeting_moments",
  "title": "Earlier decision",
  "items": [
    {
      "id": "item-1",
      "label": "Orchard review",
      "summary": "North orchard yielded 12 samples.",
      "target": {
        "meeting_id": "review_1",
        "source_meeting_id": "capture_1",
        "segment_id": "segment_4",
        "start_ms": 12000
      }
    }
  ]
}
```

Ask and summaries also read the text saved for Drive files linked to the meeting or its grouped sources, at most 8,000 characters per file and 32,000 in all. A cited file has `kind: "drive_file"`, `drive_file_id`, its title as `quote` and its `url`. Knowledge extraction and profile enrichment do not read Drive text. Workspace chat reads the same text for the people, projects and meetings in its context and cites a file inline as `[drive:ID]`. Meeting reads over MCP list linked files as `drive_files` with metadata only.

With `Accept: text/event-stream` the reply is an event stream for OpenAI, Anthropic and Google models. Each `delta` event carries `{ "text" }` to append as the model writes the answer, then one `done` event carries the JSON above, or an `error` event carries `{ "message" }` after the failed attempt is saved. The streamed text equals the saved `answer`. The stream opens with the first text, so a rejected request, a provider that answers whole and the fixture answer keep the JSON reply and its status.

`GET /meetings/{id}/ask` returns `{ "meeting_id", "thread", "threads", "messages" }` with the messages of every Q&A thread of that meeting, newest thread first. `thread` is the newest thread, or `null` before the first question.

### `POST /meetings/{id}/summarize` and `/handoff`

`summarize` writes `summary`, `action_items` (with `evidence_segment_ids` and `evidence_quote`), `suggested_tags` and a copyable `followup_email_draft`, which is never sent. An edited draft stays visible after another briefing. A generated action item ID is `act-` plus 12 hex characters of SHA-256 of `<meeting id>|<lowercased text>`, so regenerating keeps each item on its task. Regenerating moves only the state and due date of an existing task.

`handoff` takes `{ "target": "claude" | "chatgpt" | "codex" | "t3" }` plus an optional `source_id` to select a transcript, and returns `copyable_context`, a meeting resource URI and a prompt link in `launch_url` for Claude and ChatGPT or `desktop_uri` for Codex and T3 Code. The link names the selected meeting and tells the agent how to read it through MCP.

## Transcript ingestion

| Method | Path                        | Auth | Purpose                                                                                                                                                                       |
| ------ | --------------------------- | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST` | `/meetings/{id}/transcript` | User | Upsert participants and partial or committed segments. A self flag or local microphone identifies that device as the owner throughout the meeting, including earlier segments |

```json
{
  "participants": [
    {
      "platform": "google_meet",
      "participant_device_id": "device-554",
      "display_name": "Ada Lovelace",
      "email": null,
      "transport_source_ids": ["554"],
      "attribution_mode": "one_mapped_source",
      "is_self": false
    }
  ],
  "segments": [
    {
      "external_segment_id": "seg-device-554-001",
      "participant_device_id": "device-554",
      "speaker_name_snapshot": "Ada Lovelace",
      "attribution": "one_mapped_source",
      "source_ids": ["554"],
      "unmapped_contributors": [],
      "stream_generation": 1,
      "status": "committed",
      "text": "Hello everyone.",
      "language_code": "en",
      "start_ms": 1200,
      "end_ms": 2100,
      "receive_epoch_ms": 1794233221200,
      "decoded_sample_offset": 57600,
      "rtp_timestamp": 160000,
      "provider": "elevenlabs",
      "words": [
        {
          "text": "Hello",
          "start_ms": 1200,
          "end_ms": 1600,
          "provider_start_s": 0.0,
          "provider_end_s": 0.4,
          "type": "word",
          "speaker_id": "device-554"
        }
      ]
    }
  ]
}
```

Returns `{ "participants": [...], "segments": [...] }`.

- `external_segment_id` is the idempotency key that turns a partial into its committed segment
- Live segments require `one_mapped_source` or `local_mic` attribution, a nonempty `participant_device_id`, no `unmapped_contributors`, and word `speaker_id` values that are empty or match that device. Segments with missing attribution, unmapped or mixed sources, or conflicting word IDs are omitted even if they may contain one speaker. Other segments and participant metadata in the batch are saved atomically. A rejected committed segment removes its matching partial, including partials in the same request, but never a committed segment. Existing records and provider-labeled imports remain supported. The response includes `omitted_segments` so clients can distinguish omitted input from saved lines.
- Accepted attribution is stored as sent. Emails are never invented
- A segment records the supplied `provider`, including `teams_captions` for a Teams browser caption. Omitting it preserves the existing source on update and leaves it empty on a new segment. Teams caption times mark receipt and have no word timestamps.
- Provider word times (`provider_start_s`, `provider_end_s`) apply to words without `start_ms` and `end_ms`. They are offset from `chunk_anchor_ms`, else the segment `start_ms`, else `receive_epoch_ms` minus the meeting time origin, never from the compact decoder clock
- A new participant resolves to a person in the order in [How people merge](/docs/people-and-projects.md#how-people-merge): `is_self` or `local_mic` is the owner, and a full name of two or more words names the one person with that name. One-word and ambiguous names become new people with a `person_merge_candidate` suggestion

## Notes and attachments

| Method   | Path                                                 | Auth | Purpose                                       |
| -------- | ---------------------------------------------------- | ---- | --------------------------------------------- |
| `POST`   | `/meetings/{id}/notes`                               | User | Add a note or link to a meeting or its series |
| `DELETE` | `/notes/{noteId}`                                    | User | Delete a note or link                         |
| `POST`   | `/meetings/{id}/attachments`                         | User | Upload a screenshot or file                   |
| `GET`    | `/meetings/{id}/attachments/{attachmentId}/download` | User | Download raw bytes                            |
| `GET`    | `/meetings/{id}/attachments/{attachmentId}/image`    | User | Image bytes, or JSON with `?format=json`      |
| `DELETE` | `/attachments/{attachmentId}`                        | User | Delete an attachment                          |

Meetings never lock after `ended`. The Mac app adds items only during a live meeting, and the web app adds them afterwards.

### `POST /meetings/{id}/notes`

```json
{
  "scope": "meeting",
  "kind": "link",
  "content": "Sprint 6 tracker",
  "url": "https://github.com/fcakyon/alim/issues/1",
  "provenance": "manual",
  "timestamp_ms": 45000
}
```

With `capture_session_id` and `capture_item_id`, a retry returns the saved note instead of a second one. The Mac notes document uses `capture_item_id` `notes-document`: a repeat replaces its text in place and keeps its ID and timestamp, and empty content deletes it. `capture_item_revision` is a positive, increasing integer for each edit. The server retains the latest revision after deletion, accepts identical retries and rejects stale or conflicting revisions with 409. Unversioned document requests remain supported until a versioned request has been saved for that capture session.

`scope: "series"` attaches the note to the meeting's series. Links default to `ingested_status: "url_only"`. `provenance` accepts `manual`, `calendar_description`, `meeting_chat` and `screenshot_ocr`, and any other value, `import` and `import_ai` included, is stored as `manual`.

### `POST /meetings/{id}/attachments`

`multipart/form-data` with `file`, `kind`, `captured_at_ms`, `window_title`, `source_app`, `extracted_text` and `extracted_links`. `kind` is `screenshot`, `file`, `audio_chunk` or `replay_bundle`. Without it, `.png`, `.jpg`, `.jpeg`, `.webp` and `.gif` become `screenshot` and other files `file`. `extracted_links` is a JSON array, and a screenshot's links become `screenshot_ocr` link notes. `window_title` defaults to the file name for `file`. The response has `file_url` and `download_url`.

`download` sends `Content-Disposition: attachment`, `X-Content-Type-Options: nosniff`, `Content-Security-Policy: default-src 'none'; sandbox` and `Cache-Control: private, no-store`. `image` returns raw bytes for `<img>`, or a base64 JSON envelope with `?format=json` or `Accept: application/json` without `image/`. A non-image attachment returns `400`.

## Transcription

| Method | Path                                      | Auth  | Purpose                                                  |
| ------ | ----------------------------------------- | ----- | -------------------------------------------------------- |
| `GET`  | `/admin/transcription`                    | User  | Active provider, capabilities and catalog                |
| `PUT`  | `/admin/transcription`                    | Admin | Set `provider`, `model_id` and optional `base_url`       |
| `POST` | `/transcription/session`                  | User  | Start a provider session for one stream                  |
| `POST` | `/transcription/check`                    | Probe | Start a fixed synthetic session for deployed provider QA |
| `GET`  | `/transcription/openai-realtime`          | User  | WebSocket relay to OpenAI Realtime                       |
| `GET`  | `/transcription/personal/openai-realtime` | User  | Open the relay for the issued personal OpenAI selection  |
| `POST` | `/transcription/audio`                    | User  | Multipart audio proxy for OpenAI-compatible STT          |

| Provider               | Models                                                               | Session result                                                       |
| ---------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- |
| `elevenlabs` (default) | `scribe_v3_live` (default), `scribe_v2_realtime`                     | Single-use `realtime_scribe` token                                   |
| `openai_realtime`      | `gpt-4o-mini-transcribe`, `gpt-4o-transcribe`, `gpt-live-transcribe` | `token: ""` and a relative `websocket_url` to the server relay       |
| `gemini_realtime`      | `gemini-3.5-transcribe-live`, `gemini-2.5-flash-native-audio-latest` | Single-use token (`uses: 1`) locked to the selected model            |
| `openai_compatible`    | `mlx-community/whisper-large-v3-turbo`, `whisper-1`                  | `token: ""` and `http_transcription_url: "/api/transcription/audio"` |

`GET /admin/transcription` returns `active`, `active_capabilities`, `catalog`, `providers_configured` and `can_edit`. `PUT /admin/transcription` returns `{ "active", "capabilities" }`. `OPENSCRIBE_TRANSCRIPTION_PROVIDER`, `OPENSCRIBE_TRANSCRIPTION_MODEL` and `OPENSCRIBE_LOCAL_STT_BASE_URL` set the default before an admin saves one, and `OPENSCRIBE_LOCAL_STT_API_KEY` is the optional bearer token for that endpoint.

`POST /transcription/check` accepts only a token from the separate `transcription_probes` auth collection. It ignores the request body and uses the active server provider with `qa-provider-check`, 16 kHz PCM, Auto language and manual commits. The response has the session fields below. It reads no meeting or user profile. Probe tokens cannot call user or admin routes, list probe records or change settings. Only a PocketBase superuser can mint a probe token. The migration creates one probe identity with interactive sign-in disabled.

### `POST /transcription/session`

```json
{
  "meeting_id": "optional_meeting_id",
  "participant_device_id": "device-554",
  "audio_format": "pcm_48000",
  "language_mode": "auto",
  "language_code": "",
  "commit_strategy": "vad"
}
```

| Session option       | Behavior                                                                                                                                                                                                           |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `commit_strategy`    | `vad` (default), `manual` or `turn_prediction`.                                                                                                                                                                    |
| `meeting_id`         | Uses the meeting’s saved languages. Omit it to use the account languages.                                                                                                                                          |
| `capture_session_id` | Send with `meeting_id` when multiple captures are active to avoid a `409`. With one active capture the server selects it automatically.                                                                            |
| Provider and model   | A registered capture keeps its personal selection or workspace-default choice across reconnects. Without a registered capture, current settings apply. Sending `provider`, `model_id` or `base_url` returns `403`. |

The response includes the following fields.

- **Connection** includes `provider`, `model_id`, `transport`, `token`, `websocket_url`, `websocket_subprotocols`, `http_transcription_url` and `expires_in_seconds`.
- **Audio** includes `participant_device_id`, `audio_format`, `target_sample_rate` and `commit_strategy`.
- **Recognition** includes `language_mode`, `language_code`, `meeting_languages`, `include_timestamps`, `include_language_detection`, `recheck_cadence_seconds`, `verification_mode`, `setup_payload` and `capabilities`.

Removing or replacing a personal OpenAI key closes relays using that key. Issued Gemini and ElevenLabs sessions follow provider expiry. A reconnect needs the capture’s original credential.

### Relays

- `openai-realtime` checks meeting ownership, dials `wss://api.openai.com/v1/realtime?intent=transcription` and uses the account’s effective model on setup and on every client `session.update`. Language changes, 24 kHz PCM `input_audio_buffer.append` and `input_audio_buffer.commit` pass through
- `audio` forwards multipart audio to the admin `base_url` with the admin `model_id`. Word timestamps and language detection count as unsupported until a real response shows them

## Tags and people

| Method   | Path                        | Auth | Purpose                                                               |
| -------- | --------------------------- | ---- | --------------------------------------------------------------------- |
| `GET`    | `/tags`                     | User | List tags                                                             |
| `POST`   | `/tags`                     | User | Create a tag                                                          |
| `PATCH`  | `/tags/{id}`                | User | Update `name`, `description`, `color`                                 |
| `DELETE` | `/tags/{id}`                | User | Delete a tag                                                          |
| `GET`    | `/people/email-suggestions` | User | Match a typed name or address in this account                         |
| `GET`    | `/people`                   | User | List unmerged people profiles in `{ "people" }`                       |
| `PATCH`  | `/people/{id}`              | User | Set `manual_name`, `email` and `manual_metadata`, returns the profile |
| `POST`   | `/people/{id}/enrich`       | User | Enrich a profile with the `profile_enrichment` model                  |

`PATCH /tags/{id}` requires a non-empty `name` and returns `{ "id", "name", "description", "color", "created", "updated" }`. Each profile has `id`, `email` (null when empty), `platform_ids`, `display_name`, `manual_name`, `effective_name`, `inferred_metadata`, `manual_metadata`, `effective_metadata`, `merged_into` and `entity_id` when a person entity links it. `manual_metadata` holds countries, companies, job titles, responsibilities, LinkedIn and Scholar URLs and links. `enrich` takes `{ "source_url", "source_type", "accessible_text", "meeting_context_id" }`, all optional, and returns `404` for a profile the user does not own.

## Personal AI settings

| Method  | Path           | Auth | Purpose                                                |
| ------- | -------------- | ---- | ------------------------------------------------------ |
| `GET`   | `/settings/ai` | User | Read saved key flags and selections                    |
| `PATCH` | `/settings/ai` | User | Update your provider keys, task models or speech model |

To return speech to the workspace default, PATCH the following body. Use the signed-in account ID and the `revision` from GET (initially `"0"`). Omitted fields keep their values.

```json
{
  "expected_owner": "your_user_id",
  "revision": "revision_from_get",
  "transcription": null
}
```

> [!TIP]
> A `409` means the account or settings changed. Read the current settings before editing again.

| Field           | GET                                       | PATCH                                                                                |
| --------------- | ----------------------------------------- | ------------------------------------------------------------------------------------ |
| `keys`          | Configured flags by provider              | Send a string to replace one credential or `null` to remove it.                      |
| `models`        | Personal workload selections              | Replaces the whole list. An empty array restores all workspace defaults.             |
| `transcription` | Personal cloud speech selection or `null` | Send `provider` and `model_id` in an object, or `null` to use the workspace default. |

Personal selections require a matching saved key. The catalog marks ineligible models with `workspace_key_only`. The server verifies paid access when saving a Google key and before a personal Gemini model request or speech connection.

## Admin AI

| Method | Path                                              | Auth  | Purpose                                                                                              |
| ------ | ------------------------------------------------- | ----- | ---------------------------------------------------------------------------------------------------- |
| `GET`  | `/admin/models`                                   | User  | `catalog`, `settings`, `can_edit` and `providers_configured`                                         |
| `PUT`  | `/admin/models`                                   | Admin | Set the model per workload                                                                           |
| `GET`  | `/admin/agents`                                   | User  | Active `.md` contracts for all built-in AI agents and the website tool registry                      |
| `GET`  | `/admin/agents/{id}`                              | User  | One agent contract, version history, unified diffs, plus owner `rollout_stats` and `recent_rollouts` |
| `PUT`  | `/admin/agents/{id}`                              | Admin | Save a new agent contract revision (prompt, tools, access mode, model or raw `.md`)                  |
| `POST` | `/admin/agents/{id}/versions/{versionId}/restore` | Admin | Restore a prior agent contract revision as a new version                                             |
| `POST` | `/admin/agents/{id}/tools/execute`                | Admin | Execute an allowed website tool under the agent's access mode and owner scope                        |

| Workload             | Default                         |
| -------------------- | ------------------------------- |
| `tagging`            | `openai` `gpt-6-luna`           |
| `profile_enrichment` | `openai` `gpt-6-luna`           |
| `qa`                 | `anthropic` `claude-sonnet-5-5` |
| `summary`            | `anthropic` `claude-sonnet-5-5` |
| `action_items`       | `google` `gemini-3.8-flash`     |
| `decisions`          | `google` `gemini-decision-1`    |

The catalog lists OpenAI `gpt-6-luna`, `gpt-6.1-terra`, `gpt-6.1-sol` and `gpt-6-astra`, Anthropic `claude-haiku-5-5`, `claude-sonnet-5-5`, `claude-opus-5-5` and `claude-fable-5-2`, and Google `gemini-3.5-flash-lite`, `gemini-3.8-flash`, `gemini-4-argon`, `gemini-4-hydrogen` and `gemini-4-carbon`, plus the decision models Google `gemini-decision-1` and TypeSafe `jev-1.14.0`. `qa` serves both meeting Q&A and workspace chat. `decisions` answers topic matching, email classification, duplicate and series checks and takes only a provider with a decision API (`openai`, `google`, `typesafe`). When using workspace defaults, `decisions` automatically falls back across configured decision providers (for example `google` to `typesafe`). Personal key overrides stay pinned. API keys stay on the server.

```json
{
  "settings": [
    { "workload": "tagging", "provider": "openai", "model_id": "gpt-6-luna" },
    { "workload": "qa", "provider": "anthropic", "model_id": "claude-sonnet-5-5" }
  ]
}
```

## Knowledge

People (`kind: "person"`) and projects (`kind: "project"`) are knowledge entities with structured details, evidence, tasks and versions. How they behave is in [People, projects and tasks](/docs/people-and-projects.md).

### Entities

| Method   | Path                                               | Auth | Purpose                                                                                                 |
| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------------------------------------------------- |
| `GET`    | `/knowledge/entities`                              | User | List people and projects                                                                                |
| `POST`   | `/knowledge/entities`                              | User | Create a person or project                                                                              |
| `GET`    | `/knowledge/entities/{id}`                         | User | Full entity page payload                                                                                |
| `PATCH`  | `/knowledge/entities/{id}`                         | User | Update name, emails, brief, status, pin                                                                 |
| `POST`   | `/knowledge/entities/{id}/merge`                   | User | Merge into `target_entity_id`                                                                           |
| `POST`   | `/knowledge/entities/{id}/details`                 | User | Add a detail                                                                                            |
| `PATCH`  | `/knowledge/details/{detailId}`                    | User | Edit a detail                                                                                           |
| `DELETE` | `/knowledge/details/{detailId}`                    | User | Remove a detail                                                                                         |
| `GET`    | `/knowledge/entities/{id}/files`                   | User | List uploaded files attached to a person or project                                                     |
| `POST`   | `/knowledge/entities/{id}/files`                   | User | Upload a local file (up to 50 MB) to a person or project, redacting plain text via `OPENSCRIBE_PII_URL` |
| `GET`    | `/knowledge/entities/{id}/files/{fileId}/download` | User | Owner-scoped download with `Content-Disposition: attachment` and sandbox headers                        |
| `DELETE` | `/knowledge/entities/{id}/files/{fileId}`          | User | Delete an uploaded entity file                                                                          |

`GET /knowledge/entities` filters: `kind`, `q` (name, brief, email and active details), `status` (`active` default, `provisional`, `archived`, `all`), `project_id` and `tag_id`. It returns `{ "entities": [...], "people": [...], "projects": [...] }`. Each entity has `id`, `kind`, `canonical_name`, `manual_name`, `effective_name`, `email`, `person_profile_id`, `status`, `current_brief`, `manual_brief`, `effective_brief`, `pinned`, `last_observed_at`, `active_details_count`, `pending_suggestions_count`, `open_tasks_count` and `project_roles`.

`current_brief` is a one-line tagline, never a summary. A project takes the tagline of its newest extraction. A person's is at most two of their roles and responsibilities, each with its project, joined with `·`, and empty without any. `effective_brief` is `manual_brief` when set, else `current_brief`.

`POST` takes `{ "kind", "name", "manual_name", "email", "emails", "person_profile_id", "manual_brief", "pinned", "tag_ids", "series_id" }` and returns `201` with the page payload. A person links to an owned profile or creates one. Version 1 is recorded with `trigger_kind: "manual"`.

`GET /knowledge/entities/{id}` also accepts a `people_profiles` ID. It returns `entity`, `details` (each with `evidence`), `history`, `relations`, `members`, `projects`, `tags`, `tasks`, `todos`, `deadlines`, `meetings`, `suggestions`, `evidence`, `is_historical_view`, `read_only`, `latest_version_id`, `version_count` and `deadline_changes`. The entity includes its `do_not_merge_with` IDs and name slugs. Previous due dates are available on the current page. Revision summaries and full snapshots are served by the versions route. With `?version_id=` it shows that version's snapshot with `is_historical_view: true`, `selected_version` and `read_only: true`, and changes nothing.

`PATCH` accepts `manual_name` (or `name`), `canonical_name`, `email` or `emails` (people), `manual_brief`, `status` (`active`, `provisional`, `archived`), `pinned` and `tag_ids`, syncs name and email to the linked profile and records a `manual` revision.

A person detail returns ordered `emails`. The first is also returned as `email` for single-address clients. On PATCH, `emails` replaces the full list. Send `[]` to clear it. An editor may include `previous_emails` with the list it opened to preserve independent address additions and removals from a concurrent edit. An invalid address or one assigned to another named person returns `400` with the reason. Choosing the address of an unnamed contact can link that contact to the person. The update and its revision are atomic.

`GET /people/email-suggestions?q=...` returns up to 12 distinct `{email, name}` matches in `items`, using the authenticated account’s saved contacts, meeting and invitee metadata, connected account addresses and retained message headers. An empty query returns an empty list. Unnamed contacts can appear here even when they have no directory entry.

`merge` takes `{ "target_entity_id": "..." }` of the same kind. Both IDs may be entity or profile IDs and follow `merged_into` first. Merging into itself returns `400`. For people:

- The target keeps its primary email and retains access to both address lists. A person merge can include `preferred_name`, the exact displayed name of either selected person. This saves a manual name on the survivor. Without a choice, an existing manual name takes precedence, then a recorded full name takes precedence over a short label or address.
- The target gains the source's platform IDs, participants, details with evidence, tasks, suggestions and links
- Tasks that move to the owner's person become `is_owner`
- Pending `Maybe` proposals naming the source are dropped
- The source keeps `merged_into`, so later lookups follow it. No route splits a merge

For projects, merging retains the source names, normalized key and previous aliases in `current_attributes.aliases`. Matching also reads `manual_attributes.aliases`. Saved `projects` and `manual_projects` on owned meetings and series replace absorbed names or slugs with the surviving effective name, with repeats removed. Pending proposals between the merged projects become accepted, and other suggestions point to the survivor.

Both project and person merges collapse repeated active details and tasks after references move. Details combine evidence without repeated source rows. Tasks retain manual field locks, completed state, combined tags and evidence segment IDs, earliest/latest evidence bounds and latest mention time. Retracted tasks remain tombstones. Affected meeting action items refresh to the canonical tasks, including tasks supported by their transcript segments.

### Detail kinds

| Kind             | Fields                                                                                                                                             |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `note`           | `value_text`, optional `label` and related person, project or tag                                                                                  |
| `role`           | `value_text`, optional `related_project_id` so one person holds different roles per project                                                        |
| `responsibility` | `value_text`, optional project or tag                                                                                                              |
| `location`       | `value_text`                                                                                                                                       |
| `skill`          | `value_text`, optional tag or project                                                                                                              |
| `link`           | `label`, any `http` or `https` `url`, `ingested_status` (`url_only`, or `authorized_content` when a Drive URL auto-ingests under `drive.readonly`) |
| `deadline`       | `value_text`, `due_at`, `deadline_state` (`upcoming`, `completed`, `rescheduled`, `canceled`, `past_due_unconfirmed`, `unconfirmed`)               |
| `relation`       | Typed link to an owned person, project or tag, `label`                                                                                             |

Every kind stores `value_text` up to 5000 characters, `label` up to 300 and `url` up to 2000.

`POST .../details` takes `kind`, `label`, `value_text`, `url`, `valid_from`, `valid_to`, `due_at`, `related_person_id`, `related_project_id`, `related_tag_id`, `source_meeting_id`, `evidence_segment_ids`, `evidence_start_ms`, `evidence_end_ms` and `evidence_quote`, and returns `201 { "detail", "entity" }`. A new single-valued detail supersedes the active one for the same entity, kind and project, and `replaces_prior` overrides that default. `deadline_state`, `sort_order` and `evidence_speaker` are also accepted.

`PATCH` accepts the same fields plus `deadline_state`, `status` (`active`, `superseded`, `archived`, `retracted`) and `sort_order`, sets `is_manual: true` and returns `{ "detail" }`. Editing a removed detail returns 404 unless the caller explicitly restores its `active` status.

`DELETE` returns `204`. Only a manual detail without meeting evidence is deleted. Any other detail stays as a `retracted` tombstone, so a later extraction does not bring it back. The workspace chat `retract_detail` operation does the same.

A detail PATCH returns the saved `revision_id` when it records an edit. DELETE with `?return_revision=true` also returns this ID for a recorded removal. To undo an edit to a retained fact, PATCH its detail with `{"undo_fact_revision":"<revision_id>"}`. Alim restores the stored fields and their manual or inferred status. A conflicting change returns 409.

### Relations, evidence and tag mentions

| Method   | Path                          | Auth | Purpose                                 |
| -------- | ----------------------------- | ---- | --------------------------------------- |
| `GET`    | `/knowledge/relations`        | User | Links between people, projects and tags |
| `GET`    | `/knowledge/evidence`         | User | Evidence and tag mentions               |
| `POST`   | `/meetings/{id}/tag-mentions` | User | Tag a time range of a meeting           |
| `DELETE` | `/tag-mentions/{mentionId}`   | User | Remove a tag mention                    |

- `relations` filters `entity_id`, `project_id`, `person_id`, `tag_id` and `status` (default `active`), and returns `{ "relations": [...] }`. A detail never relates an entity to itself
- `evidence` filters `entity_id`, `detail_id`, `meeting_id` and `tag_id`, and returns `{ "evidence": [...], "tag_mentions": [...] }`. Each evidence item carries `entity_id` and `entity_kind`, the person or project its detail belongs to, which the graph map uses to link a meeting to every record it is cited for
- `tag-mentions` takes `{ "tag_id", "start_ms", "end_ms", "segment_ids", "quote", "entity_id" }` and returns `201 { "tag_mention": {...} }`

### Tasks and deadlines

| Method   | Path                                       | Auth | Purpose                                                                             |
| -------- | ------------------------------------------ | ---- | ----------------------------------------------------------------------------------- |
| `GET`    | `/knowledge/tasks`                         | User | List tasks                                                                          |
| `POST`   | `/knowledge/tasks`                         | User | Create a task                                                                       |
| `PATCH`  | `/knowledge/tasks/{taskId}`                | User | Edit a task                                                                         |
| `DELETE` | `/knowledge/tasks/{taskId}`                | User | Remove a task                                                                       |
| `GET`    | `/knowledge/deadlines`                     | User | Milestones and task due dates in one list                                           |
| `GET`    | `/knowledge/housekeeping`                  | User | Up to 5 stale tasks and passed deadlines                                            |
| `POST`   | `/knowledge/housekeeping/{kind}/{id}/keep` | User | Hide an entry for 30 days                                                           |
| `GET`    | `/knowledge/housekeeping/resolve`          | User | Task/deadline resolution status and pending counts                                  |
| `POST`   | `/knowledge/housekeeping/resolve`          | User | Run focused task/deadline resolution (sync, single-item or `Prefer: respond-async`) |

Meeting, person and project pages edit the same `knowledge_tasks` rows.

- `GET /knowledge/tasks` accepts up to 100 comma-separated task `ids` to refresh saved task rows and filters `person_id` (assignee), `project_id`, `meeting_id`, `tag_id` and `state` (`open`, `in_progress`, `done`, `canceled`, `all`). Each task has `id`, `text`, `state`, `completed`, `due_at`, `assignee_person_id`, `assignee_name`, `assignee_email`, `is_owner`, `project_id`, `project_name`, `tag_ids`, `source_meeting_id`, `source_meeting_title`, the evidence fields and `is_manual`
- `POST` takes the same link and evidence fields, syncs to `meetings.action_items` and returns `201 { "task" }`
- `PATCH` accepts `text`, `state`, `completed` (`true` is `done`, `false` is `open`), `due_at`, `assignee_person_id`, `project_id` and `tag_ids`. It sets `is_manual: true` so later extraction keeps the edit, and returns `{ "task" }`
- Set `assignee_person_id` to a workspace person to update the task's name, email and `is_owner` from that person, or send an empty string to unassign it. Every meeting that cites the task shows the updated assignment.
- `DELETE` returns `204`. A source-backed task stays as a `retracted` tombstone. Only a manual task without a source meeting is deleted
- `deadlines` filters `person_id`, `project_id`, `meeting_id` and `state` (`upcoming`, `completed`, `rescheduled`, `canceled`, `past_due_unconfirmed`, `unconfirmed`, `all`). Entries have `source_kind` `milestone` or `task_due_date` and `date_status` `anchored` or `unconfirmed`
- `housekeeping` returns `{ "items": [{ "kind": "task" | "deadline", "id", "text", "at" }] }`, oldest first. It lists open tasks no meeting mentioned in 14 days (`last_mentioned_at`) and active deadlines more than a day past `due_at` that are not completed or canceled. Entries with a future `snoozed_until` are left out. Source-backed entries add `source_meeting_id`, `source_meeting_title`, `source_meeting_started_at` and the evidence fields
- `keep` takes `kind` `task` or `deadline`, sets `snoozed_until` 30 days ahead, records no revision and returns `204`
- `GET /knowledge/housekeeping/resolve` returns the caller's latest async resolution summary (`running`, `scope`, `checked`, `resolved`, `done`, `canceled`, `rescheduled`, `still_open`, `skipped_no_later_data`, `skipped_manual_lock`, `deferred_redaction`, `errors`, `api_calls`, `tool_calls`, `input_tokens`, `output_tokens`, `last_run_at`, `last_error`) plus live `pending_tasks_count` and `pending_deadlines_count`
- `POST /knowledge/housekeeping/resolve` resolves open tasks and active non-manual deadlines against strictly later ended canonical meetings (including grouped transcript segments and notes) and post-creation eligible redacted emails using the read-only `task_resolution` agent (`anthropic` `claude-haiku-5-5` by default). Send `{ "kind": "task" | "deadline", "id": "..." }` to resolve one owned entry (returns `404` for another owner, `409` if currently leased, `503` if the provider is unconfigured), or `{ "scope": "owner" | "all", "limit": 10, "force": false }` for a bounded batch (`limit` caps at `50` sync, `500` async). Adding `Prefer: respond-async` returns `202` and reuses an in-flight owner run. Items with zero later meetings and zero later eligible emails skip without a model call and stamp `resolution_checked_at`. Every `done`, `canceled` or `rescheduled` verdict requires confidence `>= 0.75`, passes financial-field checks and verifies a verbatim post-creation quote against the target meeting or `OPENSCRIBE_PII_URL`-redacted post-creation email messages before applying mutations, syncing `meetings.action_items`, attaching `meeting_segment` or `meeting_note` detail evidence for meeting-backed deadlines and recording an entity revision (state-locked tasks with unlocked due dates remain eligible for rescheduling). When later eligible emails exist and redaction is unavailable, the run fails closed and defers retry with a backoff lease instead of advancing `resolution_checked_at`. Operators can run the same sweep from the CLI with `openscribe resolve-tasks --owner <id>`

### Suggestions and extraction

| Method | Path                                            | Auth | Purpose                                                     |
| ------ | ----------------------------------------------- | ---- | ----------------------------------------------------------- |
| `GET`  | `/knowledge/suggestions`                        | User | Pending or resolved suggestions                             |
| `POST` | `/knowledge/entities/{id}/resolve-group`        | User | Apply the selected group review in one transaction          |
| `POST` | `/knowledge/suggestions/{suggestionId}/resolve` | User | `{ "action": "accept" \| "reject" }`                        |
| `POST` | `/meetings/{id}/extraction`                     | User | Queue extraction, returns `202`                             |
| `GET`  | `/meetings/{id}/extraction`                     | User | Latest job status and counts                                |
| `GET`  | `/knowledge/extraction/failures`                | User | Meetings whose last extraction failed                       |
| `POST` | `/knowledge/extraction/retry-failed`            | User | Requeue every failed meeting, returns `202 { "scheduled" }` |

`suggestions` filters `entity_id` (also lists existing-entity `person_merge_candidate` and `project_merge_candidate` suggestions on both entity pages), `meeting_id` and `status` (`pending` default, `accepted`, `rejected`, `all`). Each suggestion has `id`, `status`, `suggestion_type`, `reason` (`Maybe <name>?` for existing person or project merge proposals), `target_entity_id`, `target_entity_kind`, `target_entity_name`, `candidate_entity_id`, the current `candidate_entity_name`, `same_name`, the `proposed_*` fields, related IDs, the source meeting and the evidence fields. `same_name: true` groups matching effective names for review. People use full-name normalization, and projects compare alphanumeric names without punctuation or spaces.

`resolve` returns the suggestion, the entity summary and the current page in `entity_detail`. On accept it also returns `applied_detail`. The web sends `open_entity_id` to keep the current page or follow it to its surviving record. This response omits the training trajectory. The server still records the decision.

`POST /knowledge/entities/{id}/resolve-group` takes `action` and `entity_ids` for the other records the user selected. Person reviews accept pending proposals with different names. Person merges on both review routes accept the same optional `preferred_name` as a direct merge. A group choice must name one of the selected people or the open person. All selected decisions commit together. It returns `entity_detail` and `resolved_count`. A project group keeps the open project. A person group follows the saved proposal directions. If the selected proposals nominate different survivors besides the open person, the owner takes precedence, then a person with an email, then the oldest.

- `accept` applies the proposal as a manual edit. A role or location supersedes the old one, a deadline supersedes the same milestone, and other kinds add a detail. A `person_merge_candidate`, or a `project_merge_candidate` with non-empty `candidate_entity_id`, merges the target into the candidate, like `merge`
- `reject` stores a negative constraint so the same proposal does not return. Rejecting an existing-entity merge proposal adds each entity to the other's `do_not_merge_with`. Existing projects also store normalized slugs of the other's saved names and aliases on both records, without creating a separate project

Importing a transcript, ending a capture or receiving late committed speech queues the source durably. The same queue backfills existing imported meetings across workspaces. Workers group sources first and pick the newest available occurrence for extraction. Unchanged evidence reuses its saved outcome. An explicit extraction requests a fresh analysis. Up to four occurrences can be processed at once.

Extraction writes a short `overview` on the occurrence from committed speech, including for meetings without tasks or project updates. Later evidence can update it. If the replacement transcript has too little speech to summarize, a successful extraction clears the old overview. The existing `summary` and `manual_summary` fields retain the detailed brief and edits. `effective_summary` prefers the edit, then the detailed brief, then the overview. Without a configured extraction model, the overview can contain a short transcript quotation.

The archive worker fills missing overviews on previously processed meetings from the same workspace without changing their tasks, projects or detailed briefs. Eligible meetings report `queued` while they wait for the worker. It uses at most 48,000 characters of committed speech spread across the occurrence for a summary-only request. Retrying a failed archive overview repeats only the summary request, including through the bulk retry route. Failed or refused full extractions remain available for explicit retry.

- Supported facts with owner-scoped segment citations apply automatically with a `meeting` revision. Ambiguous identities, project merges, conflicts and anything touching a manual edit become `pending` suggestions
- Imported meetings resolve each speaker label to a person first, as in [Imported meetings](/docs/people-and-projects.md#imported-meetings). Their facts apply without review
- Extraction receives active owner project IDs, effective names and briefs as reference context. Saved names and absorbed aliases match directly. Workstream names and initial-plus-version abbreviations such as `Y27 Paper Alignment` and `YOLO27` are shortlisted without tagline dilution, and an unambiguous rule match becomes a `project_merge_candidate` that carries project details. Its target still binds person roles and tasks while pending. Accepting an extracted name saves it in the project’s manual aliases and leaves its other proposed facts available for individual review. Rejecting an extracted name creates its separate project and files pending facts for the same target and normalized name with their original meeting evidence
- A meeting title that unambiguously names or abbreviates an existing project adds its effective name to `projects` and supplies otherwise empty project bindings
- After extraction, active saved projects with matching names, aliases, alphanumeric names or version abbreviations receive `project_merge_candidate` proposals. The newer project is `target_entity_id`, the older is `candidate_entity_id`, and `proposed_entity_kind` is `project`. Updated projects also receive proposals for shortlisted decision-model matches of at least 0.5. Neither pass merges projects automatically, and both respect kept-apart IDs and slugs
- A project `brief` is a one-line tagline of up to 160 characters that replaces the project's `current_brief`. It adds no detail
- Each detail holds one fact, and its `value_text` is cut at 400 characters
- An extracted deadline without a parseable `due_at` is saved as a `note` that keeps its `due_text`
- A task from another meeting changes only when its subject words match, and then only its state and due date
- An answer that saves every item replaces the meeting's earlier automatic tasks and evidence. User-created, edited (`is_manual` or `manual_fields`) and removed rows stay. A failed, refused or empty job deletes nothing

The startup repair migration `202611170004_link_existing_project_meetings_and_merges` proposes rule-matched existing project pairs without provider calls. For ended, unmerged meetings, it adds an unambiguous title-matched project's effective name to `projects`, fills empty `knowledge_tasks.project` values except retracted or manually locked tasks, and refreshes affected `action_items`. Matching reads saved aliases and abbreviations. Multiple matches stay unresolved. The migration never merges projects.

`POST /meetings/{id}/extraction` returns `202 { "meeting_id", "job_id", "status": "queued", "content_hash" }`. `GET /meetings/{id}/extraction` returns:

```json
{
  "meeting_id": "mtg_1",
  "job_id": "job_mtg_1_1794233500",
  "status": "completed",
  "content_hash": "sha256:...",
  "entities_updated": ["ent_person_1"],
  "details_upserted": ["det_1"],
  "tasks_upserted": ["tsk_1"],
  "suggestions_created": ["sug_1"],
  "updated_at": "2026-11-09T18:05:02Z",
  "job": {
    "status": "completed",
    "reason": "",
    "refusal_category": "",
    "model": "anthropic/claude-sonnet-5-5",
    "stop_reason": "end_turn",
    "input_tokens": 12895,
    "output_tokens": 3327,
    "raw": { "projects": 2, "details": 5, "tasks": 4, "tag_mentions": 0, "speakers": 3 },
    "validated": { "projects": 2, "details": 5, "tasks": 4, "tag_mentions": 0, "speakers": 3 },
    "written": { "projects": 0, "details": 3, "tasks": 4, "tag_mentions": 0, "speakers": 3 },
    "speakers": [{ "label": "Ada Lovelace", "person_id": "ent_person_1", "method": "email" }],
    "finished_at": "2026-11-09T18:05:02Z"
  }
}
```

| Field                         | Values                                                                                                                                                                                                                                                                                  |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`                      | `idle`, `queued` or `running` for the occurrence, then its saved `job.status`                                                                                                                                                                                                           |
| `job.status`                  | `completed`, `empty`, `refused` (see `refusal_category`) or `failed` (see `reason`)                                                                                                                                                                                                     |
| `raw`, `validated`, `written` | Items returned, items that passed citation checks, items saved                                                                                                                                                                                                                          |
| `dropped`                     | Validated items not saved, by reason: `project_without_name`, `project_save_failed`, `detail_without_project`, `detail_without_person`, `detail_save_failed`, `suggestion_save_failed`, `detail_removed_by_user`, `task_removed_by_user`, `task_save_failed`, `tag_mention_save_failed` |
| `speakers[].method`           | `owner`, `email`, `name`, `new`, `group` or `generic` (the last two stay unassigned)                                                                                                                                                                                                    |

`job` comes from `meetings.knowledge_job`, survives restarts and is absent before the first run. New outcomes retain the input fingerprint in `content_hash` after a restart. The queued response has an empty hash until the worker reads the evidence. `failures` returns `{ "items": [{ "meeting_id", "title", "reason", "finished_at" }], "retrying": 0 }`, newest first. Refused jobs are left out, and meetings already retrying are only counted.

When the extraction provider reports an output limit, the worker can split the selected transcript into smaller sections at segment boundaries. Each request uses the configured output limit. The worker validates the sections separately and publishes an occurrence result only after all sections succeed. The job reports `capped_calls`, `completed_sections` and the total tokens used across all attempts.

The output-limit upgrade queues earlier failed imported occurrences with a `max_tokens` stop for one more extraction. The worker includes matching results written by a previous server during deployment. A whole-job processing deadline saves `failed` with `deadline_exceeded` and the usage observed so far. Explicit retry is available. Shutting down the server releases unfinished work for its replacement.

### Versions

| Method | Path                                                    | Auth | Purpose                                                                                                                                                                                                                                                                                                         |
| ------ | ------------------------------------------------------- | ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET`  | `/knowledge/entities/{id}/versions`                     | User | Revision summaries with a total count, latest ID, `limit` (default 25, maximum 200) and `offset`. Pass `version_id` for a historical page in `snapshot_view`, or add `detail_only=true` for the single full `version`. A revision missing its before snapshot includes the preceding revision ID when available |
| `POST` | `/knowledge/entities/{id}/versions/{versionId}/restore` | User | Restore a version                                                                                                                                                                                                                                                                                               |

Every change to an entity, its details or its tasks records a version with `trigger_kind` `manual`, `prompt`, `meeting`, `import` or `restore`. An entity older than version tracking gets baseline version 1 of its current state when first read. Viewing a version changes nothing.

Each revision summary has `id`, `entity_id`, `version_number`, `trigger_kind`, `trigger_id`, `trigger_label`, `summary`, `changes`, `restored_from_version_id` and `created`. Reading a full revision adds `before_snapshot` and `after_snapshot` with the entity, details and tasks. Each change is `{ "change_type": "added" | "updated" | "removed" | "superseded", "kind", "field", "detail_id", "task_id", "label", "before", "after" }`.

Restore applies `after_snapshot` in one transaction across the entity, details, tasks, the linked profile, inverse relations and `meetings.action_items`. It records a new `restore` version and returns `{ "restored_version_id", "revision", ...entity page payload }`.

## Workspace chat

| Method | Path              | Auth | Purpose                              |
| ------ | ----------------- | ---- | ------------------------------------ |
| `GET`  | `/workspace/chat` | User | Threads, or one thread with messages |
| `POST` | `/workspace/chat` | User | Ask, or make an explicit edit        |

`GET` combines `scope_kind`, `thread_id`, `meeting_id`, `entity_id` and `tag_id` filters and returns `{ "threads", "thread", "messages" }`, with `thread` null when nothing matches. `POST` also takes `title` and `operations`, a list of the allowed edit operations that runs as an explicit edit. It returns `{ "thread", "user_message", "assistant_message", "messages", "answer", "provider", "model_id", "verification_mode", "citations", "changes", "revision_ids" }`.

```json
{
  "thread_id": "",
  "message": "Update Ada's role on Project Analytical to Principal Architect",
  "context": {
    "entity_ids": ["ent_person_1", "ent_proj_1"],
    "meeting_ids": ["mtg_1"],
    "tag_ids": ["tag_1"],
    "selected": { "kind": "person", "id": "ent_person_1" },
    "view": "graph",
    "version_id": ""
  }
}
```

- A thread belongs to the workspace or to one meeting, entity or tag. A POST that pairs it with a different selection returns `409` before saving the question. A follow-up that omits context uses the thread’s own record. The client can send up to ten meeting hints. Transcript retrieval ranks committed segments across the selected person's or project's linked occurrences, the selected meeting or tag, or the owner's workspace. Each lookup returns up to 24 matching passages plus the adjacent utterances for the first three hits. A grouped recording retains its source ID and source-local clock. Merging people or projects brings their conversations to the surviving record. Older turns with a recorded selection can be recovered into their own conversation.
- A person or project opened from a meeting can send `context.origin_meeting_id` separately from the bounded list of meetings. Ask resolves “this meeting” using that occurrence and the selected record’s actual meeting links. A removal request returns choices for confirmation. Workspace and tag requests identify a recording by its title. A request to remove a single to-do or detail can identify it by name.
- Send `Accept: text/event-stream` to receive a read turn as `status` and `delta` events with a `text` field. The terminal `done` contains the saved JSON reply. A failure after the stream opens sends `error` with a `message`. Direct task views, edit turns and early HTTP errors use JSON.
- Inline `[1]` references index the reply’s `citations` starting at one. A segment has `meeting_id`, `meeting_title`, `source_meeting_id`, `segment_id`, `start_ms` and `end_ms`. Pass the segment ID when opening the meeting to select its transcript source.
- When ranked search is unavailable, Ask can read the transcripts of the supplied meetings if the agent has transcript access.
- New workspace answers record `context.reply_to` with the user message ID. Ask can use up to eight completed exchanges in the same thread and revision and one additional scoped transcript lookup before answering.
- Assistant messages may contain `parts`. A `meeting_removal` part carries `meetings` with `meeting_id`, `meeting_title`, `label` and `include_related`. A `task_list` carries up to 25 canonical task rows and a `read_only` flag. A `task_status_chart` carries a title and counts by state. The server resolves records and computes counts within the selected scope. Older messages can omit parts. Reading a reply performs no edits.
- `context` is the visible selection only. Foreign IDs return `400` or `404`
- The user message is saved before the model runs. A provider failure saves an assistant message with `status: "failed"`
- Questions, and anything asked while viewing a `version_id`, change nothing
- Explicit edits run in one transaction through these operations only: `update_entity`, `upsert_detail`, `update_detail`, `retract_detail`, `create_task`, `update_task`, `complete_task`, `retract_task`, `attach_tag`, `detach_tag`. One invalid operation rolls back the turn
- Edits record `prompt` versions (`trigger_id` is the assistant message, `trigger_label` the user message)

## Imports

| Method   | Path                            | Auth | Purpose                                                                                                                                                                                                                                                                 |
| -------- | ------------------------------- | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET`    | `/import/sources`               | User | `{ "items": [{ "source", "label", "transport", "connected", "imported_count", "account_email", "suggested_account_email", "daily_sync" }] }`                                                                                                                            |
| `GET`    | `/import/{source}/known`        | User | `{ "external_ids": [...] }` already imported                                                                                                                                                                                                                            |
| `POST`   | `/import/tactiq/quality`        | User | Assess supplied caption turns without creating a meeting                                                                                                                                                                                                                |
| `POST`   | `/import/{source}/meetings`     | User | Push one raw payload (`push` sources)                                                                                                                                                                                                                                   |
| `PUT`    | `/import/{source}/connection`   | User | Store an API key sent as `{ "credential", "account_email" }` (`api_key` sources), returns `{ "source", "connected": true, "account_email" }`                                                                                                                            |
| `PATCH`  | `/import/{source}/connection`   | User | Set `{ "account_email" }` without the key, returns `{ "source", "connected", "account_email", "updated_meetings" }`                                                                                                                                                     |
| `DELETE` | `/import/{source}/connection`   | User | Disconnect the source and end its daily run, returns `204`                                                                                                                                                                                                              |
| `POST`   | `/import/{source}/list`         | User | Page source meetings with `{ "cursor" }`                                                                                                                                                                                                                                |
| `POST`   | `/import/{source}/pull`         | User | Import one meeting by `{ "external_id" }`                                                                                                                                                                                                                               |
| `DELETE` | `/import/{source}/meetings`     | User | Remove all transcripts imported from this provider                                                                                                                                                                                                                      |
| `POST`   | `/import/tactiq/connect`        | User | Connect the verified Tactiq account from My Meetings with `owner_id` and `account_email`, including an empty account. Returns `204`                                                                                                                                     |
| `POST`   | `/import/tactiq/daily/claim`    | User | Claim a due browser import with `owner_id` and `account_email`. Explicit Sync now adds `force: true` and a per-run `run_id` (UUID). A reload reuses the ID with the same workspace and source account to get a fresh lease. The previous lease then expires immediately |
| `POST`   | `/import/tactiq/daily/renew`    | User | Extend the current 15-minute lease using the same owner, account and lease, returns `204`                                                                                                                                                                               |
| `POST`   | `/import/tactiq/daily/meetings` | User | Import one export using the same owner, account and lease plus `raw`                                                                                                                                                                                                    |
| `POST`   | `/import/tactiq/daily/finish`   | User | Finish the lease with `status: "complete"`, `"retry"` or `"stopped"`. Stopping releases the lease without marking a sync complete. Returns `204`                                                                                                                        |

**On-demand caption check.** POST up to 1 MiB of JSON to `/import/tactiq/quality` with `turns: [{speaker?, text}]` and optional `subject` and `language`. The transcript-quality agent runs `assess_transcript_quality@v1` (Gemini Decision 1 by default).

| Response | Meaning                                                                                                                        |
| -------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `200`    | Returns `outcome` (`usable_content`, `mixed`, `suspected_corruption` or `inconclusive`), `turns`, `windows` and `agent_trace`. |
| `400`    | Invalid body or empty list of turns.                                                                                           |
| `503`    | Assessment unavailable, including a missing decision provider or caption redactor.                                             |

Each connector registers in `importConnectors` (`apps/server/imports.go`) with transport `push` (the client posts `{ "raw": {...} }` per meeting) or `api_key` (the server pulls with a stored key). Manual import processes one meeting per request. Connected sources check daily for new meetings. The server walks tldv pages with the encrypted key, retries incomplete passes with backoff and resumes after a restart. Tactiq uses the Chrome companion in the signed-in source account.

`daily_sync` contains `status` (ready, syncing, retrying or paused), `last_synced_at` and `next_sync_at`. Empty timestamps mean no completed or scheduled check yet. Failures may include an `issue` code. A Tactiq claim returns `lease` and `external_ids` to skip. An empty lease means the run could not be claimed. The source account must match the verified account saved at connection or during a manual import. Older imports with one observed source account qualify automatically. A workspace switch returns `403`. A stale lease or changed source account on ingestion returns `409`.

- `connection` verifies the key with one live list call, then stores it encrypted. A rejected key returns `400`. No route returns the key
- `account_email` is optional, an empty string clears it and an invalid email returns `400`. Setting it fills the email on imported meetings from that source that have none, and `pull` uses it when the source payload has no account email
- `suggested_account_email` appears only on a connected `api_key` source without a saved `account_email` when at least two imported meetings share one dominant invitee address
- `list` returns `{ "items": [{ "external_id", "known" }], "next_cursor" }`. Repeat with `next_cursor` until it is `""`
- `DELETE .../meetings` returns `{ "deleted": 12 }`. Daily checks keep scanning connected sources and skip removed IDs. The next daily claim includes these IDs
- Unknown source is `404`, a bad body `400`, and a route that does not match the source transport `400`

`meetings`, `daily/meetings` and `pull` return one result. For `created` and `exists`, `meeting_id` identifies the saved source and `title` is its current stored title.

```json
{
  "external_id": "abc",
  "meeting_id": "rec_1",
  "title": "Roadmap sync",
  "status": "created",
  "segments": 383,
  "error": ""
}
```

| `status`            | Meaning                                                                                                                              |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `created`           | Meeting, notes and segments written                                                                                                  |
| `exists`            | Already imported, content unchanged                                                                                                  |
| `unusable_captions` | Tactiq skipped the source after two caption quality checks. No meeting was created. Changed captions are eligible for another check. |
| `no_transcript`     | Source has no transcript yet                                                                                                         |
| `unavailable`       | Source access does not allow reading this item, or a daily import encountered an item removed from the workspace                     |
| `failed`            | Nothing written, `error` says why                                                                                                    |

An imported meeting is stored `ended` with `capture_capability: "unverified"`, `language_mode: "auto"`, segments with `attribution: "unmapped"`, the source speaker in `speaker_name_snapshot`, `provider` set to the source key and no words. The import transaction stores source material. After commit, the backend groups sources by occurrence and processes Mind evidence in the background. The same worker handles existing imports across workspaces. Each meeting is one transaction. A rerun keeps the content and only fills in a missing calendar account and the source account email.

## Telemetry

| Method | Path         | Auth   | Purpose                                                |
| ------ | ------------ | ------ | ------------------------------------------------------ |
| `POST` | `/telemetry` | Public | Product events from the web app, extension and Mac app |

```json
{
  "client_id": "random_uuid_or_ga_cookie_pair",
  "client_app": "macos",
  "client_version": "0.3.0",
  "events": [
    {
      "name": "capture_start",
      "params": { "platform": "zoom_native", "session_id": 1763000000, "engagement_time_msec": 1 }
    }
  ]
}
```

- Returns `204`, also when events are dropped. `400` for malformed JSON, an unknown `client_app` (`web`, `extension`, `macos`), a bad `client_version` (`^\d+(\.\d+){0,3}$`, max 20 chars) or `client_id`, 0 or more than 25 events, or an event not listed for that app. `429` above 300 requests per minute per IP
- `apps/server/analytics-policy.json` is the only allowlist. Unlisted params, strings outside the listed values and out-of-range numbers are stripped. The server adds `client_app`, `client_version` and `hosting` (`hosted` or `self_hosted`)
- Dropped when `OPENSCRIBE_TELEMETRY=off` or the signed-in user has `telemetry_off`. The user ID is never forwarded
- A server with `GOOGLE_ANALYTICS_ID` and `GOOGLE_ANALYTICS_API_SECRET` (and the `_EXTENSION_` and `_MACOS_` pairs) posts to the GA4 Measurement Protocol EU endpoint. Any other server relays the cleaned body to `https://alim.akyonlabs.com/api/telemetry` with `X-OpenScribe-Forwarded: 1` and no IP, token or cookie, and a relayed request is never relayed again
- `OPENSCRIBE_TELEMETRY=debug` validates against Google's debug endpoint and records nothing. Failed forwards are logged without the URL and dropped

## MCP and OAuth

All discovery, `/oauth/*` and `/mcp` paths below are full paths from the origin, not under `/api`.

| Method                  | Path                                        | Auth      | Purpose                                                                          |
| ----------------------- | ------------------------------------------- | --------- | -------------------------------------------------------------------------------- |
| `GET`                   | `/.well-known/oauth-protected-resource`     | Public    | RFC 9728 metadata for `/mcp`                                                     |
| `GET`                   | `/.well-known/oauth-protected-resource/`    | Public    | Same metadata with a trailing slash                                              |
| `GET`                   | `/.well-known/oauth-protected-resource/mcp` | Public    | Path-scoped metadata for `/mcp`                                                  |
| `GET`                   | `/.well-known/oauth-authorization-server`   | Public    | RFC 8414 server metadata                                                         |
| `GET`                   | `/.well-known/openid-configuration`         | Public    | Same metadata for OIDC-style clients                                             |
| `GET`                   | `/.well-known/ai-catalog.json`              | Public    | SEP-2127 AI catalog discovery metadata                                           |
| `GET`                   | `/mcp/server-card`                          | Public    | SEP-2127 MCP server card metadata                                                |
| `POST`                  | `/oauth/register`                           | Public    | RFC 7591 dynamic client registration                                             |
| `GET`                   | `/oauth/authorize`                          | Public    | Browser consent SPA shell with anti-framing and no-store cache headers           |
| `GET`                   | `/oauth/request`                            | Public    | Validate PKCE `S256` authorization parameters and return consent metadata JSON   |
| `POST`                  | `/oauth/consent`                            | User      | Approve or deny a client                                                         |
| `POST`                  | `/oauth/token`                              | Public    | Exchange a code or refresh token                                                 |
| `POST`                  | `/oauth/revoke`                             | Public    | Revoke an access or refresh token                                                |
| `GET`                   | `/oauth/grants`                             | User      | List the user's client grants, including RFC 3339 `last_used_at` after first use |
| `DELETE`                | `/oauth/grants/{id}`                        | User      | Revoke a grant                                                                   |
| `POST`, `GET`, `DELETE` | `/mcp`                                      | MCP token | Stateless Streamable HTTP MCP with JSON responses on POST                        |

- All three protected-resource discovery paths, `/mcp/server-card`, and `/.well-known/ai-catalog.json` accept `OPTIONS` preflights.
- Public clients use `token_endpoint_auth_method: "none"`. Client ID Metadata Documents are accepted, and Claude, Claude Code, ChatGPT and `alim-cli` are predefined clients with exact redirect URIs
- The authorization server advertises `offline_access` alongside `handoff:read`, `meetings:read`, `meetings:ask` and `profile:read`. Refreshing with only `openid` or `offline_access` preserves the approved scopes. Codes live 5 minutes, access tokens 1 hour and refresh tokens 30 days.
- Refresh rotates both tokens. Retrying with the previous refresh token within 60 seconds returns the same rotated pair and its remaining access lifetime when the client, resource and user still match. A later replay of the previous token revokes the grant and returns `400 invalid_grant`.
- MCP supports versions `2026-07-28` and `2025-11-25`. `/mcp` returns `401` with `WWW-Authenticate: Bearer resource_metadata="..."` without a valid token. Authenticated GET and DELETE return `405` with `Allow: POST`. A foreign `Origin` receives `403`.
- Rate limits return `429` after 60 registrations per IP, 30 CIMD fetches per IP, 300 token requests per client and IP pair, 60 revocations per IP, or 600 MCP calls per grant in the current minute.

| Tool                      | Scope           | Purpose                                                                                                                                                                                                                                                                                              |
| ------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `handoff_read`            | `handoff:read`  | Read one owned `kind` and `id`, with optional `source_id` or `version_id`. Continue with the returned `next` arguments. Reading another page renews the two-minute snapshot window. If the snapshot expires or exceeds the cache limit and the record has changed, start over                        |
| `whoami`                  | `profile:read`  | Read the connected account's stable profile ID, name and email                                                                                                                                                                                                                                       |
| `meetings_list`           | `meetings:read` | List meetings by account, email, tag, linked person or project, series, text or verification mode. Default 25, maximum 100                                                                                                                                                                           |
| `meetings_search`         | `meetings:read` | Search titles, overviews, summaries, linked people and projects, and transcript passages across the archive. Filter by `person_ids` or `project_ids`. Hits carry the occurrence overview and linked entities. Transcript hits retain their source segment IDs and timestamps. Default 25, maximum 50 |
| `meeting_read`            | `meetings:read` | Read a meeting, linked Drive file metadata and bounded transcript page. Pass `segment_offset` and `segment_limit` (default and maximum 250)                                                                                                                                                          |
| `meeting_screenshot_read` | `meetings:read` | Read one screenshot with its metadata and OCR text                                                                                                                                                                                                                                                   |
| `meeting_ask`             | `meetings:ask`  | Cited answer about one meeting, optionally with screenshots and `include_series_history`, which reads every earlier meeting of the series like `past_meetings: "all"`                                                                                                                                |
| `context_metadata`        | `meetings:read` | Series metadata, people profiles and tags                                                                                                                                                                                                                                                            |

`meeting_read` omits word-level timestamps, limits each screenshot's OCR to 1,200 characters and returns `drive_files`, `total_segments`, `total_participants` (participant rows before the result was trimmed to fit), `segment_offset`, `has_more_segments` and `web_url`. For another page, add the number of returned segments to `segment_offset`. The viewer uses `total_participants` to distinguish a trimmed roster from an empty one. A complete list on a later page replaces the previous roster. List, search, meeting read and workspace metadata results fit within 100,000 JSON bytes.

The meeting viewer MCP App uses the content-hashed `ui://alim/meeting-{build}.html` resource exposed in `meeting_read` metadata as `_meta.ui.resourceUri`. An authenticated client can load its static shell. Meeting bundles and screenshot resources under `alim://meetings/{id}` require the owner's `meetings:read` scope. Client setup is in [MCP clients](/docs/mcp.md) and server setup is in [Self-hosting](/docs/self-hosting.md).

## Collections

All app collections use the list and view rule `@request.auth.id != '' && owner = @request.auth.id` unless noted. Create, update and delete rules are `nil`.

### Users, auth and accounts

| Collection                                                                   | Fields                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `users` (auth)                                                               | `name`, `avatar`, `admin` (server-managed), `meeting_languages`, `telemetry_off`, `time_format` (`auto`, `12h`, `24h`), hidden `classification_retry_at` and `classification_batch_size` for mailbox classification                                                                                                                                                                                                                          |
| `device_logins`                                                              | `user`, `code`, `secret` (hidden, SHA-256), `device_label`, `status` (`pending`, `approved`, `denied`, `claimed`), `expires`                                                                                                                                                                                                                                                                                                                 |
| `oauth_transactions`                                                         | `owner`, `nonce` (unique), `browser_binding_hash` (hidden), `code_verifier` (hidden), `calendar_id`, `return_to`, `expires`                                                                                                                                                                                                                                                                                                                  |
| `calendar_accounts`                                                          | `owner`, `google_sub`, `email`, `display_name`, `calendar_id` (default `primary`), `scopes`, `encrypted_token` (hidden, AES-256-GCM), `sync_status` (`connected`, `error`, `revoked`), `last_synced_at`. Unique `(owner, email, calendar_id)`                                                                                                                                                                                                |
| `calendar_hidden_events`                                                     | `owner`, `calendar_account`, `calendar_id`, `scope` (`event`, `series`), `target_id`, `event_id`, `recurring_event_id`, `title`, `start_at`, `account_email`, `created`. Unique `(owner, calendar_account, calendar_id, scope, target_id)`. Calendar account deletion cascades                                                                                                                                                               |
| `email_accounts`                                                             | `owner`, `provider` (`gmail`, `microsoft`), `google_sub`, `email`, `display_name`, `scopes`, hidden `provider_account_id`, hidden AES-256-GCM `encrypted_token`, hidden `search_checkpoint`, hidden `classification_catalog`, `sync_status`, `last_synced_at`. Unique `(owner, email)` for `gmail` and `(owner, provider_account_id)` for `microsoft`                                                                                        |
| `email_threads`                                                              | `owner`, `account`, `gmail_id`, `subject`, `last_message_at`, `person_ids`, `project_ids`, `auto_project_ids`, `manual_project_ids`, `excluded_project_ids`, `classification_status`, `project_fingerprint`, `classification_rollout_id`, hidden `classification_attempt_at`, hidden `classification_cursor`, hidden `classification_revision`, plaintext `messages`. Unique `(account, gmail_id)`. Account deletion cascades to its threads |
| `drive_accounts`                                                             | `owner`, `google_sub`, `email`, `display_name`, granted `scopes`, hidden AES-256-GCM `encrypted_token`, `status` (`connected`, `reconnect_required`). Unique `(owner, email)`                                                                                                                                                                                                                                                                |
| `drive_links`                                                                | `owner`, `account`, one of `meeting`, `email_thread` or `entity`, `file_id`, `title`, `mime_type`, `web_view_link`, `modified_time`, hidden `text` (at most 32,000 redacted characters), `text_status`, `fetched_at`. Deleting the account or the target deletes the link, and entity merges and meeting grouping move and deduplicate it                                                                                                    |
| `entity_files`                                                               | `owner`, `entity`, `file` (protected, max 50 MB, any type), `filename`, `mime_type`, hidden `text` (at most 32,000 redacted characters), `text_status`, `created`. Deleting the entity deletes its files, and entity merges move them                                                                                                                                                                                                        |
| `import_connections`                                                         | Owner, provider, bound source account, daily schedule and checkpoint. tl;dv stores the encrypted API credential. Unique `(owner, source)`. No client rules                                                                                                                                                                                                                                                                                   |
| `personal_ai_settings`                                                       | One row per owner. Hidden `settings` holds encrypted credentials, model choices, speech selection and revision. No client rules.                                                                                                                                                                                                                                                                                                             |
| `capture_speech_settings`                                                    | One row per registered capture that has requested a speech session. Hidden `selection` records the personal choice and credential tag or the workspace default. Deleting the capture deletes the row. No client rules.                                                                                                                                                                                                                       |
| `import_caption_reviews`                                                     | Owner-scoped quality result, source ID, input fingerprint, agent trace and last check time. No caption text or client rules.                                                                                                                                                                                                                                                                                                                 |
| `import_exclusions`                                                          | Owner, source and external meeting ID removed from automatic imports. No client rules                                                                                                                                                                                                                                                                                                                                                        |
| `mcp_oauth_clients`, `mcp_oauth_codes`, `mcp_oauth_tokens`, `mcp_oauth_jtis` | OAuth clients, single-use code hashes, token hashes, scopes, expiry, a hidden rotation secret, grant rotation and last-use timestamps, and single-use redeemed JWT-bearer JTI hashes. No client rules                                                                                                                                                                                                                                        |
| `transcription_probes`                                                       | Dedicated provider-check auth identity, with no public record rules or interactive sign-in                                                                                                                                                                                                                                                                                                                                                   |
| `ai_settings`                                                                | `workload` (unique, includes `transcription` and `decisions`), `provider` (includes `typesafe`), `model_id`, `base_url`, `updated_by`. Admin writes only                                                                                                                                                                                                                                                                                     |
| `ai_rollouts`                                                                | `owner`, `agent_id`, `agent_version`, `workload`, `call_kind` (`generate`, `decide`, `tool_loop`), `provider`, `model_id`, `fallback_used`, `status` (`ok`, `error`), `error_code`, `latency_ms`, `prompt_hash`, `group_key`, `source_kind`, `source_id`, `system_prompt`, scrubbed `input_payload`, `raw_output`, `parsed_output`, `tool_trace`, `usage`                                                                                    |

### Meetings

Capture clients create a session with `session_id`, `started_at` (ISO 8601), `state`, increasing integer `revision`, and `meeting` containing the normal meeting creation fields. An optional owned `meeting_id` registers an existing local recording without creating another meeting. An optional `planned_meeting_id` links a new capture to an owned scheduled meeting. If the plan is gone, normal occurrence matching resumes. A nonempty owned calendar account, calendar ID and calendar event occurrence ID resolve atomically to the same meeting. A recurring series ID or meeting title alone never joins occurrences. The response is `{meeting, session_id, timeline_offset_ms}`. The `capture_sessions` collection stores that immutable start, optional end, state, revision, last presence time and whether the original transcript identities belong to a legacy recording. Meeting state also stores the latest `capture_active_until` deadline.

Capture creation uses the original `local_recording_meta.time_origin_epoch_ms` when present, preserving milliseconds even if an older client formatted `started_at` in whole seconds. A heartbeat may include `started_at_epoch_ms` to refine an older whole-second registration within that same second. This corrects the capture binding without rewriting stored content.

State updates accept `joined`, `recording`, `ended` (requires `ended_at`) or `interrupted` (unknown end time). Clients send heartbeats at least every 30 seconds. Lower or repeated revisions do not overwrite newer state, and ended or interrupted sessions cannot reopen. A fresh recording session takes precedence over a fresh joined session. Without fresh presence for 90 seconds, the meeting serializes as `failed`, retaining an unknown end time. A later session can resume the occurrence.

Transcript and note JSON accept `capture_session_id`. Attachment multipart accepts the same field. The server translates session-relative segment, word, note and file timestamps to the existing canonical meeting clock. New captures namespace transient participant IDs and segment IDs by session. The first session registered against a legacy meeting retains its existing transcript identities for replay. Notes and attachments also accept `capture_item_id` to return the existing saved item on retry.

An operator can repair confirmed legacy duplicates with the `repair-capture-meetings` command. The command runs a named application migration scoped to one owner and a verified calendar occurrence. It preserves transcript, note, file, task and evidence record IDs, translates their timestamps and retains old meeting IDs as aliases. Old meeting URLs, file links and MCP resources resolve to the combined meeting, while the meetings list hides alias rows. Its first page includes an owner-scoped `meeting_aliases` map from each old ID to its canonical ID, independent of list filters, so clients can update local bindings without opening every old meeting. Later pages omit that map. Conflicting manual summaries remain as notes, and the original meeting rows retain their source metadata. An alias cannot point across owners. The request and data-directory options are described in [Self-hosting](/docs/self-hosting.md).

When the verified occurrence recurs, the combined meeting joins that calendar series. Existing series rows and series notes are preserved.

| Collection             | Fields                                                                                                                                                                                                                                                                                                                                                              |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `meeting_series`       | `owner`, `calendar_account`, `calendar_id`, `recurring_event_id` (all three empty for an inferred series), `origin` (`calendar`, `inferred`, `manual`), `title`, `summary`, `manual_summary`, `projects`, `manual_projects`, `deadlines`, `manual_deadlines`. Unique `(owner, calendar_account, calendar_id, recurring_event_id)` where `recurring_event_id` is set |
| `tags`                 | `owner`, `name`, `description`, `color`. Unique `(owner, name)`                                                                                                                                                                                                                                                                                                     |
| `people_profiles`      | `owner`, `email` (optional, never invented), `platform_ids`, `display_name`, `manual_name`, `inferred_metadata`, `manual_metadata`, `merged_into`. Unique `(owner, email)` for unmerged rows with an email                                                                                                                                                          |
| `meeting_participants` | `owner`, `meeting` (cascade), `person`, `platform`, `participant_device_id`, `transport_source_ids`, `display_name`, `email` (verified only), `attribution_mode`, `is_self`. Unique `(meeting, platform, participant_device_id)`                                                                                                                                    |
| `meeting_notes`        | `owner`, `meeting`, `series`, `kind` (`note`, `link`), `content`, `url`, `link_type`, `provenance`, `ingested_status` (`url_only`, `authorized_content`), `timestamp_ms`                                                                                                                                                                                            |
| `meeting_attachments`  | `owner`, `meeting` (cascade), `file` (protected, max 50 MB, any type), `kind` (`screenshot`, `file`, `audio_chunk`, `replay_bundle`), `captured_at_ms`, `window_title`, `source_app`, `extracted_text`, `extracted_links`                                                                                                                                           |

`platform_ids` holds `{ "platform", "participant_id", "meeting_id", "stable_id" }`. A per-meeting `participant_device_id` never matches across meetings. `inferred_metadata` and `manual_metadata` hold `country`, `company`, `job_title`, `responsibilities`, `linkedin_url`, `scholar_url`, `links` and `sources`, and the manual value wins when it is set. `link_type` is `webpage`, `github`, `slack`, `google_drive` or `other`. `provenance` is `manual`, `calendar_description`, `meeting_chat`, `screenshot_ocr`, `import` or `import_ai` (the last two written only by imports).

### `meetings`

| Field                                                                                        | Type                   | Notes                                                                                                                |
| -------------------------------------------------------------------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `owner`, `calendar_account`, `series`                                                        | relation               | Account is optional                                                                                                  |
| `series_kept_apart`                                                                          | json                   | Series the user unlinked the meeting from                                                                            |
| `calendar_id`, `calendar_event_id`, `recurring_event_id`                                     | text                   | From Google Calendar                                                                                                 |
| `title`                                                                                      | text                   | Required                                                                                                             |
| `platform`                                                                                   | select                 | `google_meet`, `zoom_native`, `zoom_browser`, `teams_native`, `teams_browser`, `slack_huddle`, `local_mic`, `other`  |
| `state`                                                                                      | select                 | `preview`, `waiting`, `joined`, `recording`, `ended`, `failed`                                                       |
| `capture_capability`                                                                         | select                 | `per_participant_pcm`, `single_stream_verified`, `mixed_audio`, `metadata_only`, `unverified` (default)              |
| `meeting_url`                                                                                | text                   |                                                                                                                      |
| `account_email`                                                                              | text                   | Server-set, see below                                                                                                |
| `language_mode`, `language_code`                                                             | select, text           | `auto` clears the code                                                                                               |
| `meeting_languages`                                                                          | json                   | Account preference snapshot at creation                                                                              |
| `detected_languages`                                                                         | json                   | `[{ "language_code", "detected_at_ms", "source" }]`                                                                  |
| `started_at`, `ended_at`                                                                     | date                   |                                                                                                                      |
| `tags`, `suggested_tags`                                                                     | relation, json         | Suggestions are `{ "tag_id", "name", "reason" }`                                                                     |
| `overview`, `summary`, `manual_summary`                                                      | text                   | Automatic one-sentence overview, detailed brief and edited brief                                                     |
| `action_items`                                                                               | json                   | `{ "id", "task_id", "text", "assignee_email", "is_owner", "evidence_segment_ids", "evidence_quote", "completed" }`   |
| `followup_email_draft`                                                                       | json                   | `{ "subject", "body", "generated_at" }`, never sent                                                                  |
| `projects`, `manual_projects`, `deadlines`, `manual_deadlines`                               | json                   |                                                                                                                      |
| `linked_project_ids`, `manual_project_ids`, `excluded_project_ids`, `topic_match_rollout_id` | json, json, json, text | Auto-matched, manually attached and excluded topic entity IDs plus the latest `topic_matching` rollout ID            |
| `local_recording_meta`                                                                       | json                   | `{ "local_bundle_path", "sample_rate", "channels", "recoverable", "time_origin_epoch_ms" }`                          |
| `verification_mode`                                                                          | select                 | `real`, `controlled_test`, `fixture`                                                                                 |
| `import_source`, `import_external_id`                                                        | text                   | Unique `(owner, import_source, import_external_id)` when set                                                         |
| `import_meta`                                                                                | json                   | `{ "url", "reported_platform", "reported_language", "attendees", "invitees", "imported_at" }` as the source reported |
| `knowledge_job`                                                                              | json                   | Last extraction outcome, IDs and counts only                                                                         |

`account_email` is the lowercased address the meeting happened under: the calendar account's email, else the `authuser` email of a Meet URL, else the import source account, else empty. It is recomputed when the meeting is created, when its account changes and when a re-import fills it in. Every distinct value counts as one of the owner's emails.

### `transcript_segments`

| Field                                                        | Type     | Notes                                                                                            |
| ------------------------------------------------------------ | -------- | ------------------------------------------------------------------------------------------------ |
| `owner`, `meeting`, `participant`                            | relation | Meeting cascades. Participant is empty for unmapped or mixed audio                               |
| `participant_device_id`                                      | text     | Empty when unmapped or mixed                                                                     |
| `speaker_name_snapshot`                                      | text     | Name at that moment, never a key                                                                 |
| `attribution`                                                | select   | `one_mapped_source`, `mixed_sources`, `unmapped`, `local_mic`                                    |
| `source_ids`, `unmapped_contributors`                        | json     | Contributing and unmapped RTP source IDs                                                         |
| `stream_generation`                                          | int      | Increments on rejoin or renegotiation                                                            |
| `status`                                                     | select   | `partial`, `committed`                                                                           |
| `text`, `language_code`                                      | text     | Language is provider-reported                                                                    |
| `start_ms`, `end_ms`                                         | int      | Meeting timeline                                                                                 |
| `receive_epoch_ms`, `decoded_sample_offset`, `rtp_timestamp` | int      | Timing for replay alignment                                                                      |
| `words`                                                      | json     | `[{ "text", "start_ms", "end_ms", "provider_start_s", "provider_end_s", "type", "speaker_id" }]` |
| `provider`, `external_segment_id`                            | text     | Segment ID is the idempotency key                                                                |

### Knowledge

| Collection                  | Fields                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `knowledge_entities`        | `owner`, `kind` (`person`, `project`), `canonical_name`, `manual_name`, `normalized_key`, `email`, `person_profile`, `series`, `tags`, `status` (`active`, `archived`, `merged`, `provisional`), `merged_into`, `do_not_merge_with`, `current_brief`, `manual_brief`, `current_attributes`, `manual_attributes` (JSON objects including `aliases`), `pinned`, `last_observed_at`                                                                                                                                                        |
| `knowledge_details`         | `owner`, `entity`, `kind`, `label`, `value_text`, `url`, `ingested_status`, `valid_from`, `valid_to`, `due_at`, `due_text`, `deadline_state`, `related_person`, `related_project`, `related_tag`, `cardinality` (`single_valued`, `multi_valued`), `status` (`active`, `superseded`, `expired`, `provisional`, `retracted`, `archived`), `is_manual`, `sort_order`, `first_observed_at`, `last_observed_at`, `superseded_at`, `superseded_by`, `snoozed_until`, hidden `resolution_checked_at`, hidden `resolution_lease`, `dedupe_key` |
| `knowledge_detail_evidence` | `owner`, `detail`, `source_type` (`manual`, `meeting_segment`, `meeting_note`, `meeting_attachment`, `profile_migration`, `series_migration`), `source_meeting`, `source_series`, `source_note`, `source_attachment`, `observed_at`, `evidence_segment_ids`, `evidence_start_ms`, `evidence_end_ms`, `evidence_speaker`, `evidence_quote`, `source_url`, `extraction_run_id`                                                                                                                                                            |
| `knowledge_tasks`           | `owner`, `text`, `state` (`open`, `in_progress`, `done`, `canceled`, `retracted`), `due_at`, `due_text`, `due_status` (`anchored`, `unconfirmed`, `none`), `assignee_person`, `assignee_name`, `assignee_email`, `is_owner`, `project`, `tags`, `source_meeting`, `action_item_id`, evidence fields, `is_manual`, `manual_fields`, `last_mentioned_at`, `snoozed_until`, hidden `resolution_checked_at`, hidden `resolution_lease`, `dedupe_key`                                                                                        |
| `knowledge_tag_mentions`    | `owner`, `tag`, `meeting`, `entity`, `start_ms`, `end_ms`, `segment_ids`, `quote`, `is_manual`                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `knowledge_suggestions`     | `owner`, `status` (`pending`, `accepted`, `rejected`), `suggestion_type` (`detail_conflict`, `ambiguous_identity`, `new_project_candidate`, `project_merge_candidate`, `detail_candidate`, `person_merge_candidate`), `reason`, `target_entity`, `candidate_entity`, `proposed_entity_kind`, `proposed_entity_name`, `proposed_kind`, `proposed_label`, `proposed_value_text`, `proposed_url`, `proposed_due_at`, related IDs, `source_meeting`, evidence fields, `dedupe_key`                                                          |
| `knowledge_entity_versions` | `owner`, `entity`, `version_number`, `trigger_kind`, `trigger_id`, `trigger_label`, `summary`, `changes`, `before_snapshot`, `after_snapshot`, `restored_from_version_id`                                                                                                                                                                                                                                                                                                                                                               |
| `training_trajectories`     | `owner`, `agent_id`, `agent_version`, `signal_type` (`explicit`, `implicit`), `target_kind`, `target_id`, `entity_id`, `source_meeting`, `source_kind`, `source_id`, `action` (`ok`, `no`, `revise`, `attach`, `detach`, `dismiss`), `revise_chip`, `reward`, `rollout_id`, `prompt_hash`, `group_key`, `input_context`, `rejected_output`, `chosen_output`, `agent_trace`                                                                                                                                                              |

Evidence fields are `evidence_segment_ids`, `evidence_start_ms`, `evidence_end_ms` and `evidence_quote`, plus `evidence_speaker` where listed. Owner, entity, detail and source meeting relations cascade on delete.

### Workspace chat

| Collection                | Fields                                                                                                                                                                                                                                                                                 |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `workspace_chat_threads`  | `owner`, `title`, `scope_kind` (`workspace`, `meeting`, `entity`, `tag`), `meeting`, `entity`, `context_json`, `last_message_at`                                                                                                                                                       |
| `workspace_chat_messages` | `owner`, `thread`, `meeting`, `role` (`user`, `assistant`), `status` (`completed`, `failed`, `pending`), `content` (max 100000), `error_message` (sanitized), `workload`, `provider`, `model_id`, `verification_mode`, `context_json`, `citations`, `parts`, `changes`, `revision_ids` |

Citations are `{ "kind", "segment_id", "meeting_id", "meeting_title", "start_ms", "end_ms", "speaker", "quote", "entity_id", "detail_id", "task_id", "drive_file_id", "entity_file_id", "url" }`. Workspace chat resolves `[drive:ID]` to a linked Drive source and `[entity_file:ID]` to an uploaded source with its `entity_id` and filename as `label`. The citation marker is removed from the answer text.

## Mind pipelines, ontologies, compaction and feedback

All routes below are relative to `/api` and require a user session. Each reads or changes only the signed-in owner's records.

| Method | Path                               | Payload or result                                                                                                                                         |
| ------ | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET`  | `/knowledge/ontologies`            | `{active_ontology_id, active_ontology, ontologies}`                                                                                                       |
| `PUT`  | `/knowledge/ontologies/active`     | `{active_ontology_id, overrides?: {node_kinds?, sections?}}`, returns the ontology list and active contract                                               |
| `POST` | `/knowledge/entities/{id}/compact` | Full entity detail payload plus `compacted_details` and `compacted_tasks`                                                                                 |
| `POST` | `/knowledge/feedback`              | `{target_kind, target_id, action, revise_chip?, patch?}`, returns `{trajectory, entity}` where `entity` is the full updated entity detail payload or null |
| `GET`  | `/knowledge/trajectories`          | `{trajectories, summary: {total, ok, no, revise, by_action, by_agent, ready_for_local_training}}`                                                         |
| `GET`  | `/knowledge/trajectories/export`   | Owner-scoped GRPO/DPO training trajectory export joined with `ai_rollouts` (`?format=grpo_jsonl` NDJSON default or `json`, optional `?agent_id=`)         |

`workspace_default` is the default ontology. Opt-in `medical_visits` maps `clinician` to storage kind `person` and `condition`, `organ_system` and `medication` to `project`. Ontology contracts contain `id`, `version`, `name`, `opt_in`, `node_kinds: [{kind, label, storage_kind}]` and `sections: [{id, label, detail_kinds}]`. Overrides replace the selected contract's node kinds or sections for that owner. The active persona does not change recording support.

Entity creation and patch accept `ontology_kind`. It must match a node kind in the active ontology and the entity's storage kind. A patch with an empty string clears the manual label. Serialization prefers `manual_attributes.ontology_kind` to `current_attributes.ontology_kind`.

Feedback targets are `detail`, `task` or `suggestion`, and actions are `ok`, `no` or `revise`. Rewards are 1, -1 and 0.5 respectively. OK confirms without changing text. No retracts a sourced item or removes an unsourced manual item. Suggestions use the existing accept/reject behavior and negative merge constraints. A resolved suggestion cannot be resolved again. The legacy `/knowledge/suggestions/{suggestionId}/resolve` route also writes one trajectory.

| Target     | Revise chip             | Patch                                                                                                                               |
| ---------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| Detail     | `outdated_superseded`   | Optional `superseded_by_id` referencing a different active detail on the same entity                                                |
| Detail     | `duplicate_of`          | Required `superseded_by_id`, combines evidence and supersedes the duplicate                                                         |
| Detail     | `change_kind`           | `kind` and optional `label`                                                                                                         |
| Detail     | `move_entity`           | `target_entity_id`                                                                                                                  |
| Detail     | `edit_inline`           | `value_text` and/or `label`                                                                                                         |
| Task       | `already_done`          | None                                                                                                                                |
| Task       | `not_a_todo`            | None, saves a cited note on the project or assignee entity and retracts the task                                                    |
| Task       | `change_project`        | `project_id`, empty clears it                                                                                                       |
| Task       | `change_assignee`       | `assignee_person_id`, empty clears it                                                                                               |
| Task       | `edit_inline`           | `text`                                                                                                                              |
| Suggestion | Any structured revision | Overrides using `target_entity_id`, `candidate_entity_id`, `kind`, `label`, `value_text`, `text` or `name`, then accepts the result |

Trajectories contain `owner`, `agent_id`, `agent_version`, `target_kind`, `target_id`, `entity_id`, `source_meeting`, `action`, `revise_chip`, `reward`, `input_context`, `rejected_output`, `chosen_output`, `agent_trace` and timestamps. Revise saves both outputs in the same transaction as the mutation and entity revision. `ready_for_local_training` means at least 100 records and does not start training.

Agent contracts returned by `/admin/agents` include `pipeline: [{id, tool, mode, when?, config?}]`. `PUT /admin/agents/{id}` accepts `pipeline` as well as Markdown. Tool references use `name@v1`, modes are `mandatory` or `conditional`, and conditions are `always`, `unresolved`, `ambiguous_candidates`, `candidates_found`, `large_catalog` or `post_extraction`. Pipeline step config validates `top_k` (`1..50`) and `min_catalog_size` (`1..5000`). Pipeline Markdown uses one canonical JSON line per step with sorted config keys for readable version diffs. Only admins can edit contracts.

Calendar, email and scheduling use the same owner-scoped functions as their HTTP routes. Their deterministic versioned tools are:

| Tools (all `@v1`)                                                           | Effect                                                                                                                     |
| --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `meeting_schedule`                                                          | Create a local planned meeting with timezone and participant emails                                                        |
| `meeting_schedule_with_invites`                                             | Create an event and send Google Calendar invitations using previously granted access                                       |
| `zoom_accounts_list`, `zoom_account_disconnect`, `zoom_meeting_link_create` | List or disconnect owned Zoom accounts and create a scheduled participant link                                             |
| `meeting_link_create`                                                       | Create a Google Meet space with an already granted connection                                                              |
| `calendar_events_list`, `calendar_events_sync`                              | Read saved events, or sync Google and update local context                                                                 |
| `calendar_occurrence_match@v1`                                              | Return the kept input indices and grouped hidden state for provider copies and linked meetings                             |
| `calendar_hidden_list`, `calendar_event_hide`, `calendar_event_unhide`      | List, hide and restore occurrences or series                                                                               |
| `time_format_read`, `time_format_update`                                    | Read and save `auto`, `12h` or `24h`                                                                                       |
| `meeting_join_mode_read`, `meeting_join_mode_update`                        | Read and save `browser` or `desktop` for Zoom and Teams                                                                    |
| `email_accounts_list`, `email_threads_list`                                 | Read owned accounts and currently matching threads                                                                         |
| `email_account_sync`, `email_account_disconnect`                            | Sync or remove one owned email connection                                                                                  |
| `drive_files_list`, `drive_file_read`                                       | List the Drive files linked to one target, or read up to 20,000 characters of one file's saved text without calling Google |

List and read tools are read-only. Sync, hide, unhide, preference updates, scheduling, call creation and disconnect require an explicit agent allowlist entry and read-write access. Tools cannot grant OAuth consent. Missing Meet authorization requires the browser connection flow. Existing agents receive no new permissions automatically.

The tool catalog includes `version` and `kind` (`deterministic` or `ai_model`). The matching tools are `entity_rule_match@v1`, `shortlist_candidates@v1`, `hybrid_rrf_shortlist@v1`, `decide_predicates@v1`, `source_link_entity@v1` and `source_unlink_entity@v1`. The compaction and rollout tools are `detail_supersede@v1`, `task_consolidate@v1`, `entity_merge@v1`, `rollouts_stats@v1` and `trajectories_export@v1`. Tool execution retains the existing agent allowlist, access mode and owner boundaries. Decision predicates are `person_same_as`, `project_same_as`, `detail_supersedes`, `task_duplicates` and `source_belongs_to_topic`.

`POST /meetings/{id}/links` and `POST /email/threads/{id}/links` accept `{ "entity_id" }` and return `{ source_kind, source_id, entity_id, linked, manual_project_ids, excluded_project_ids, linked_projects }` (email threads also return `project_ids`). `DELETE .../links/{entityId}` returns the same shape with `linked: false`. `GET .../link-suggestions` returns `{ source_kind, source_id, candidates: [{ entity_id, name, brief, rrf_score, lexical_score, cooccurrence_hits, lexical_rank, cooccurrence_rank, recency_rank, last_observed_at }] }`, excluding linked and excluded topics.

The local `contact_resolution` contract executes `contact_resolve@v1` on observed calendar addresses or saved profile IDs. Agents with permission can also use `contact_email_suggest@v1` for owner-scoped autocomplete. The existing `person_create` and `person_update` tools accept ordered `emails`. An update can include `previous_emails` to preserve concurrent address edits. Agent detail returns up to eight recent `recent_activity` records from the signed-in workspace’s revisions and suggestions with their recorded tool steps and versions.

Calendar list and sync run the active `calendar_occurrence_matching` agent. Its mandatory read-only step calls `calendar_occurrence_match@v1` with occurrence identity and copy preferences. The response includes `agent_trace` with the saved agent version and executed step. The matcher runs locally on metadata and makes no model calls.

The local `meeting_source_matching` agent uses `meeting_source_match@v1` to evaluate occurrence, time and dialogue signals. Read its version and decision in the `agent_trace` on grouped transcript sources and source suggestions.

The read-only `task_resolution` agent runs in the background after meetings end or email classification completes, and on demand via `/knowledge/housekeeping/resolve`. Its contract allows only focused evidence tools: `list_later_timeline@v1`, `search_evidence_passages@v1`, `read_transcript_window@v1` and `read_email_thread@v1`. Every email tool output is masked through `OPENSCRIBE_PII_URL` before the model sees it, and financial guardrail checks (`checkForbiddenFinancialFields`) reject restricted quotes or explanations.

Suggestions, details, tasks and entity versions serialize `agent_trace: {agent_id, agent_version, steps: [{step_id, tool, outcome, rule?, confidence?, reason?}]}`. Compaction revisions use `trigger_kind: "compaction"`. Compaction retains superseded details and retracted source tasks, combines citations and follows the active `knowledge_compaction` pipeline. Task records store `consolidated_into` for their surviving canonical task.
