openapi: 3.1.0
info:
  title: Asurion Command Center API
  version: 0.1.0
  description: "Asurion Command Center API. Auto-exported from FastAPI's /openapi.json\
    \ by scripts/export-openapi.py. **Do not edit by hand** \u2014 re-run `make export-openapi`\
    \ whenever a route changes. See docs/architecture.md and docs/adrs/ for context."
paths:
  /v1/widgets/clarify:
    post:
      tags:
      - widgets
      summary: Start an Add Widget Clarifier session (SSE)
      description: 'Open a new Clarifier session and stream its progress via SSE.


        Event names match the Spine Clarifier: ``stage`` | ``gaps`` |

        ``questions`` | ``result`` | ``error``. Per [ADR-005](docs/adrs/ADR-005.md);

        fail-loud per [ADR-008](docs/adrs/ADR-008.md). See

        [docs/widget-builder.md](docs/widget-builder.md) for the full SSE

        contract.'
      operationId: clarify_start_v1_widgets_clarify_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/StartBody'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /v1/widgets/clarify/respond:
    post:
      tags:
      - widgets
      summary: Resume a Clarifier session with answers (SSE)
      description: "Answer the Clarifier's questions or abandon the session.\n\nWith\
        \ the metric matcher in place, real Bedrock often fills every\nrequired field\
        \ on the first pass and the graph interrupts with zero\nquestions \u2014 the\
        \ frontend resumes with ``answers: []`` to advance\npast the HITL gate. ``abandon=true``\
        \ cancels the session."
      operationId: clarify_respond_v1_widgets_clarify_respond_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RespondBody'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /v1/widgets:
    get:
      tags:
      - widgets
      summary: List rail widgets for the current owner
      description: 'Return up to 24 most-recent widgets currently placed on the rail.


        Dismissed widgets are excluded. Newly-created widgets surface here

        immediately and are appended to the layout doc on the next GET.'
      operationId: list_widgets_v1_widgets_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                items:
                  $ref: '#/components/schemas/StoredWidget'
                type: array
                title: Response List Widgets V1 Widgets Get
    post:
      tags:
      - widgets
      summary: Persist a widget to the dashboard rail
      description: 'Persist a Clarifier-built widget.


        Atomically validates ``spec.metric`` and promotes one-off metrics into

        ``metrics_catalog`` ([ADR-007](docs/adrs/ADR-007.md)). For the

        ``custom`` variant ([ADR-006](docs/adrs/ADR-006.md)) also runs the

        static-check gate (zero ``import`` statements, sealed scope) before

        insert. Returns the stored row including the resolved ``metric_id``.'
      operationId: persist_widget_v1_widgets_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PersistBody'
        required: true
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/StoredWidget'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /v1/widgets/{widget_id}:
    patch:
      tags:
      - widgets
      summary: Move a widget between rail and dismissed
      description: 'Update widget placement (``rail`` | ``dismissed``).


        Returns 404 when the widget id is unknown.'
      operationId: update_placement_v1_widgets__widget_id__patch
      parameters:
      - name: widget_id
        in: path
        required: true
        schema:
          type: string
          title: Widget Id
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PlacementUpdateBody'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: object
                additionalProperties:
                  type: string
                title: Response Update Placement V1 Widgets  Widget Id  Patch
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /v1/widgets/{widget_id}/data:
    post:
      tags:
      - widgets
      summary: Resolve a widget's live data via per-metric routing (Prompt 4)
      description: "Resolve a widget to live data.\n\nSee [`docs/sql-generator.md`](../../docs/sql-generator.md)\
        \ \xA7 *Per-widget\ndata resolver* for the routing dispatch + graceful-degradation\n\
        contract. The resolver delegates Databricks-routed metrics to\n``POST /v1/widgets/sql/generate``\
        \ (Prompt 3) under the hood; the\nresponse carries ``generated_sql`` so the\
        \ dashboard can surface it\nin the SpecJsonView (Prompt 5).\n\nLive-data outages\
        \ (Databricks unavailable, Bedrock unavailable,\nsafety violation) return\
        \ **200 with ``live_data_unavailable=true``**\nand the widget's baked-in ``mock_data``\
        \ \u2014 structurally distinct\nfrom MockLlm substitution per [ADR-008](../../docs/adrs/ADR-008.md).\n\
        Caller errors (unknown widget, free-text request) still return\nRFC 7807 4xx."
      operationId: resolve_data_endpoint_v1_widgets__widget_id__data_post
      parameters:
      - name: widget_id
        in: path
        required: true
        schema:
          type: string
          title: Widget Id
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DataResolverBody'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DataResolverResponse'
        '404':
          description: Widget not found.
          content:
            application/problem+json: {}
        '422':
          description: "Caller error \u2014 metric not found, metric not Databricks-routed\
            \ (when an explicit override was passed), or free-text rejected. Warehouse\
            \ outages are NOT 4xx \u2014 those return 200 with ``live_data_unavailable=true``."
          content:
            application/problem+json: {}
        '503':
          description: "Defensive catch-all for resolver bugs. Live-data failures\
            \ use 200 + live_data_unavailable=true, NOT 503 (PRD v2.1 \xA7C.10 #10)."
          content:
            application/problem+json: {}
  /v1/widgets/sql/generate:
    post:
      tags:
      - sql-gen
      summary: Generate Databricks SQL for a catalog-anchored metric (Prompt 3)
      description: "Generate Databricks SQL anchored to a ``metrics_catalog`` metric.\n\
        \nSee PRD v2.1 \xA7C.4.2 for the request flow and \xA7C.4.3 for the safety\n\
        contract. The handler converts every typed exception into an\nRFC 7807 response\
        \ \u2014 the success path returns ``GenerateSqlResponse``."
      operationId: generate_sql_endpoint_v1_widgets_sql_generate_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GenerateSqlRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GenerateSqlResponse'
        '404':
          description: Metric not found in metrics_catalog.
          content:
            application/problem+json: {}
        '422':
          description: Request rejected by the route or safety layer. ``kind`` is
            ``free_text_rejected`` | ``metric_not_databricks`` | ``safety_violation``.
          content:
            application/problem+json: {}
        '503':
          description: Bedrock or Databricks unavailable. ``kind`` is ``bedrock_unavailable``
            | ``databricks_unavailable`` | ``databricks_auth_error`` | ``databricks_timeout``
            | ``databricks_query_error``.
          content:
            application/problem+json: {}
  /v1/metrics:
    get:
      tags:
      - metrics
      summary: List all catalog metrics
      description: "Return every metric in ``metrics_catalog`` (10 v1 + 3 Databricks\
        \ today).\n\nSorted by creation time. Includes lineage columns\n(``source_schema``\
        \ / ``source_table`` / ``source_query``) populated for the\nPart C metrics\
        \ \u2014 see [docs/sql-generator.md \xA7 Lineage columns](docs/sql-generator.md)."
      operationId: list_metrics_v1_metrics_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                items:
                  $ref: '#/components/schemas/CatalogMetric'
                type: array
                title: Response List Metrics V1 Metrics Get
    post:
      tags:
      - metrics
      summary: Create a new catalog metric
      description: 'Insert a new ``MetricDefinition`` into the catalog.


        Rejects with 409 when ``body.name`` already exists. Atomic with the

        ``upsert_metric_from_definition`` path used by ``POST /v1/widgets``

        so one-off metrics introduced via the Clarifier always land in the

        catalog. See [ADR-007](docs/adrs/ADR-007.md).'
      operationId: create_metric_v1_metrics_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateMetricBody'
        required: true
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CatalogMetric'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /v1/metrics/{metric_id}:
    get:
      tags:
      - metrics
      summary: Fetch a single metric by id
      description: Return the catalog row for ``metric_id``. 404 if unknown.
      operationId: get_metric_v1_metrics__metric_id__get
      parameters:
      - name: metric_id
        in: path
        required: true
        schema:
          type: string
          title: Metric Id
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CatalogMetric'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /v1/dashboard/layout:
    get:
      tags:
      - dashboard
      summary: Load the dashboard layout for the current owner
      description: 'Return the persisted layout doc + lenient-backfilled missing IDs.


        The single demo user ``jane.smith@asurion.com`` is the only owner today.

        Newly-added canonical IDs (sections, KPI tiles, panels, widget UUIDs)

        are appended at the tail in canonical order so saved layouts never

        silently drop new surfaces. See [ADR-009](docs/adrs/ADR-009.md).'
      operationId: get_layout_v1_dashboard_layout_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DashboardLayoutDoc'
    put:
      tags:
      - dashboard
      summary: Save the dashboard layout doc
      description: 'Persist a reordered layout doc.


        Strict validation: rejects unknown section/panel/KPI IDs with 422.

        Lenient backfill: shorter-than-canonical lists are accepted and

        backfilled at the tail. See [ADR-009](docs/adrs/ADR-009.md).'
      operationId: put_layout_v1_dashboard_layout_put
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DashboardLayoutDoc'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DashboardLayoutDoc'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /health:
    get:
      tags:
      - meta
      summary: Liveness probe
      description: "Return ``{\"status\": \"ok\"}`` if the api process is up.\n\n\
        Does not exercise the database, Redis, or Bedrock \u2014 use the\n``/v1/databricks/health``\
        \ endpoint for the deeper Databricks probe and\nthe route-specific endpoints\
        \ for everything else."
      operationId: health_health_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                additionalProperties:
                  type: string
                type: object
                title: Response Health Health Get
  /v1/databricks/health:
    get:
      tags:
      - meta
      summary: Databricks SQL Warehouse smoke test
      description: "Smoke-test the Databricks SQL Warehouse connection.\n\nReturns\
        \ 200 with `{status, rows_sampled, latency_ms, catalog, schema,\nauth_method,\
        \ table}` on success. On any `DatabricksError`, returns 503\nwith `Content-Type:\
        \ application/problem+json` (RFC 7807) and a\nstructured body \u2014 never\
        \ a 500, never a stack trace.\n\nThis mirrors ADR-008's fail-loud discipline\
        \ into the Databricks path:\nthe response shape makes the failure category\
        \ explicit\n(databricks_unavailable / databricks_auth_error / databricks_timeout\
        \ /\ndatabricks_query_error) so the operator gets actionable copy."
      operationId: databricks_health_v1_databricks_health_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /v1/demo/manifest:
    get:
      tags:
      - demo
      summary: IDs the seed pinned for the demo customer/device
      description: "Return stable IDs for the demo customer and device.\n\nUseful\
        \ when constructing curl scripts for the demo arc \u2014 the seeder\nuses\
        \ fixed UUIDs so external scripts can reference them without\nre-querying."
      operationId: demo_manifest_v1_demo_manifest_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                additionalProperties:
                  type: string
                type: object
                title: Response Demo Manifest V1 Demo Manifest Get
  /v1/events:
    post:
      tags:
      - events
      summary: Ingest an event envelope
      description: 'Persist an event envelope and trigger any downstream aggregations.


        The envelope is the unit of ingest in v1; Part B ([ADR-V2-001](docs/adrs/ADR-V2-001.md))

        routes this through Kafka. Today the api writes directly to Postgres

        and publishes to ``pubsub:dashboard``.'
      operationId: post_event_v1_events_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/EventEnvelope'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: object
                title: Response Post Event V1 Events Post
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /v1/dashboard/state:
    get:
      tags:
      - dashboard
      summary: Snapshot of the executive dashboard
      description: "Return the full dashboard payload \u2014 KPI tiles, top issues,\
        \ alerts,\nrecommendations, customer/device focus, builder mode, and the resolved\n\
        layout doc per [ADR-009](docs/adrs/ADR-009.md)."
      operationId: get_dashboard_state_v1_dashboard_state_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: object
                title: Response Get Dashboard State V1 Dashboard State Get
  /v1/issue-sessions/{issue_session_id}:
    get:
      tags:
      - issue-sessions
      summary: Issue session detail
      description: 'Return the timeline + decisions + outcomes for a single issue
        session.


        Returns 404 when the session id is unknown.'
      operationId: get_issue_session_v1_issue_sessions__issue_session_id__get
      parameters:
      - name: issue_session_id
        in: path
        required: true
        schema:
          type: string
          title: Issue Session Id
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: object
                title: Response Get Issue Session V1 Issue Sessions  Issue Session
                  Id  Get
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /v1/decisions/next-best-action:
    post:
      tags:
      - decisions
      summary: Recommend the next best action for an issue session
      description: 'Run the deterministic scorer + Bedrock rationale path for the

        given session. Falls back to a templated rationale on Bedrock failure

        per [ADR-003](docs/adrs/ADR-003.md).'
      operationId: post_decision_v1_decisions_next_best_action_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DecisionRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: object
                title: Response Post Decision V1 Decisions Next Best Action Post
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /v1/feedback/outcome:
    post:
      tags:
      - feedback
      summary: Record approval/decline of a recommendation
      description: 'Record the outcome of a recommendation (approved / declined /
        executed).


        Emits a ``recommendation.approved`` event for downstream aggregation.'
      operationId: post_outcome_v1_feedback_outcome_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OutcomeRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: object
                title: Response Post Outcome V1 Feedback Outcome Post
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /v1/dashboard/select:
    post:
      tags:
      - dashboard
      summary: Select an issue session as the dashboard focus
      description: Set the focused issue session for the dashboard. Pass ``null``
        to clear.
      operationId: post_select_v1_dashboard_select_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SelectRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                additionalProperties:
                  anyOf:
                  - type: string
                  - type: 'null'
                type: object
                title: Response Post Select V1 Dashboard Select Post
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /v1/admin/reset-demo:
    post:
      tags:
      - admin
      summary: Reset synthetic demo data
      description: "Truncate widgets + issue sessions and re-run the seed.\n\nRequires\
        \ the api to be running. If the boot validator blocks startup,\nuse the direct-SQL\
        \ escape hatch documented in\n[docs/lessons-learned.md \xA7 demo-reset chicken-and-egg](docs/lessons-learned.md)."
      operationId: admin_reset_v1_admin_reset_demo_post
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                additionalProperties:
                  type: string
                type: object
                title: Response Admin Reset V1 Admin Reset Demo Post
