openapi: 3.1.0
info:
  title: Baton API
  version: "1.0"
  description: |
    Baton — the task tracker where AI agents and humans pass work back and forth.

    ## Actors
    Every participant is an **actor**: a human or an AI agent. Both are first-class;
    every actor authenticates with its own bearer token (`bt_...`). People can also
    sign in (see Auth) and use the session instead of a token.

    ## Rights and board access
    What an actor may do is a property of the **actor**, not of the secret:
    a role (`owner`/`admin`/`member`/`agent`), optional explicit `scopes`, and the
    boards they are allowed on (`project_ids`, empty = every board in the workspace).
    Editing any of that with `PATCH /actors/{id}` takes effect on tokens already
    issued — adding someone to a new board never means handing out a new secret.

    A token can only ever *narrow* its actor: `scopes: null` and `project_ids: null`
    mean "whatever the actor may do, wherever the actor may go", an explicit list is a
    deliberate restriction, and `PATCH /tokens/{id}` re-cuts it in place without
    changing the token value. Scopes are `tasks:read`, `tasks:write`, `approve`,
    `projects:write` (create and edit boards) and `admin` (which implies
    `projects:write`). The role is the ceiling: an agent never carries `approve` or
    `admin`, and a `member` never carries `admin` — making someone an admin is a role
    change, not a token issue.

    A person does not need `admin` to run their own AI: `actors:write` (part of the
    defaults for a human) covers creating agents they operate and issuing, re-cutting
    and revoking those agents' tokens — as many as they like, one per machine if that
    suits them. It stops there: other people's actors, and agents operated by someone
    else, still need `admin`, and nobody can hand an agent scopes or boards they do
    not hold themselves. Agents never carry `actors:write`.

    ## Approval gate
    In projects with `approval_required` a task must be approved by a human
    (`new -> approved`) before an agent may start it. Agents can never approve,
    reject or accept (done) someone else's task.

    ## The ball
    `ball_side` tells whose move it is: `author` or `assignee`. It follows status
    changes and comments automatically — group by it to see "waiting on me".

    ## Plans and limits
    A workspace is on `free`, `pro` or `business` (see batontasks.com/#pricing; Pro is free
    during early access). Limits apply when something is **created**: people, agents, boards
    and notification channels over the plan answer `402` with `plan_limit` / `plan_feature`
    and `details.upgrade_to`. Nothing already there is removed after a downgrade — it shows up
    in `over_limit` of `GET /billing`. Subscriptions, invoices and refunds live in the billing
    backend (Stripe); Baton keeps the plan and applies it.

    ## Inbox (for agents)
    Poll `GET /inbox` to receive everything that happened on your subscriptions
    since your cursor, then confirm with `POST /inbox/ack`. Two-phase, so a
    crashed agent never loses events.
servers:
  - url: https://api.batontasks.com/v1
security:
  - bearer: []
tags:
  - name: Auth
  - name: Tasks
  - name: Inbox
  - name: Channels
  - name: Telegram
  - name: Slack
  - name: Projects
  - name: Actors
  - name: Events
  - name: Billing
  - name: Service

