{
  "openapi": "3.1.0",
  "info": {
    "title": "TerraBrains Public API",
    "version": "1.0.0",
    "description": "The versioned, workspace-scoped public REST API for TerraBrains — the operating system for geotechnical engineering.\n\n**Authentication.** Every request must be authenticated. Either send the browser session cookie (the web app), or `Authorization: Bearer <supabase access token>` — the same token the mobile app uses. Unauthenticated requests receive `401 {\"error\":\"unauthenticated\"}`.\n\n**API tokens.** A workspace owner or admin mints a token in Settings → API tokens (`Authorization: Bearer tb_…`). A token belongs to one workspace and carries scopes; it is accepted ONLY by the operations whose `security` lists `apiToken`, and only with the scope that operation names: `projects:read` (listProjects), `boreholes:read` (listBoreholes), `analysis:run` (listAnalyses, runAnalysis). The save and saved-run operations need a signed-in user and refuse a token with `403 {\"error\":\"token_not_accepted\"}`. An invalid, expired or revoked token is `401 {\"error\":\"invalid_token\"}` (the three are deliberately indistinguishable); a token without the operation's scope is `403 {\"error\":\"insufficient_scope\"}`. With a token, `X-TerraBrains-Org` is optional and, if sent, must be the token's own workspace id (`403 token_org_mismatch` otherwise). Revocation and expiry take effect on the next request. A token also stops working (the same `401 invalid_token`) while the owner or admin who minted it is no longer an active owner/admin of the workspace, and when the workspace is closed. Repeated invalid tokens from one address are answered `429 {\"error\":\"too_many_failed_tokens\"}` with `Retry-After`; a valid token is still served.\n\n**Workspace scoping.** A caller with several workspaces names the target with the `X-TerraBrains-Org` header (workspace id or slug). With exactly one workspace, or the web app's active-workspace cookie set, the header may be omitted. An ambiguous request is refused with `409 {\"error\":\"workspace_ambiguous\"}`. A workspace the caller is not an active member of is refused with `403 {\"error\":\"not_a_member\"}`. Resources outside the resolved workspace are indistinguishable from resources that do not exist (`404`).\n\n**Rate awareness.** Every response carries `X-RateLimit-Limit` and `X-RateLimit-Reset`, and `X-RateLimit-Remaining` whenever the counter answered. The ceiling is 120 requests per 60 seconds per workspace per route class (reads, writes and analysis runs are separate classes; a workspace's tokens and users share one budget per class), enforced by a durable cross-instance counter. Over the ceiling the API returns `429 {\"error\":\"rate_limited\"}`. `X-RateLimit-Remaining` is the counter's own figure (limit minus requests counted in the current window) and `X-RateLimit-Reset` is the Unix time the window ends; a 429 also carries `Retry-After`. If the counter itself is unavailable the limiter fails OPEN for reads and writes — requests are served, `X-RateLimit-Limit` still advises the ceiling, and `X-RateLimit-Remaining` is omitted because it is not known. Analysis runs fail CLOSED instead: `503 {\"error\":\"rate_limit_unavailable\"}`, because compute is never served unmetered. Well-behaved clients should self-throttle on the headers regardless.\n\n**Errors.** Failures are always JSON: `{\"error\": \"<machine code>\", \"message\": \"<human sentence>\"}` with a real HTTP status. The API never answers a JSON request with an HTML redirect.",
    "contact": { "url": "https://terrabrains.ai" }
  },
  "servers": [{ "url": "https://terrabrains.ai", "description": "Production" }],
  "security": [{ "bearerAuth": [] }, { "cookieAuth": [] }],
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "description": "A Supabase access token for a signed-in TerraBrains user (the same token the mobile app uses)."
      },
      "cookieAuth": {
        "type": "apiKey",
        "in": "cookie",
        "name": "sb-access-token",
        "description": "The browser session cookie set by the web app."
      },
      "apiToken": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "tb_<48 hex>",
        "description": "A workspace API token minted by an owner/admin in Settings → API tokens. Accepted only by operations that list `apiToken` in their security, and only with the scope named in the operation description. Stored hashed (SHA-256); the secret is shown once at minting."
      }
    },
    "parameters": {
      "orgHeader": {
        "name": "X-TerraBrains-Org",
        "in": "header",
        "required": false,
        "description": "Workspace id or slug. Required when the caller belongs to several workspaces and has no active-workspace cookie.",
        "schema": { "type": "string" }
      },
      "limit": {
        "name": "limit",
        "in": "query",
        "required": false,
        "schema": { "type": "integer", "minimum": 1, "maximum": 100 },
        "description": "Page size. Out-of-range or absent values fall back to the documented default."
      }
    },
    "schemas": {
      "Error": {
        "type": "object",
        "required": ["error", "message"],
        "properties": {
          "error": { "type": "string", "description": "Machine-readable code, e.g. `unauthenticated`, `invalid_token`, `insufficient_scope`, `token_not_accepted`, `token_org_mismatch`, `not_a_member`, `workspace_ambiguous`, `project_not_found`, `rate_limited`." },
          "message": { "type": "string", "description": "A human sentence describing the failure." }
        }
      },
      "AnalysisType": {
        "type": "object",
        "required": ["slug", "title", "category", "spec", "addon", "api_runnable"],
        "properties": {
          "slug": { "type": "string", "example": "infinite-slope" },
          "title": { "type": "string", "example": "Infinite slope" },
          "category": { "type": "string", "enum": ["Site", "Shallow", "Deep", "Seismic", "Walls", "Improvement", "Pavement"] },
          "spec": { "type": "string", "description": "Governing standard(s) or method, as shown in the product." },
          "addon": {
            "type": ["string", "null"],
            "enum": ["pavement-suite", "advanced-fe-suite", "deep-foundations-suite", "deep-excavation-suite", null],
            "description": "The Store pack that unlocks this analysis, or null when it is in every plan's base catalogue."
          },
          "api_runnable": { "type": "boolean", "description": "True when POST /api/v1/analyses/{slug}/run computes this analysis (a config engine that is not a Store-pack engine)." }
        }
      },
      "Borehole": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "name": { "type": "string", "example": "BH-01" },
          "site_id": { "type": "string", "format": "uuid" },
          "status": { "type": "string" },
          "drilling_method": { "type": "string" },
          "planned_depth_m": { "type": ["number", "null"] },
          "actual_depth_m": { "type": ["number", "null"] },
          "elevation_m": { "type": ["number", "null"] },
          "groundwater_depth_m": { "type": ["number", "null"] },
          "position": {
            "type": ["object", "null"],
            "description": "WGS84 position, or null when no usable position is recorded (including the legacy 0°,0° placeholder).",
            "properties": { "lat": { "type": "number" }, "lng": { "type": "number" } }
          },
          "started_at": { "type": ["string", "null"], "format": "date-time" },
          "completed_at": { "type": ["string", "null"], "format": "date-time" },
          "created_at": { "type": "string", "format": "date-time" },
          "updated_at": { "type": "string", "format": "date-time" }
        }
      },
      "RunRequest": {
        "type": "object",
        "properties": {
          "inputs": {
            "type": "object",
            "description": "Field values keyed by the analysis's field keys (the same keys the product form uses). Numbers must be finite JSON numbers; select fields one of their option values; list and table fields arrays. Unknown keys are refused. Omitted fields take the form default and are listed in `defaulted`.",
            "additionalProperties": true
          }
        }
      },
      "RunResult": {
        "type": "object",
        "required": ["slug", "title", "inputs", "defaulted", "outputs", "summary", "saved"],
        "properties": {
          "slug": { "type": "string" },
          "title": { "type": "string" },
          "inputs": { "type": "object", "description": "The exact inputs the engine ran on (caller values + defaults)." },
          "defaulted": { "type": "array", "items": { "type": "string" }, "description": "Field keys the caller omitted, which took the form default." },
          "outputs": { "type": "object", "description": "The engine's full result object." },
          "summary": {
            "type": "array",
            "description": "The headline outputs the product's results rail shows, in order. `value` is null when the engine produced no value.",
            "items": {
              "type": "object",
              "properties": {
                "label": { "type": "string" },
                "unit": { "type": ["string", "null"] },
                "value": { "type": ["number", "string", "boolean", "null"] }
              }
            }
          },
          "warnings": { "type": "array", "items": { "type": "string" } },
          "references": { "type": "array", "items": { "type": "string" } },
          "engine_version": { "type": ["string", "null"], "description": "Build ref of the server that computed it, or null when unknown." },
          "execution_ms": { "type": "number", "description": "Measured engine wall time for this request." },
          "saved": { "type": "boolean", "const": false, "description": "Runs through this endpoint are never saved." }
        }
      },
      "Project": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "reference": { "type": "string", "example": "PRJ-2026-004" },
          "name": { "type": "string" },
          "client_name": { "type": ["string", "null"] },
          "status": { "type": "string" },
          "started_at": { "type": ["string", "null"], "format": "date-time" },
          "due_at": { "type": ["string", "null"], "format": "date-time" },
          "is_demo": { "type": "boolean", "description": "True for the sample project — sample data is disclosed wherever it surfaces." },
          "created_at": { "type": "string", "format": "date-time" }
        }
      },
      "AnalysisRun": {
        "type": "object",
        "description": "A saved analysis run: the full input echo, outputs, and provenance. A signed report cites this row byte-for-byte.",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "analysis_kind": { "type": "string", "example": "infinite-slope" },
          "label": { "type": ["string", "null"] },
          "inputs": { "type": "object", "description": "The complete input echo as received." },
          "outputs": { "type": "object", "description": "The server-authorised outputs (never the caller's claim)." },
          "engine_version": { "type": ["string", "null"], "description": "Build ref of the engine that produced the result." },
          "design_code": { "type": ["string", "null"], "example": "IS 456" },
          "result_status": { "type": ["string", "null"], "enum": ["ok", "warning", null] },
          "warnings": { "description": "Warning strings, when result_status is `warning`." },
          "created_by": { "type": ["string", "null"], "format": "uuid" },
          "created_at": { "type": "string", "format": "date-time" }
        }
      },
      "RunSubmission": {
        "type": "object",
        "required": ["kind", "inputs", "outputs"],
        "properties": {
          "kind": { "type": "string", "description": "An analysis slug from GET /api/v1/analyses." },
          "label": { "type": "string", "maxLength": 200 },
          "inputs": { "type": "object", "description": "The full input echo (≤ 512 KB)." },
          "outputs": { "type": "object", "description": "The computed outputs (≤ 512 KB). The server re-derives/authorises base-engine outputs before storing; premium engines require result_token." },
          "design_code": { "type": "string", "maxLength": 120 },
          "warnings": { "type": "array", "items": { "type": "string" }, "maxItems": 50 },
          "result_token": { "type": "string", "description": "Premium engines only: the token /api/run-premium issued with the result. Without it a premium save is refused." }
        }
      }
    },
    "responses": {
      "Unauthenticated": {
        "description": "Missing/expired session or access token, or an invalid, expired or revoked API token (`invalid_token`).",
        "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
      },
      "Forbidden": {
        "description": "Authenticated, but the workspace, role, plan or API token scope does not allow this (e.g. `insufficient_scope`, `token_not_accepted`).",
        "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
      },
      "NotFound": {
        "description": "No such resource in this workspace (or it does not exist — the two are indistinguishable).",
        "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
      },
      "RateLimited": {
        "description": "Over the workspace's request ceiling. See X-RateLimit-Reset.",
        "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
      }
    }
  },
  "paths": {
    "/api/v1/analyses": {
      "get": {
        "operationId": "listAnalyses",
        "summary": "List the analysis catalogue",
        "description": "Every analysis type the workspace can open in the product, with the Store pack that gates each one (`null` = base catalogue, every plan) and whether runAnalysis computes it. API token scope: `analysis:run`.",
        "security": [{ "apiToken": [] }, { "bearerAuth": [] }, { "cookieAuth": [] }],
        "parameters": [{ "$ref": "#/components/parameters/orgHeader" }],
        "responses": {
          "200": {
            "description": "The catalogue.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": ["analyses"],
                  "properties": { "analyses": { "type": "array", "items": { "$ref": "#/components/schemas/AnalysisType" } } }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "409": { "description": "Workspace ambiguous — send X-TerraBrains-Org.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/api/v1/projects": {
      "get": {
        "operationId": "listProjects",
        "summary": "List the workspace's projects",
        "description": "Newest first, soft-deleted excluded, capped at `limit`. API token scope: `projects:read`.",
        "security": [{ "apiToken": [] }, { "bearerAuth": [] }, { "cookieAuth": [] }],
        "parameters": [
          { "$ref": "#/components/parameters/orgHeader" },
          { "$ref": "#/components/parameters/limit", "description": "Page size (default 50, max 100)." }
        ],
        "responses": {
          "200": {
            "description": "The project list.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": ["projects"],
                  "properties": {
                    "projects": { "type": "array", "items": { "$ref": "#/components/schemas/Project" } },
                    "limit": { "type": "integer" }
                  }
                }
              }
            }
          },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/api/v1/projects/{projectId}/boreholes": {
      "get": {
        "operationId": "listBoreholes",
        "summary": "List a project's boreholes",
        "description": "Oldest first. A project outside the workspace, soft-deleted or unknown is 404. `truncated` is true when more boreholes exist than `limit`. API token scope: `boreholes:read`.",
        "security": [{ "apiToken": [] }, { "bearerAuth": [] }, { "cookieAuth": [] }],
        "parameters": [
          { "name": "projectId", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } },
          { "$ref": "#/components/parameters/orgHeader" },
          { "name": "limit", "in": "query", "required": false, "schema": { "type": "integer", "minimum": 1, "maximum": 500 }, "description": "Page size (default 200, max 500). Out-of-range or absent values fall back to the default." }
        ],
        "responses": {
          "200": {
            "description": "The borehole list.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": ["boreholes", "project_id", "limit", "truncated"],
                  "properties": {
                    "boreholes": { "type": "array", "items": { "$ref": "#/components/schemas/Borehole" } },
                    "project_id": { "type": "string", "format": "uuid" },
                    "limit": { "type": "integer" },
                    "truncated": { "type": "boolean" }
                  }
                }
              }
            }
          },
          "400": { "description": "Malformed project id.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/api/v1/analyses/{slug}/run": {
      "post": {
        "operationId": "runAnalysis",
        "summary": "Run one config analysis",
        "description": "Computes the analysis with the same guarded engine the product runs and returns the result. Nothing is saved. Only entries with `api_runnable: true` in listAnalyses can be run: bespoke-form analyses are 400 `not_runnable_via_api`, Store-pack analyses 403 `premium_not_available`. The workspace's plan must include the analysis (403 `not_entitled`). Inputs are validated against the analysis's declared fields (400 `invalid_inputs` with an `issues` list). An engine refusal of the inputs is 422 `compute_refused` with the engine's `errors`. The computation runs on a separate worker with a 20-second limit: past it the run is stopped and answered 422 `compute_timeout`. At most 2 runs per workspace compute at once (429 `run_in_progress`, `Retry-After: 2`); a saturated service is 503 `compute_busy` with `Retry-After`. API token scope: `analysis:run`.",
        "security": [{ "apiToken": [] }, { "bearerAuth": [] }, { "cookieAuth": [] }],
        "parameters": [
          { "name": "slug", "in": "path", "required": true, "schema": { "type": "string" }, "example": "infinite-slope" },
          { "$ref": "#/components/parameters/orgHeader" }
        ],
        "requestBody": {
          "required": false,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RunRequest" } } }
        },
        "responses": {
          "200": { "description": "Computed.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RunResult" } } } },
          "400": { "description": "Malformed JSON, invalid inputs, or an analysis that is not runnable through the API.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "413": { "description": "Request body over 256 KB.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "422": { "description": "The engine refused these inputs (`compute_refused`, with `errors`), or the computation exceeded its 20-second limit (`compute_timeout`).", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" },
          "503": { "description": "The compute meter is unavailable (`rate_limit_unavailable`; runs are paused rather than served unmetered), the compute service is saturated (`compute_busy`) or unavailable (`compute_unavailable`). Retry after `Retry-After`.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/api/v1/projects/{projectId}/runs": {
      "get": {
        "operationId": "listRuns",
        "summary": "List a project's saved analysis runs",
        "description": "Newest first. Filter with `kind`, page with `before` (keyset on `created_at`).",
        "parameters": [
          { "name": "projectId", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } },
          { "$ref": "#/components/parameters/orgHeader" },
          { "$ref": "#/components/parameters/limit", "description": "Page size (default 25, max 100)." },
          { "name": "kind", "in": "query", "required": false, "schema": { "type": "string" }, "description": "Filter to one analysis slug." },
          { "name": "before", "in": "query", "required": false, "schema": { "type": "string", "format": "date-time" }, "description": "Only runs created before this timestamp (keyset paging)." }
        ],
        "responses": {
          "200": {
            "description": "The run list.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": ["runs"],
                  "properties": {
                    "runs": { "type": "array", "items": { "$ref": "#/components/schemas/AnalysisRun" } },
                    "limit": { "type": "integer" },
                    "project_id": { "type": "string", "format": "uuid" }
                  }
                }
              }
            }
          },
          "400": { "description": "Malformed id or paging parameter.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      },
      "post": {
        "operationId": "submitRun",
        "summary": "Submit (save) an analysis run",
        "description": "Saves a computed run to the project record. The caller's workspace role must hold `analysis:write`; the plan must include the analysis; premium engines require the `result_token` issued by the product's compute route. Stored outputs are server-authorised, never the caller's claim. Run-only analyses (differential-settlement, fe-slope-3d, slope-3d-dem) are refused — the product never records them.",
        "parameters": [
          { "name": "projectId", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } },
          { "$ref": "#/components/parameters/orgHeader" }
        ],
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RunSubmission" } } }
        },
        "responses": {
          "201": {
            "description": "Saved.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": ["id", "project_id", "kind"],
                  "properties": {
                    "id": { "type": "string", "format": "uuid" },
                    "project_id": { "type": "string", "format": "uuid" },
                    "kind": { "type": "string" }
                  }
                }
              }
            }
          },
          "400": { "description": "Malformed body, run-only analysis, or the save was refused.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "413": { "description": "inputs/outputs over 512 KB.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/api/v1/runs/{runId}": {
      "get": {
        "operationId": "getRun",
        "summary": "Get one saved analysis run",
        "description": "The full record, byte-for-byte: input echo, outputs, engine version, design code, status, warnings.",
        "parameters": [
          { "name": "runId", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } },
          { "$ref": "#/components/parameters/orgHeader" }
        ],
        "responses": {
          "200": {
            "description": "The run.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": ["run"],
                  "properties": { "run": { "$ref": "#/components/schemas/AnalysisRun" } }
                }
              }
            }
          },
          "400": { "description": "Malformed id.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    }
  }
}