components:
  schemas:
    CatalogMetric:
      properties:
        metric_id:
          type: string
          title: Metric Id
          description: UUID assigned by Postgres.
        name:
          type: string
          maxLength: 80
          minLength: 2
          pattern: ^[a-z][a-z0-9_]+$
          title: Name
          description: snake_case identifier (e.g. 'cost_avoided_mtd').
        label:
          type: string
          maxLength: 80
          minLength: 2
          title: Label
          description: Human label (e.g. 'Cost avoided MTD').
        definition:
          type: string
          maxLength: 400
          minLength: 10
          title: Definition
          description: "Plain-English answer to 'what does this metric measure?'.\
            \ Surfaced in the MetricInfoBadge popover; this is the single most important\
            \ research outcome \u2014 every widget answers this question."
        formula:
          type: string
          maxLength: 240
          minLength: 2
          title: Formula
          description: Compact pseudo-SQL the engineer/analyst can read at a glance
            (e.g. 'SUM(outcomes.cost_avoided) WHERE recorded_at >= MTD'). Holistics-style
            readable formula, not executable SQL.
        entity:
          type: string
          enum:
          - issue_sessions
          - outcomes
          - claims
          - devices
          - alerts
          - operations_context
          - ai_recommendations
          - events
          - ev_claim
          - ev_product_catalog
          title: Entity
          description: Source domain entity in db/init.sql.
        unit:
          anyOf:
          - type: string
            enum:
            - count
            - percent
            - currency
            - minutes
            - rating
            - ratio
          - type: 'null'
          title: Unit
          description: Unit of the resulting number; drives KpiTile's value_format.
        default_filter:
          type: object
          title: Default Filter
          description: 'Default scoping filter (e.g. {''window'': ''MTD''} or {''status'':
            ''open''}). Mirrors metrics_catalog.default_filter; the Clarifier''s time_window
            question writes here.'
        default_refresh_seconds:
          type: integer
          maximum: 3600.0
          minimum: 5.0
          title: Default Refresh Seconds
          default: 60
        owner:
          type: string
          maxLength: 120
          minLength: 3
          title: Owner
          default: jane.smith@asurion.com
        source_schema:
          anyOf:
          - type: string
            maxLength: 80
          - type: 'null'
          title: Source Schema
          description: Warehouse schema, e.g. 'l3_asurion'. NULL for synthetic Postgres
            metrics.
        source_table:
          anyOf:
          - type: string
            maxLength: 120
          - type: 'null'
          title: Source Table
          description: Bare table name, e.g. 'ev_claim' or 'issue_sessions'.
        source_query:
          anyOf:
          - type: string
            maxLength: 4000
          - type: 'null'
          title: Source Query
          description: Parameterised executable SQL with {time_window_start}, {dimensions},
            {filters} placeholders. Only databricks-routed metrics need this; Postgres
            metrics leave it None and the data resolver hits the v1 fast path.
        last_validated_at:
          anyOf:
          - type: string
          - type: 'null'
          title: Last Validated At
          description: ISO-8601 timestamp of the last successful schema-validation
            run.
        validation_status:
          type: string
          enum:
          - valid
          - drift_detected
          - unknown
          title: Validation Status
          default: valid
        governance_status:
          type: string
          enum:
          - approved
          - pending
          - deprecated
          title: Governance Status
          default: approved
        approved_by:
          anyOf:
          - type: string
            maxLength: 120
          - type: 'null'
          title: Approved By
        version:
          type: integer
          minimum: 1.0
          title: Version
          default: 1
        created_at:
          type: string
          title: Created At
        updated_at:
          type: string
          title: Updated At
      type: object
      required:
      - metric_id
      - name
      - label
      - definition
      - formula
      - entity
      - created_at
      - updated_at
      title: CatalogMetric
      description: 'A row in metrics_catalog. Superset of MetricDefinition.


        The metric_id is required (DB-assigned); version + timestamps are

        DB-managed and surfaced for the catalog browser UI.'
    CheckResult:
      properties:
        kind:
          type: string
          title: Kind
          description: "Stable rule identifier \u2014 one of: single_select, non_allowlisted_table,\
            \ limit_injected, limit_too_high, forbidden_construct, parse_error."
        passed:
          type: boolean
          title: Passed
        message:
          type: string
          title: Message
          description: Human-readable detail.
          default: ''
      type: object
      required:
      - kind
      - passed
      title: CheckResult
      description: "One row of the safety report \u2014 one rule, pass or fail.\n\n\
        ``kind`` is the stable identifier the route layer surfaces in the\nRFC 7807\
        \ problem body. ``message`` is a human-readable explanation\nfor logs / Swagger\
        \ / the eventual SourceBadge tooltip."
    CreateMetricBody:
      properties:
        name:
          type: string
          maxLength: 80
          minLength: 2
          pattern: ^[a-z][a-z0-9_]+$
          title: Name
        label:
          type: string
          maxLength: 80
          minLength: 2
          title: Label
        definition:
          type: string
          maxLength: 400
          minLength: 10
          title: Definition
        formula:
          type: string
          maxLength: 240
          minLength: 2
          title: Formula
        entity:
          type: string
          enum:
          - issue_sessions
          - outcomes
          - claims
          - devices
          - alerts
          - operations_context
          - ai_recommendations
          - events
          - ev_claim
          - ev_product_catalog
          title: Entity
        unit:
          anyOf:
          - type: string
            enum:
            - count
            - percent
            - currency
            - minutes
            - rating
            - ratio
          - type: 'null'
          title: Unit
        default_filter:
          type: object
          title: Default Filter
        default_refresh_seconds:
          type: integer
          maximum: 3600.0
          minimum: 5.0
          title: Default Refresh Seconds
          default: 60
        owner:
          type: string
          maxLength: 120
          minLength: 3
          title: Owner
          default: jane.smith@asurion.com
        source_schema:
          anyOf:
          - type: string
            maxLength: 80
          - type: 'null'
          title: Source Schema
        source_table:
          anyOf:
          - type: string
            maxLength: 120
          - type: 'null'
          title: Source Table
        source_query:
          anyOf:
          - type: string
            maxLength: 4000
          - type: 'null'
          title: Source Query
        validation_status:
          type: string
          enum:
          - valid
          - drift_detected
          - unknown
          title: Validation Status
          default: valid
        governance_status:
          type: string
          enum:
          - approved
          - pending
          - deprecated
          title: Governance Status
          default: approved
        approved_by:
          anyOf:
          - type: string
            maxLength: 120
          - type: 'null'
          title: Approved By
      type: object
      required:
      - name
      - label
      - definition
      - formula
      - entity
      title: CreateMetricBody
      description: "POST /v1/metrics request \u2014 like MetricDefinition but never\
        \ carries id/version."
    DashboardLayoutDoc:
      properties:
        version:
          type: integer
          title: Version
          default: 1
        sections:
          items:
            type: string
          type: array
          title: Sections
        kpi_strip:
          items:
            type: string
          type: array
          title: Kpi Strip
        heatmap_row:
          items:
            type: string
          type: array
          title: Heatmap Row
        detail_row:
          items:
            type: string
          type: array
          title: Detail Row
        my_widgets:
          items:
            type: string
          type: array
          title: My Widgets
      type: object
      title: DashboardLayoutDoc
      description: 'The on-the-wire layout envelope.


        The frontend posts the full doc on every reorder; the server validates,

        backfills missing canonical IDs at the tail, rejects unknown ones with

        422, and round-trips the same shape back from GET.'
    DataIntent:
      properties:
        entity:
          type: string
          title: Entity
          description: Domain entity, e.g. 'issue_sessions', 'outcomes', 'devices'.
        metric:
          type: string
          title: Metric
          description: Aggregated measure, e.g. 'count', 'avg(cost_avoided)'.
        dimensions:
          items:
            type: string
          type: array
          title: Dimensions
          description: Group-by dimensions, e.g. ['region', 'time_bucket_1d'].
        filters:
          type: object
          title: Filters
          description: 'Filter hints, e.g. {''status'': ''open'', ''window'': ''last_7_days''}.'
        refresh_seconds:
          type: integer
          maximum: 3600.0
          minimum: 5.0
          title: Refresh Seconds
          default: 30
        backend:
          type: string
          enum:
          - postgres
          - databricks
          - auto
          title: Backend
          description: Per-metric routing hint stamped by spec_synthesizer from config/metric_routing.yaml
            when a catalog metric resolves (Part C, ADR-PROTO-005). The data resolver
            still treats the routing yaml as authoritative; non-'auto' values only
            matter when a caller invokes the resolver with an inline data_intent but
            no metric_id (test path).
          default: auto
      type: object
      required:
      - entity
      - metric
      title: DataIntent
      description: What live signal the widget *would* bind to (deferred to the next
        story).
    DataResolverBody:
      properties:
        refresh:
          type: boolean
          title: Refresh
          description: Bypass the Redis cache for this call. The fresh result is still
            written back to the cache.
          default: false
        dry_run:
          type: boolean
          title: Dry Run
          description: 'Databricks-only: skip warehouse execution, return generated
            SQL + safety verdict only. Has no effect on the Postgres path.'
          default: false
      type: object
      title: DataResolverBody
      description: "Request body for ``POST /v1/widgets/{widget_id}/data``.\n\nBoth\
        \ flags default to False \u2014 the dashboard renderers (Prompt 5) hit\nthis\
        \ endpoint with an empty body. ``refresh=true`` is the manual\n'reload tile'\
        \ button; ``dry_run=true`` is the demo runbook\nacceptance #4 dry-run leg."
    DataResolverResponse:
      properties:
        widget_id:
          type: string
          title: Widget Id
        data:
          title: Data
          description: Rows or mock_data shape. Postgres / Databricks paths return
            list[dict]; graceful-degradation returns the widget's spec.mock_data as-is
            (could be a dict for kpi or a list for chart/table).
        schema:
          items:
            $ref: '#/components/schemas/DataSchemaColumn'
          type: array
          title: Schema
          description: Best-effort column descriptors.
        source:
          type: string
          title: Source
          description: 'Where the data came from. One of: postgres, databricks, databricks_template_only,
            databricks_unavailable, databricks_auth_error, databricks_timeout, databricks_query_error,
            bedrock_unavailable, safety_violation, mock_data, no_metric, postgres_unmapped,
            resolver_error.'
        cache_hit:
          type: boolean
          title: Cache Hit
          default: false
        freshness_seconds:
          type: integer
          title: Freshness Seconds
          default: 0
        live_data_unavailable:
          type: boolean
          title: Live Data Unavailable
          default: false
        generated_sql:
          anyOf:
          - type: string
          - type: 'null'
          title: Generated Sql
        executed:
          type: boolean
          title: Executed
          default: false
        rows_returned:
          type: integer
          title: Rows Returned
          default: 0
        execution_ms:
          type: integer
          title: Execution Ms
          default: 0
        explanation:
          type: string
          title: Explanation
          default: ''
        tables_used:
          items:
            type: string
          type: array
          title: Tables Used
        error_kind:
          anyOf:
          - type: string
          - type: 'null'
          title: Error Kind
        error_detail:
          anyOf:
          - type: string
          - type: 'null'
          title: Error Detail
        metric_name:
          anyOf:
          - type: string
          - type: 'null'
          title: Metric Name
        backend:
          anyOf:
          - type: string
          - type: 'null'
          title: Backend
          description: 'Routing backend that handled this request: postgres | databricks
            | None.'
      type: object
      required:
      - widget_id
      - source
      title: DataResolverResponse
      description: "The wire shape of POST /v1/widgets/{id}/data.\n\n``data`` is always\
        \ a list of row dicts. KPI widgets get a single\nrow like ``[{\"value\": 42}]``;\
        \ chart / table widgets get the rows\ndirectly. Graceful-degradation responses\
        \ set ``live_data_unavailable``\nand put the widget's baked-in ``spec.mock_data``\
        \ in ``data`` \u2014\nstructurally distinct from MockLlm substitution per\
        \ PRD \xA7C.10 #10."
    DataSchemaColumn:
      properties:
        name:
          type: string
          title: Name
        type:
          type: string
          title: Type
          description: 'One of: number | text | datetime.'
          default: text
      type: object
      required:
      - name
      title: DataSchemaColumn
      description: "One column descriptor in the response.schema list.\n\nBest-effort\
        \ \u2014 the resolver labels columns from the SQL's projection\nplus a coarse\
        \ type from the value's Python class. Frontend uses this\nto pick KPI numerics\
        \ out of a row, or to label table headers when\nthe renderer doesn't already\
        \ know."
    DecisionRequest:
      properties:
        issue_session_id:
          type: string
          title: Issue Session Id
        requested_by:
          type: string
          title: Requested By
          default: executive_dashboard
        channel:
          type: string
          title: Channel
          default: web
      type: object
      required:
      - issue_session_id
      title: DecisionRequest
    EventEnvelope:
      properties:
        event_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Event Id
        event_type:
          type: string
          title: Event Type
        event_time:
          type: string
          title: Event Time
        source:
          type: string
          title: Source
        trace_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Trace Id
        entities:
          type: object
          title: Entities
        payload:
          type: object
          title: Payload
      type: object
      required:
      - event_type
      - event_time
      - source
      title: EventEnvelope
    GenerateSqlRequest:
      properties:
        data_intent:
          $ref: '#/components/schemas/DataIntent'
          description: What live signal the widget binds to. The same shape used throughout
            the WidgetSpec family (see app.widgets.schemas).
        metric_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Metric Id
          description: "UUID or snake_case name of the metrics_catalog row to anchor\
            \ against. Required \u2014 ADR-PROTO-002 rejects free-text NL-to-SQL."
        dry_run:
          type: boolean
          title: Dry Run
          description: "When true, validate the generated SQL but do not execute it\
            \ against Databricks. The Bedrock call still happens \u2014 this is the\
            \ path used by the demo runbook and acceptance tests."
          default: false
      type: object
      required:
      - data_intent
      title: GenerateSqlRequest
      description: "Request body for ``POST /v1/widgets/sql/generate``.\n\n``metric_id``\
        \ accepts either a UUID string or a metric ``name``\n(snake_case identifier\
        \ from ``metrics_catalog``). This mirrors the\nflexibility the seeders ship\
        \ with \u2014 names are stable across\n``make demo-reset``, UUIDs are not."
    GenerateSqlResponse:
      properties:
        request_id:
          type: string
          title: Request Id
          description: UUID for cross-referencing the sql_generation_log row.
        metric_id:
          type: string
          title: Metric Id
          description: Resolved metric UUID.
        metric_name:
          type: string
          title: Metric Name
          description: Resolved metric snake_case name.
        generated_sql:
          type: string
          title: Generated Sql
          description: The SQL that was validated (post LIMIT injection if any).
        validation:
          $ref: '#/components/schemas/SafetyResult'
          description: Per-rule safety report.
        executed:
          type: boolean
          title: Executed
          description: False when dry_run=true; True when the warehouse ran the query.
        rows_returned:
          type: integer
          title: Rows Returned
          description: Result row count (0 when dry_run=true).
          default: 0
        execution_ms:
          type: integer
          title: Execution Ms
          description: Warehouse latency in ms (0 when dry_run=true).
          default: 0
        explanation:
          type: string
          title: Explanation
          description: LLM-supplied justification for the SQL.
          default: ''
        tables_used:
          items:
            type: string
          type: array
          title: Tables Used
          description: Lower-case FQNs the LLM declared. Cross-reference against the
            dictionary subset.
        source:
          type: string
          title: Source
          description: Always ``bedrock`` on the happy path. ``databricks_template_only``
            when the metric opted into template_fallback and Bedrock failed.
          default: bedrock
      type: object
      required:
      - request_id
      - metric_id
      - metric_name
      - generated_sql
      - validation
      - executed
      title: GenerateSqlResponse
      description: 'Successful response shape.


        Failure paths use RFC 7807 ``application/problem+json`` and never

        return this model (see ``_problem`` below).'
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    HumanResponse:
      properties:
        question_id:
          type: string
          title: Question Id
        answer:
          type: string
          title: Answer
        selected_option:
          anyOf:
          - type: string
          - type: 'null'
          title: Selected Option
      type: object
      required:
      - question_id
      - answer
      title: HumanResponse
    OutcomeRequest:
      properties:
        recommendation_id:
          type: string
          title: Recommendation Id
        action_taken:
          type: string
          title: Action Taken
        approved_by:
          type: string
          title: Approved By
      type: object
      required:
      - recommendation_id
      - action_taken
      - approved_by
      title: OutcomeRequest
    PersistBody:
      properties:
        raw_input:
          type: string
          title: Raw Input
        spec:
          type: object
          title: Spec
        thread_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Thread Id
      type: object
      required:
      - raw_input
      - spec
      title: PersistBody
    PlacementUpdateBody:
      properties:
        placement:
          type: string
          pattern: ^(rail|dismissed)$
          title: Placement
      type: object
      required:
      - placement
      title: PlacementUpdateBody
    RespondBody:
      properties:
        thread_id:
          type: string
          title: Thread Id
        answers:
          anyOf:
          - items:
              $ref: '#/components/schemas/HumanResponse'
            type: array
          - type: 'null'
          title: Answers
        abandon:
          type: boolean
          title: Abandon
          default: false
      type: object
      required:
      - thread_id
      title: RespondBody
    SafetyResult:
      properties:
        is_safe:
          type: boolean
          title: Is Safe
        checks:
          items:
            $ref: '#/components/schemas/CheckResult'
          type: array
          title: Checks
        modified_sql:
          anyOf:
          - type: string
          - type: 'null'
          title: Modified Sql
          description: If LIMIT was injected, the SQL with the injected clause; None
            when the input was already safe and unmodified.
      type: object
      required:
      - is_safe
      title: SafetyResult
      description: "Full safety verdict for one Bedrock-emitted SQL string.\n\n``modified_sql``\
        \ is set when LIMIT was injected; the orchestrator\nexecutes the modified\
        \ SQL (not the original). When ``is_safe`` is\nFalse, the failed check is\
        \ the *first* failing entry in ``checks`` \u2014\ncallers should report it\
        \ as the trigger for the rejection."
    SelectRequest:
      properties:
        issue_session_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Issue Session Id
      type: object
      title: SelectRequest
    StartBody:
      properties:
        raw_input:
          type: string
          maxLength: 600
          minLength: 2
          title: Raw Input
      type: object
      required:
      - raw_input
      title: StartBody
    StoredWidget:
      properties:
        widget_id:
          type: string
          title: Widget Id
        raw_input:
          type: string
          title: Raw Input
        spec:
          type: object
          title: Spec
        placement:
          type: string
          enum:
          - rail
          - dismissed
          title: Placement
        created_at:
          type: string
          title: Created At
        created_by:
          type: string
          title: Created By
      type: object
      required:
      - widget_id
      - raw_input
      - spec
      - placement
      - created_at
      - created_by
      title: StoredWidget
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
            - type: string
            - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
      - loc
      - msg
      - type
      title: ValidationError