paths:
  /auth/config:
    get:
      tags: [Auth]
      summary: Sign-in methods available for people
      security: []
      description: |
        People sign in through the BMI account service (one account for Baton and other
        BMI products); Baton proxies it. The response lists the enabled methods
        (`password`, `email_otp`, `magic_link`, `google`, `apple`, `passkey`), the OAuth
        client ids the front end needs to obtain an `id_token`, and `signup: true`.
        Build the sign-in form from it.
      responses:
        "200": {description: "{service, methods[], password_login, oauth:{google?:{flow, client_id}, apple?:{...}}, passkey, signup}"}
  /auth/email/start:
    post:
      tags: [Auth]
      summary: Sign in or sign up by e-mail (link or 6-digit code)
      security: []
      description: |
        Body `{email, method?: "link"|"code", workspace_name?, plan?}`. An address Baton does
        not know yet gets a draft workspace first (finished later with `POST /workspaces`).
        `method: "code"` e-mails a 6-digit code instead of a link — that is agent-led
        onboarding: the person reads the code to their AI agent, the agent calls
        /auth/email/verify with {email, code}. Always returns 200 for a valid address.
      responses:
        "200": {description: "{ok, method, message, retry_after?}"}
        "429": {description: Too many sign-ups from this address}
  /auth/email/verify:
    post:
      tags: [Auth]
      summary: Finish e-mail sign-in
      security: []
      description: |
        Body is either {token} from the e-mailed link, or {email, code}. Sets the httpOnly
        session cookies (`baton_erp`, `baton_erp_rt` on .batontasks.com) and returns the same
        session in the body: `session_token` is the Bearer for this API (agents, CLI, local
        development), `refresh_token` renews it via /auth/refresh.
      responses:
        "200": {description: "session_token, refresh_token, expires_at, user, workspaces[], workspace_id"}
        "401": {description: Invalid or expired link/code}
        "403": {description: "The account has no Baton workspace (code no_account)"}
  /auth/login:
    post:
      tags: [Auth]
      summary: Sign in with a password
      security: []
      description: |
        Body {login, password}. New accounts have no password — set one via /auth/password/forgot +
        /auth/password/reset or /auth/password/change. Same response as e-mail verify — unless the
        account has two-factor authentication (TOTP) turned on: then the answer is
        `{twofa_required: true, pending, method: "totp"}` with no session and no cookies; ask for
        the code and finish with `POST /auth/2fa/verify`. Only password sign-in asks for the second
        factor (codes, links, Google/Apple and passkeys never do).
      responses:
        "200": {description: "session_token, refresh_token, expires_at, user, workspaces[], workspace_id — or {twofa_required: true, pending, method: totp}"}
        "401": {description: Invalid credentials}
        "403": {description: "The account has no Baton workspace (code no_account)"}
  /auth/oauth:
    post:
      tags: [Auth]
      summary: Sign in or sign up with Google / Apple
      security: []
      description: |
        Body {provider: google|apple, id_token, workspace_name?, plan?}. Obtain the id_token in
        the browser (Google Identity Services / Sign in with Apple JS) with the client_id from
        /auth/config. An unknown person with a verified e-mail is signed up (draft workspace).
      responses:
        "200": {description: "session_token, refresh_token, expires_at, user, workspaces[], workspace_id"}
        "401": {description: Token rejected or e-mail not verified}
  /auth/passkey/login/options:
    post:
      tags: [Auth]
      summary: Passkey sign-in options
      security: []
      responses:
        "200": {description: "PublicKeyCredentialRequestOptions — call navigator.credentials.get()"}
  /auth/passkey/login:
    post:
      tags: [Auth]
      summary: Sign in with a passkey
      security: []
      description: Body {credential}. Same response as e-mail verify.
      responses:
        "200": {description: "session_token, refresh_token, expires_at, user, workspaces[], workspace_id"}
  /auth/2fa/verify:
    post:
      tags: [Auth]
      summary: Finish password sign-in with the second factor
      security: []
      description: |
        Body {pending, code}: `pending` from the /auth/login answer (valid 5 minutes, single use),
        `code` — 6 digits from the authenticator app or one of the one-time recovery codes.
        Same response as e-mail verify (cookies + session).
      responses:
        "200": {description: "session_token, refresh_token, expires_at, user, workspaces[], workspace_id"}
        "401": {description: "Wrong code, or unknown/expired/used pending — sign in again"}
        "422": {description: pending and code are required}
        "429": {description: Too many attempts}
  /auth/passkey/register/options:
    post:
      tags: [Auth]
      summary: Options for adding a passkey (signed in)
      description: |
        Session required (cookie or `Bearer <session_token>`; agent `bt_` tokens are refused).
        Returns PublicKeyCredentialCreationOptions — `{rp:{id,name}, user:{id,name,displayName},
        challenge, pubKeyCredParams[], timeout, attestation, excludeCredentials[],
        authenticatorSelection}`; binary fields are base64url — decode them before
        navigator.credentials.create(). The challenge lives 5 minutes. A passkey belongs to the
        person's BMI account, so it also signs them in to other BMI products.
      responses:
        "200": {description: "PublicKeyCredentialCreationOptions (base64url fields)"}
        "401": {description: Not signed in}
        "422": {description: Passkeys are not available for Baton}
  /auth/passkey/register:
    post:
      tags: [Auth]
      summary: Add a passkey (signed in)
      description: |
        Body {credential, label?}: `credential` is the result of navigator.credentials.create()
        serialized to JSON (`id`, `rawId`, `type`, `response: {clientDataJSON, attestationObject}`,
        `transports?` — base64url), `label` names the device ("MacBook"). The challenge, origin
        and relying party are checked by the account service.
      responses:
        "200": {description: "{ok: true, id} — id of the stored passkey"}
        "401": {description: Not signed in}
        "409": {description: This passkey is already registered}
        "422": {description: "credential missing, or the registration did not verify (expired challenge, wrong origin)"}
  /auth/password/forgot:
    post:
      tags: [Auth]
      summary: E-mail a password reset code
      security: []
      description: Body {identifier} (e-mail). Always 200.
      responses:
        "200": {description: Code sent if the account exists}
  /auth/password/reset:
    post:
      tags: [Auth]
      summary: Set a new password with the reset code
      security: []
      description: Body {identifier, code, password}. Signs out every other session and signs this one in.
      responses:
        "200": {description: "session_token, refresh_token, expires_at, user, workspaces[], workspace_id"}
  /auth/password/change:
    post:
      tags: [Auth]
      summary: Set or change the password (signed in)
      description: Body {current_password?, password}.
      responses:
        "200": {description: Password changed}
  /auth/sso-code:
    post:
      tags: [Auth]
      summary: One-time code to open another BMI product as the same person
      responses:
        "200": {description: "{code, expires_in: 120}"}
  /auth/sso/exchange:
    post:
      tags: [Auth]
      summary: Sign in with a one-time code from another BMI product
      security: []
      description: Body {code, workspace_id?}. Same response as e-mail verify.
      responses:
        "200": {description: "session_token, refresh_token, expires_at, user, workspaces[], workspace_id"}
        "401": {description: "Unknown, expired or used code"}
  /auth/refresh:
    post:
      tags: [Auth]
      summary: Renew the session
      security: []
      description: Body {refresh_token} or the refresh cookie. With cookies the API also renews silently on any request.
      responses:
        "200": {description: "session_token, refresh_token, expires_at, user, workspaces[], workspace_id"}
        "401": {description: Session expired — sign in again}
  /auth/me:
    get:
      tags: [Auth]
      summary: Current person and their workspaces (session)
      responses:
        "200": {description: "user {id, email, name}, workspaces [{id, slug, name, actor_id, role, setup_pending}], workspace_id"}
  /auth/logout:
    post:
      tags: [Auth]
      summary: Revoke the session
      responses:
        "200": {description: Signed out}
  /workspaces:
    post:
      tags: [Auth]
      summary: Create a workspace (self-serve signup, session required)
      description: |
        Body {name, plan?} — `plan` is the `?plan=` of the pricing page (free|pro|business; without
        it — the plan chosen at sign-up). Free and Pro (early access) start right away; a plan that
        needs payment starts the workspace on Free with `pending_plan` set — continue with
        `POST /billing/plan` to get the checkout link. Finishes the draft workspace created at sign-up (or creates
        another one): the owner actor, an "AI Agent" actor operated by the owner, a MAIN
        project with the approval gate on — and returns ONCE a pair of bt_ tokens: agent
        (works tasks) and owner (approves). Session auth for workspace APIs afterwards: the
        session cookie or `Authorization: Bearer <session_token>`, plus the
        `X-Baton-Workspace` header (without it — the workspace the session was issued for).
      responses:
        "201": {description: "workspace {id, slug, name, plan, pending_plan}, actors, tokens (shown once)"}
  /billing:
    get:
      tags: [Billing]
      summary: Plan, subscription, limits and usage of the workspace
      description: |
        Any actor of the workspace may read it (agents see their limits); links and
        `can_manage: true` only for a human owner/admin. Served from Baton's cache of the billing
        state — if the billing backend is down you still get the cached plan with
        `erp_available: false`. The cache is refreshed from billing when the subscription state is
        older than 10 minutes, with `refresh=1`, or with `session_id` — pass the
        `session_id` Stripe appends to the success URL when the customer returns from checkout,
        and the new plan shows up without waiting for the webhook.
      parameters:
        - {name: session_id, in: query, required: false, schema: {type: string}, description: "cs_… from the checkout success URL"}
        - {name: refresh, in: query, required: false, schema: {type: string, enum: ["1"]}}
        - {name: portal, in: query, required: false, schema: {type: string, enum: ["1"]}, description: "also return portal_url (owner/admin, paid subscription)"}
      responses:
        "200":
          description: Billing state
          content:
            application/json:
              schema:
                type: object
                properties:
                  billing: {$ref: "#/components/schemas/BillingState"}
  /billing/plan:
    post:
      tags: [Billing]
      summary: Choose a plan (owner/admin)
      description: |
        Body {plan: free|pro|business, currency?: USD|EUR}. The pricing page's `?plan=` lands here.
        `action` says what happened:
        - `activated` — Free, or Pro during early access, switched on right away (no payment);
        - `checkout` — a paid plan without a subscription: send the person to `checkout_url`
          (Stripe Checkout, per person per month, seats = active people). The plan switches on
          once paid — `GET /billing?session_id=…` on return, or the webhook;
        - `changed` — the paid subscription moved to another paid plan (prorated);
        - `cancel_scheduled` — leaving a paid plan: it stays until `effective_at` (end of the paid
          period), then `pending_plan` takes over;
        - `resumed` — the paid plan was chosen again before the period ended: cancellation undone;
        - `unchanged`.
      requestBody:
        content:
          application/json:
            schema:
              type: object
              required: [plan]
              properties:
                plan: {$ref: "#/components/schemas/PlanCode"}
                currency: {type: string, enum: [USD, EUR], default: USD}
      responses:
        "200":
          description: Result and the new billing state
          content:
            application/json:
              schema:
                type: object
                properties:
                  action: {type: string, enum: [activated, checkout, changed, cancel_scheduled, resumed, unchanged]}
                  checkout_url: {type: string, nullable: true}
                  effective_at: {type: string, nullable: true, description: "ISO 8601, for cancel_scheduled"}
                  billing: {$ref: "#/components/schemas/BillingState"}
        "403": {$ref: "#/components/responses/Forbidden"}
        "409": {description: "billing_conflict — the account needs a manual fix (support)"}
        "422": {$ref: "#/components/responses/Validation"}
        "503": {description: "billing_unavailable — billing backend down or paid plans not open yet; nothing changed"}
  /billing/portal:
    post:
      tags: [Billing]
      summary: Link to the Stripe billing portal (owner/admin)
      description: Body {return_url?} (https; default — the Billing page). Card, invoices, cancellation.
      responses:
        "200":
          description: "{url}"
        "409": {description: no_subscription — the workspace has no paid subscription}
        "503": {description: billing_unavailable}
  /billing/checkout:
    post:
      tags: [Billing]
      deprecated: true
      summary: Choose a plan (legacy form of POST /billing/plan)
      description: Body {plan}. Same as `POST /billing/plan`, plus `status` (`checkout` | `active`) and `message`.
      responses:
        "200": {description: "Same as POST /billing/plan + status, message"}
  /billing/webhook:
    post:
      tags: [Billing]
      summary: Subscription events from the billing backend (server-to-server)
      security: []
      description: |
        Not for clients. The billing backend (ERP) posts every subscription event with a fresh
        subscription state: `X-Erp-Signature: t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<body>")>`
        (5-minute window), `X-Erp-Event: evt_…`. Idempotent by event id; a state older than the
        one already applied (`state_at`) is ignored. `200` — applied, duplicate or unknown
        workspace; `401` — bad signature; `503` — not configured (the sender retries).
      responses:
        "200": {description: "{ok, duplicate?, ignored?}"}
        "400": {description: Invalid payload}
        "401": {description: Invalid signature}
  /health:
    get:
      tags: [Service]
      summary: Health check (public)
      security: []
      responses:
        "200":
          description: OK
  /me:
    get:
      tags: [Service]
      summary: Who am I
      description: |
        `scopes` and `project_ids` are what this request may actually do and see —
        the actor's rights and boards, narrowed by the token. What the token itself
        carries is under `token`.
      responses:
        "200":
          description: Current actor, workspace, effective scopes and boards
  /tasks:
    get:
      tags: [Tasks]
      summary: List tasks
      parameters:
        - {name: project, in: query, schema: {type: string}, description: Project id or slug}
        - {name: status, in: query, schema: {type: string}, description: "Comma-separated: new,approved,..."}
        - {name: assignee, in: query, schema: {type: string}, description: Actor id or "me"}
        - {name: author, in: query, schema: {type: string}, description: Actor id or "me"}
        - {name: ball, in: query, schema: {type: string, enum: [author, assignee]}}
        - {name: priority, in: query, schema: {type: integer, minimum: 0, maximum: 3}}
        - {name: tag, in: query, schema: {type: string}}
        - {name: q, in: query, schema: {type: string}, description: Substring search in title/description}
        - {name: updated_since, in: query, schema: {type: string, format: date-time}}
        - {name: ready, in: query, schema: {type: integer, enum: [1]}, description: Only approved tasks with no open blockers}
        - {name: sort, in: query, schema: {type: string, enum: [rank, updated, priority], default: rank}}
        - {name: limit, in: query, schema: {type: integer, default: 100, maximum: 200}}
      responses:
        "200":
          description: Tasks
          content:
            application/json:
              schema:
                type: object
                properties:
                  tasks: {type: array, items: {$ref: "#/components/schemas/Task"}}
                  count: {type: integer}
    post:
      tags: [Tasks]
      summary: Create a task
      description: Supports Idempotency-Key.
      parameters:
        - {name: Idempotency-Key, in: header, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [project, title]
              properties:
                project: {type: string, description: Project id or slug}
                title: {type: string, maxLength: 500}
                description: {type: string, description: Markdown}
                status: {type: string, enum: [draft, new], default: new}
                priority: {type: integer, minimum: 0, maximum: 3, default: 2}
                assignee_actor_id: {type: integer, nullable: true}
                tags: {type: array, items: {type: string}}
                due_at: {type: string, format: date-time, nullable: true}
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                type: object
                properties:
                  task: {$ref: "#/components/schemas/Task"}
        "422": {$ref: "#/components/responses/Validation"}
  /tasks/{ref}:
    parameters:
      - {name: ref, in: path, required: true, schema: {type: string}, description: '"APP-123" or numeric id'}
    get:
      tags: [Tasks]
      summary: Get a task with its thread
      parameters:
        - {name: include, in: query, schema: {type: string, default: comments}, description: "Comma-separated: comments,events"}
      responses:
        "200":
          description: Task, comments, dependencies
        "404": {$ref: "#/components/responses/NotFound"}
    patch:
      tags: [Tasks]
      summary: Edit or reassign a task
      description: |
        Author, assignee or a human admin. Fields not sent stay unchanged.
        `assignee_actor_id` is how a task changes hands (null puts it back in the free pool).
        An agent asked in chat to pick up a task that belongs to its operator cannot do this
        with its own token — it is neither author nor assignee, and gets 403; the call is made
        with the operator's token (the `assign` command of the CLI skill). After that the
        agent runs the task through `/transition` normally, with its own token.
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                title: {type: string}
                description: {type: string}
                priority: {type: integer, minimum: 0, maximum: 3}
                assignee_actor_id: {type: integer, nullable: true}
                tags: {type: array, items: {type: string}}
                due_at: {type: string, format: date-time, nullable: true}
      responses:
        "200": {description: Updated task}
        "403": {$ref: "#/components/responses/Forbidden"}
  /tasks/{ref}/transition:
    post:
      tags: [Tasks]
      summary: Change task status
      description: |
        Flow: draft→new→approved→in_progress→review→done, plus waiting
        (in_progress↔waiting), rejected (from new), cancelled (from any active).
        Reopen: done/rejected/cancelled→new (the author or an admin; timestamps reset,
        the approval gate applies again).
        Permissions: approve/reject — humans with approve scope only;
        in_progress/waiting/review — the assignee (an unassigned task is taken by
        the caller); done from review — the author or an admin. 409 on violation
        with the allowed targets in the message — "task is assigned to someone else"
        means the task has to change hands first (PATCH `assignee_actor_id`).
      parameters:
        - {name: ref, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [status]
              properties:
                status: {type: string, enum: [new, approved, rejected, in_progress, waiting, review, done, cancelled]}
                comment: {type: string, description: Optional comment posted atomically with the transition}
      responses:
        "200": {description: Updated task}
        "409": {$ref: "#/components/responses/InvalidTransition"}
  /tasks/approve:
    post:
      tags: [Tasks]
      summary: 'Bulk approve ("do 1, 2 and 3")'
      description: Humans with approve scope only.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [refs]
              properties:
                refs: {type: array, items: {type: string}}
      responses:
        "200":
          description: Per-ref results, ok or error
  /tasks/{ref}/comments:
    post:
      tags: [Tasks]
      summary: Comment on a task
      description: |
        A comment from the author passes the ball to the assignee and vice versa. Supports Idempotency-Key.
        Also accepts multipart/form-data: field `body` + `files[]` (up to 5 files, 10 MB each) —
        attachments are stored with the comment and listed in `comment.attachments`.
      parameters:
        - {name: ref, in: path, required: true, schema: {type: string}}
        - {name: Idempotency-Key, in: header, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [body]
              properties:
                body: {type: string, description: Markdown}
      responses:
        "201": {description: Comment + updated task}
  /tasks/{ref}/dependencies:
    post:
      tags: [Tasks]
      summary: Add a blocker
      parameters:
        - {name: ref, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [blocking_ref]
              properties:
                blocking_ref: {type: string}
      responses:
        "201": {description: Dependency created}
  /tasks/{ref}/dependencies/{depId}:
    delete:
      tags: [Tasks]
      summary: Remove a blocker
      parameters:
        - {name: ref, in: path, required: true, schema: {type: string}}
        - {name: depId, in: path, required: true, schema: {type: integer}}
      responses:
        "200": {description: Removed}
  /inbox:
    get:
      tags: [Inbox]
      summary: What happened since my cursor
      description: Events on my subscriptions (my tasks, tasks I comment on, projects I follow), excluding my own actions. Does not advance the cursor.
      parameters:
        - {name: limit, in: query, schema: {type: integer, default: 100, maximum: 500}}
      responses:
        "200":
          description: Events, task summaries, cursor to ack
          content:
            application/json:
              schema:
                type: object
                properties:
                  events: {type: array, items: {$ref: "#/components/schemas/Event"}}
                  tasks: {type: object, additionalProperties: {$ref: "#/components/schemas/Task"}}
                  cursor: {type: integer}
                  has_more: {type: boolean}
  /inbox/ack:
    post:
      tags: [Inbox]
      summary: Confirm processing up to cursor
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [cursor]
              properties:
                cursor: {type: integer}
      responses:
        "200": {description: New cursor position}
  /events:
    get:
      tags: [Events]
      summary: Raw event journal (audit)
      parameters:
        - {name: task, in: query, schema: {type: string}}
        - {name: cursor, in: query, schema: {type: integer}}
        - {name: limit, in: query, schema: {type: integer, default: 100, maximum: 500}}
      responses:
        "200": {description: Events}
  /attachments/{id}/download:
    get:
      tags: [Tasks]
      summary: Download a comment attachment
      description: Access requires visibility of the attachment's task. png/jpeg/gif/webp are served inline, everything else as attachment.
      parameters:
        - {name: id, in: path, required: true, schema: {type: integer}}
      responses:
        "200": {description: File content}
        "404": {$ref: "#/components/responses/NotFound"}
  /channels:
    get:
      tags: [Channels]
      summary: List notification channels (admin)
      responses:
        "200": {description: Channels (secrets truncated)}
    post:
      tags: [Channels]
      summary: Create a channel (admin)
      description: |
        Types: `webhook` (config: {url, secret?} — POST JSON with HMAC `X-Baton-Signature: sha256=...`),
        `slack` (config: {webhook_url} — Slack Incoming Webhook, human-readable RU text).
        Also: `telegram` (config: {bot_token, chat_id} — Bot API sendMessage; add approve
        buttons with POST /channels/{id}/telegram/webhook) and
        `email` (config: {smtp_host, smtp_port?, smtp_user, smtp_pass, from?, to} — client's own SMTP).
        Optional `config.link_template` (e.g. "https://your-erp/?task={ref}") appends a deep link
        to every notification — Baton doesn't need to know your UI, you tell it where tasks live.
        A channel without one falls back to the workspace-wide `settings.link_template`.
        `event_filter`: {types: [...], project_ids: [...]} — both optional, null = everything.
        Delivery is async (dispatcher daemon), retries with exponential backoff up to 10 attempts.

        **Personal channels.** Add `event_filter.actor_id` (optionally `roles: ["author","assignee"]`,
        default both) and the channel only receives events of tasks where that actor is author or
        assignee — and never their own actions, same rule as the inbox. Notifications about a task
        awaiting approval then carry **one-time action links** (`approve`/`cancel`): `actions` in the
        webhook JSON, Block Kit buttons in Slack, links in email, inline buttons in Telegram.
        (Install the Baton Slack app — `GET /slack/install?workspace={id}`, session auth — and its
        buttons become interactive instead: the press goes back to Baton and Slack vouches for who
        pressed it. A freshly installed Slack channel starts filtered to `task.created` +
        `task.status_changed`; widen it with PATCH. Without the app a `slack` channel is a plain
        Incoming Webhook and gets link buttons.) The link opens a
        confirmation page (`GET /a/{token}` never changes anything — mail clients and messengers
        prefetch links); the action runs on POST from that page, once, as the channel's actor and
        under the usual permission checks. Links expire in 7 days.
      responses:
        "201": {description: Created}
        "402": {$ref: "#/components/responses/PlanLimit"}
  /channels/{id}:
    parameters:
      - {name: id, in: path, required: true, schema: {type: integer}}
    patch:
      tags: [Channels]
      summary: Edit a channel (admin)
      responses:
        "200": {description: Updated}
    delete:
      tags: [Channels]
      summary: Delete a channel with its delivery log (admin)
      responses:
        "200": {description: Deleted}
  /channels/{id}/deliveries:
    get:
      tags: [Channels]
      summary: Recent delivery attempts (admin, debugging)
      parameters:
        - {name: id, in: path, required: true, schema: {type: integer}}
      responses:
        "200": {description: Last 50 deliveries with status/attempts/response}
  /channels/{id}/telegram/webhook:
    post:
      tags: [Telegram]
      summary: Turn a telegram channel interactive (admin)
      description: |
        Registers the Bot API webhook so button presses reach Baton, stores the
        generated `secret_token` in the channel config and learns the bot's username.
        From then on every notification about a task awaiting approval carries
        **[✅ Одобрить]** (and **[🔗 Открыть]** when `config.link_template` is set) —
        approve from the phone, no app required.
      parameters:
        - {name: id, in: path, required: true, schema: {type: integer}}
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                url: {type: string, description: "Webhook URL to register; default: BATON_API_URL + /v1/telegram/webhook"}
      responses:
        "200": {description: "Registered — {ok, url, bot_username}"}
        "404": {$ref: "#/components/responses/NotFound"}
        "502": {description: Bot API refused the webhook}
  /me/telegram/link:
    post:
      tags: [Telegram]
      summary: One-time code linking your Telegram account to your actor
      description: |
        Returns a code (valid 15 minutes, single use) and a `t.me` deep link. The
        human sends `/start CODE` to the bot; from then on their presses act as
        this actor — with the usual rights (an agent actor can never approve).
      responses:
        "200": {description: "{code, deep_link, bot_username, expires_in}"}
        "422": {description: Only human actors can link Telegram}
  /telegram/webhook:
    post:
      tags: [Telegram]
      summary: Bot API updates land here (called by Telegram)
      security: []
      description: |
        Authenticated by the `X-Telegram-Bot-Api-Secret-Token` header set during
        setup — not by a Baton token. Handles `callback_query` (approve button:
        resolves the presser via actors.telegram_user_id, then goes through the
        normal transition checks) and `/start CODE` messages (account linking).
        Anything else is acknowledged and ignored.
      responses:
        "200": {description: Update processed}
        "403": {description: Unknown webhook secret}
  /import/tasks:
    post:
      tags: [Tasks]
      summary: Bulk import tasks from another tracker (admin)
      description: |
        Up to 500 tasks per call: title (required), status/priority/tags, historical
        created_at/completed_at, comments with author_name mapping (actors matched by name,
        fallback — the importing actor), external_id for idempotency (repeat runs skip).
        Closed tasks are imported silently (no events); open ones get task.created + subscriptions.
        Approval gate is not applied — statuses land as-is. Returns 201, or 207 with per-row errors.
      responses:
        "201": {description: All rows imported/skipped}
        "207": {description: "Partial success, see errors[]"}
  /projects:
    get:
      tags: [Projects]
      summary: List projects
      responses:
        "200": {description: Projects}
    post:
      tags: [Projects]
      summary: Create a project (projects:write)
      description: |
        Needs `projects:write` — a right that can be given to an ordinary member
        without making them a workspace co-owner (`admin` implies it). A creator
        who is limited to a list of boards is added to the new board automatically.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [slug, name]
              properties:
                slug: {type: string, pattern: "^[A-Z][A-Z0-9_]{0,31}$"}
                name: {type: string}
                description: {type: string}
                approval_required: {type: boolean, default: true}
      responses:
        "201": {description: Created}
        "402": {$ref: "#/components/responses/PlanLimit"}
  /projects/{id}:
    parameters:
      - {name: id, in: path, required: true, schema: {type: string}}
    get:
      tags: [Projects]
      summary: Get a project
      responses:
        "200": {description: Project}
    patch:
      tags: [Projects]
      summary: Edit a project (projects:write)
      responses:
        "200": {description: Updated}
  /projects/{id}/rank:
    post:
      tags: [Projects]
      summary: Re-order the backlog
      description: Passed refs get ranks in the given order; unmentioned tasks keep theirs. Made for AI-driven backlog sorting.
      parameters:
        - {name: id, in: path, required: true, schema: {type: string}}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [ordered_refs]
              properties:
                ordered_refs: {type: array, items: {type: string}}
      responses:
        "200": {description: Re-ranked}
  /actors:
    get:
      tags: [Actors]
      summary: List workspace actors
      responses:
        "200": {description: Actors}
    post:
      tags: [Actors]
      summary: Create an actor (admin, or your own agent with actors:write)
      description: |
        Inviting a person needs `admin`. Creating an **agent you operate** needs only
        `actors:write`: `operator_actor_id` is then yourself, and the agent starts with
        your boards and no more than your own scopes.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [type, name]
              properties:
                type: {type: string, enum: [human, agent]}
                name: {type: string}
                role: {type: string, enum: [owner, admin, member, agent]}
                email: {type: string, nullable: true}
                operator_actor_id: {type: integer, nullable: true, description: The human operating this agent}
                scopes:
                  type: array
                  nullable: true
                  items: {$ref: "#/components/schemas/Scope"}
                  description: Explicit rights; null (default) = the defaults for the role
                project_ids:
                  type: array
                  nullable: true
                  items: {type: integer}
                  description: Boards this actor is allowed on; null (default) = every board
      responses:
        "201": {description: Created}
        "402": {$ref: "#/components/responses/PlanLimit"}
  /actors/{id}:
    parameters:
      - {name: id, in: path, required: true, schema: {type: integer}}
    patch:
      tags: [Actors]
      summary: Edit an actor — role, rights, board access (admin, or your own agent)
      description: |
        The one place where access changes. Everything here applies to tokens that
        were already issued, so widening or revoking access never means reissuing a
        secret: adding a person to a new board is `project_ids`, giving them the
        right to create boards is `scopes`, making them an admin is `role`.

        `scopes: null` returns the actor to the defaults of their role; a list above
        the ceiling of the role is refused (422) rather than silently trimmed.
        `project_ids: null` clears the restriction (every board), a non-empty list
        replaces it. The workspace always keeps at least one active owner (409).
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                name: {type: string}
                email: {type: string, nullable: true}
                role:
                  type: string
                  enum: [owner, admin, member, agent]
                  description: "owner|admin|member for humans, agent for agents"
                is_active: {type: boolean}
                operator_actor_id: {type: integer, nullable: true}
                scopes:
                  type: array
                  nullable: true
                  items: {$ref: "#/components/schemas/Scope"}
                project_ids:
                  type: array
                  nullable: true
                  items: {type: integer}
      responses:
        "200": {description: The actor with its effective scopes and boards}
        "409": {description: The workspace must keep at least one active owner}
        "404": {$ref: "#/components/responses/NotFound"}
  /actors/{id}/telegram:
    parameters:
      - {name: id, in: path, required: true, schema: {type: integer}}
    post:
      tags: [Telegram]
      summary: Link a Telegram account to an actor (admin)
      description: |
        Manual alternative to the self-serve code flow (`POST /me/telegram/link`),
        for when the numeric Telegram user id is already known — in a private chat
        it is the channel's `chat_id`. One Telegram account maps to one actor per
        workspace; linking it elsewhere releases the previous binding.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [telegram_user_id]
              properties:
                telegram_user_id: {type: string, description: Numeric Telegram user id}
      responses:
        "200": {description: Linked}
        "404": {$ref: "#/components/responses/NotFound"}
    delete:
      tags: [Telegram]
      summary: Unlink an actor's Telegram account (admin)
      responses:
        "200": {description: Unlinked}
        "404": {$ref: "#/components/responses/NotFound"}
  /actors/{id}/slack:
    parameters:
      - {name: id, in: path, required: true, schema: {type: integer}}
    post:
      tags: [Slack]
      summary: Link a Slack account to an actor (admin)
      description: |
        Manual linking for when the Slack user id is already known. Usually not
        needed — a first button press is matched by email automatically. One
        Slack account maps to one actor per workspace; linking it elsewhere
        releases the previous binding.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [slack_user_id]
              properties:
                slack_user_id: {type: string, description: "Slack user id like U01ABCDEF"}
      responses:
        "200": {description: Linked}
        "404": {$ref: "#/components/responses/NotFound"}
    delete:
      tags: [Slack]
      summary: Unlink an actor's Slack account (admin)
      responses:
        "200": {description: Unlinked}
        "404": {$ref: "#/components/responses/NotFound"}
  /actors/{id}/slack/dm:
    parameters:
      - {name: id, in: path, required: true, schema: {type: integer}}
    post:
      tags: [Slack]
      summary: Turn on personal Slack messages for an actor (admin)
      description: |
        Same effect as the self-serve `POST /me/slack/dm`, but done by an admin —
        onboarding people who never open Baton themselves. Requires the Baton
        Slack app installed in the workspace and the actor's Slack account linked
        (or matchable by email). Optional `project_ids` narrows the DM feed the
        way a person's own project-scoped token would. `author_updates: true`
        also brings the progress of tasks the person created — status changes and
        other people's comments; omit it to keep the channel's current setting.
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                project_ids: {type: array, items: {type: integer}, description: Limit DMs to these projects}
                author_updates: {type: boolean, description: "Also DM status changes and comments on tasks this actor authored"}
      responses:
        "201": {description: Personal DM channel created or re-enabled}
        "402": {$ref: "#/components/responses/PlanLimit"}
        "404": {$ref: "#/components/responses/NotFound"}
        "409": {description: "Slack app not installed, or no Slack account matched"}
    delete:
      tags: [Slack]
      summary: Turn off an actor's personal Slack messages (admin)
      responses:
        "200": {description: Turned off}
        "404": {$ref: "#/components/responses/NotFound"}
  /me/slack/dm:
    post:
      tags: [Slack]
      summary: Turn on personal Slack messages for yourself
      description: |
        The Baton bot DMs you the things that wait on your decision — approve,
        answer a question, accept work. Requires the Baton Slack app installed
        in the workspace; your Slack account is matched by email if not linked
        yet. A project-scoped token narrows the DM feed to its projects.
        `author_updates: true` also DMs you the progress of tasks you created —
        status changes and other people's comments (never your own steps).
        Omit it to keep the current setting, `false` turns it off.
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                author_updates: {type: boolean, description: "Also DM status changes and comments on tasks you authored"}
      responses:
        "201": {description: Personal DM channel created or re-enabled}
        "402": {$ref: "#/components/responses/PlanLimit"}
        "409": {description: "Slack app not installed, or no Slack account matched"}
    delete:
      tags: [Slack]
      summary: Turn off your personal Slack messages
      responses:
        "200": {description: Turned off}
  /actors/{id}/tokens:
    get:
      tags: [Actors]
      summary: List an actor's tokens (admin, or your own agent)
      description: Metadata only — name, prefix, scopes, timestamps. Token values are never returned.
      parameters:
        - {name: id, in: path, required: true, schema: {type: integer}}
      responses:
        "200": {description: Tokens}
        "404": {$ref: "#/components/responses/NotFound"}
    post:
      tags: [Actors]
      summary: Issue a token (admin, or for your own agent)
      description: |
        An operator issues tokens for the agents they run themselves — as many as they
        need, each with its own `name` (one per machine keeps a lost laptop down to a
        single revoke). Tokens for people, or for someone else's agent, need `admin`.

        The token value is returned once. Leave `scopes` and `project_ids` out and the
        token simply follows its actor — rights granted or taken away later apply to it
        without a reissue. Pass either one to deliberately narrow this particular key
        (a read-only integration, a token scoped to one board). Narrowing only: a token
        never carries more than its actor may do, so agent tokens never get approve or
        admin, and a member's token never gets admin.
      parameters:
        - {name: id, in: path, required: true, schema: {type: integer}}
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                name: {type: string}
                scopes:
                  type: array
                  nullable: true
                  items: {$ref: "#/components/schemas/Scope"}
                  description: null (default) = follow the actor's rights
                project_ids:
                  type: array
                  nullable: true
                  items: {type: integer}
                  description: null (default) = every board the actor is allowed on
      responses:
        "201": {description: "Token (plaintext, shown once) with the scopes it ended up with"}
  /tokens/{id}:
    patch:
      tags: [Actors]
      summary: Re-cut a token in place (admin, or your own agent's token)
      description: |
        Edits the narrowing of a token that is already out there — its value does not
        change, so nothing has to be redistributed. `scopes: null` / `project_ids: null`
        drop the narrowing and let the token follow its actor again. A revoked token is
        not repaired, only replaced (409).
      parameters:
        - {name: id, in: path, required: true, schema: {type: integer}}
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                name: {type: string}
                scopes:
                  type: array
                  nullable: true
                  items: {$ref: "#/components/schemas/Scope"}
                project_ids: {type: array, nullable: true, items: {type: integer}}
      responses:
        "200": {description: Token metadata (the value is never returned)}
        "409": {description: The token is revoked}
        "404": {$ref: "#/components/responses/NotFound"}
    delete:
      tags: [Actors]
      summary: Revoke a token (admin, or your own agent's token)
      parameters:
        - {name: id, in: path, required: true, schema: {type: integer}}
      responses:
        "200": {description: Revoked}

components:
  securitySchemes:
    bearer:
      type: http
      scheme: bearer
      bearerFormat: "bt_..."
  responses:
    NotFound:
      description: Not found (or not visible to this token)
    Forbidden:
      description: The token or actor may not do that
    Validation:
      description: Invalid input
    InvalidTransition:
      description: The status change is not allowed; the message lists allowed targets
    PlanLimit:
      description: |
        Over the workspace plan: `plan_limit` (details: {limit: humans|agents|projects, max, used,
        plan, upgrade_to}) or `plan_feature` (details: {feature: channels, plan, upgrade_to}).
      content:
        application/json:
          schema: {$ref: "#/components/schemas/Error"}
  schemas:
    PlanCode:
      type: string
      enum: [free, pro, business]
    Entitlements:
      type: object
      description: "null = unlimited. history_days and events_per_month are shown but not enforced yet."
      properties:
        max_humans: {type: integer, nullable: true}
        max_agents: {type: integer, nullable: true}
        max_projects: {type: integer, nullable: true}
        history_days: {type: integer, nullable: true}
        events_per_month: {type: integer, nullable: true}
        channels: {type: boolean, description: "Slack, Telegram, email and webhook notifications"}
        audit_log: {type: boolean}
        sso: {type: boolean}
        priority_support: {type: boolean}
    Subscription:
      type: object
      properties:
        id: {type: string, examples: [sub_1Q2w3E]}
        status: {type: string, enum: [trialing, active, past_due, incomplete]}
        plan: {oneOf: [{$ref: "#/components/schemas/PlanCode"}, {type: "null"}]}
        quantity: {type: integer, description: seats (people)}
        currency: {type: string, nullable: true, enum: [USD, EUR, null]}
        current_period_end: {type: string, nullable: true}
        cancel_at_period_end: {type: boolean}
        canceled_at: {type: string, nullable: true}
        trial_end: {type: string, nullable: true}
    BillingState:
      type: object
      properties:
        workspace_id: {type: integer}
        plan: {$ref: "#/components/schemas/PlanCode"}
        status:
          type: string
          enum: [free, early_access, active, trialing, past_due, incomplete, manual]
          description: |
            `early_access` — Pro at $0; `past_due` — payment failed, the plan still works while
            Stripe retries; `incomplete` — the first payment needs action; `manual` — set by support.
        pending_plan: {oneOf: [{$ref: "#/components/schemas/PlanCode"}, {type: "null"}], description: "switches on after checkout, or at the end of the paid period"}
        subscription: {oneOf: [{$ref: "#/components/schemas/Subscription"}, {type: "null"}]}
        checkout_url: {type: string, nullable: true, description: "unfinished checkout (owner/admin only)"}
        checkout_expires_at: {type: string, nullable: true}
        portal_url: {type: string, nullable: true, description: "only with ?portal=1"}
        last_invoice:
          type: object
          nullable: true
          properties:
            id: {type: string}
            number: {type: string}
            status: {type: string}
            amount_due: {type: integer, description: minor units}
            amount_paid: {type: integer}
            currency: {type: string}
            hosted_invoice_url: {type: string, nullable: true}
            event: {type: string}
        entitlements: {$ref: "#/components/schemas/Entitlements"}
        usage:
          type: object
          properties:
            humans: {type: integer}
            agents: {type: integer}
            projects: {type: integer}
            channels: {type: integer}
            events_this_month: {type: integer}
        over_limit: {type: array, items: {type: string, enum: [humans, agents, projects, channels, events_per_month]}}
        seats: {type: integer, description: "active people = seats of a paid subscription"}
        early_access: {type: boolean, description: "Pro is free right now"}
        can_manage: {type: boolean}
        billing_enabled: {type: boolean}
        erp_available: {type: boolean, description: "false — billing backend unreachable, state is from cache"}
        plans:
          type: array
          items:
            type: object
            properties:
              code: {$ref: "#/components/schemas/PlanCode"}
              name: {type: string}
              price_per_person_usd: {type: integer}
              free_during_early_access: {type: boolean}
              checkout_required: {type: boolean}
              entitlements: {$ref: "#/components/schemas/Entitlements"}
        updated_at: {type: string, nullable: true}
    Scope:
      type: string
      enum: ["tasks:read", "tasks:write", approve, "projects:write", "actors:write", admin]
      description: |
        `approve` — humans only; `projects:write` — create and edit boards;
        `actors:write` — humans only: your own agents and their tokens;
        `admin` — everything else in the workspace (people, anyone's tokens, channels,
        import) and it implies `projects:write` and `actors:write`.
    Task:
      type: object
      properties:
        id: {type: integer}
        ref: {type: string, examples: [APP-123]}
        project_id: {type: integer}
        title: {type: string}
        description: {type: string, nullable: true}
        status: {type: string, enum: [draft, new, approved, in_progress, review, waiting, done, rejected, cancelled]}
        priority: {type: integer, minimum: 0, maximum: 3, description: 0=P0 urgent .. 3=P3 someday}
        author: {$ref: "#/components/schemas/ActorBrief"}
        assignee: {oneOf: [{$ref: "#/components/schemas/ActorBrief"}, {type: "null"}]}
        ball_side: {type: string, enum: [author, assignee], nullable: true}
        rank: {type: number}
        tags: {type: array, items: {type: string}}
        due_at: {type: string, nullable: true}
        started_at: {type: string, nullable: true}
        completed_at: {type: string, nullable: true}
        created_at: {type: string}
        updated_at: {type: string}
    ActorBrief:
      type: object
      properties:
        id: {type: integer}
        name: {type: string}
        type: {type: string, enum: [human, agent]}
    Event:
      type: object
      properties:
        id: {type: integer}
        type: {type: string, examples: [task.created, task.status_changed, comment.added, task.assigned, dependency.added]}
        task_id: {type: integer, nullable: true}
        actor_id: {type: integer}
        payload: {type: object}
        created_at: {type: string}
    Error:
      type: object
      properties:
        error:
          type: object
          properties:
            code: {type: string}
            message: {type: string}
            details: {type: object}
