openapi: 3.1.0
info:
  title: Clarity API - Self-Learning Agent
  description: 'External API for the Clarity Self-Learning Agent (SLA) service.


    This API provides endpoints for:

    - **User Registration**: Onboard users and manage external ID mappings

    - **Session Management**: Track multi-step workflows with completion semantics

    - **Input Processing**: Submit various input types for belief extraction

    - **Self-Model Management**: CRUD operations for customizable self-models

    - **View Computation**: Compute temporal views (being, becoming, telos)

    - **Projections**: What-if analysis and goal-seeking projections

    - **Context Assembly**: Format self-model data for AI/LLM consumption


    ## Authentication


    All endpoints require an API key passed via the `X-API-Key` header.


    ```

    X-API-Key: your-api-key-here

    ```'
  version: 1.0.0
  contact:
    name: Epistemic Me
    url: https://epistemicme.ai
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT
paths:
  /health/:
    get:
      tags:
      - health
      summary: Health Check
      description: 'Lightweight health check — no blocking DB/embedder calls.


        Use GET /health/deep for comprehensive component checks.'
      operationId: health_check_health__get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                additionalProperties: true
                type: object
                title: Response Health Check Health  Get
  /health/deep:
    get:
      tags:
      - health
      summary: Deep Health Check
      description: Comprehensive health check with component probes (may be slow).
      operationId: deep_health_check_health_deep_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                additionalProperties: true
                type: object
                title: Response Deep Health Check Health Deep Get
  /health/stats:
    get:
      tags:
      - health
      summary: Get Stats
      description: Get comprehensive system and application statistics
      operationId: get_stats_health_stats_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                additionalProperties: true
                type: object
                title: Response Get Stats Health Stats Get
  /health/ready:
    get:
      tags:
      - health
      summary: Readiness Check
      description: Kubernetes-style readiness probe
      operationId: readiness_check_health_ready_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                additionalProperties: true
                type: object
                title: Response Readiness Check Health Ready Get
  /health/worker:
    get:
      tags:
      - health
      summary: Worker Health
      description: Check worker/queue health via Redis (Phase 1)
      operationId: worker_health_health_worker_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                additionalProperties: true
                type: object
                title: Response Worker Health Health Worker Get
  /health/metrics:
    get:
      tags:
      - health
      summary: Get Metrics
      description: Prometheus-style metrics endpoint
      operationId: get_metrics_health_metrics_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                additionalProperties: true
                type: object
                title: Response Get Metrics Health Metrics Get
  /episodes/:
    post:
      tags:
      - episodes
      summary: Create Episode
      description: Create a new episode
      operationId: create_episode_episodes__post
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Episode'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: object
                additionalProperties:
                  type: string
                title: Response Create Episode Episodes  Post
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    get:
      tags:
      - episodes
      summary: List Episodes
      description: List recent episodes
      operationId: list_episodes_episodes__get
      parameters:
      - name: user_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: User Id
      - name: pillar
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: Pillar
      - name: days
        in: query
        required: false
        schema:
          type: integer
          default: 7
          title: Days
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          default: 20
          title: Limit
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Episode'
                title: Response List Episodes Episodes  Get
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /episodes/{episode_id}:
    get:
      tags:
      - episodes
      summary: Get Episode
      description: Get a specific episode
      operationId: get_episode_episodes__episode_id__get
      parameters:
      - name: episode_id
        in: path
        required: true
        schema:
          type: string
          title: Episode Id
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Episode'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /beliefs/:
    post:
      tags:
      - beliefs
      summary: Create Belief
      description: Create or update a belief
      operationId: create_belief_beliefs__post
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Belief'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: object
                additionalProperties:
                  type: string
                title: Response Create Belief Beliefs  Post
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    get:
      tags:
      - beliefs
      summary: List Beliefs
      description: List beliefs with optional filters
      operationId: list_beliefs_beliefs__get
      parameters:
      - name: user_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: User Id
      - name: kind
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: Kind
      - name: status
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: Status
      - name: pillar
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: Pillar
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          default: 20
          title: Limit
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Belief'
                title: Response List Beliefs Beliefs  Get
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /beliefs/{belief_id}:
    get:
      tags:
      - beliefs
      summary: Get Belief
      description: Get a specific belief
      operationId: get_belief_beliefs__belief_id__get
      parameters:
      - name: belief_id
        in: path
        required: true
        schema:
          type: string
          title: Belief Id
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Belief'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /beliefs/{belief_id}/evidence:
    get:
      tags:
      - beliefs
      summary: Get Belief Evidence
      description: Get evidence episodes for a belief
      operationId: get_belief_evidence_beliefs__belief_id__evidence_get
      parameters:
      - name: belief_id
        in: path
        required: true
        schema:
          type: string
          title: Belief Id
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  additionalProperties: true
                title: Response Get Belief Evidence Beliefs  Belief Id  Evidence Get
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /context/:
    post:
      tags:
      - context
      summary: Assemble Context
      description: Assemble working memory context under budget
      operationId: assemble_context_context__post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ContextQuery'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorkingMemoryContext'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /context/search:
    post:
      tags:
      - context
      summary: Search Memories
      description: Search memories using text and vector similarity
      operationId: search_memories_context_search_post
      parameters:
      - name: query
        in: query
        required: true
        schema:
          type: string
          title: Query
      - name: user_id
        in: query
        required: false
        schema:
          type: string
          title: User Id
      - name: pillar
        in: query
        required: false
        schema:
          type: string
          title: Pillar
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          default: 10
          title: Limit
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: object
                additionalProperties: true
                title: Response Search Memories Context Search Post
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /prompts/prompts/{prompt_id}:
    get:
      tags:
      - prompts
      summary: Get Prompt Template
      description: Fetch a prompt template from the registry
      operationId: get_prompt_template_prompts_prompts__prompt_id__get
      parameters:
      - name: prompt_id
        in: path
        required: true
        schema:
          type: string
          title: Prompt Id
      - name: version
        in: query
        required: false
        schema:
          type: string
          default: latest
          title: Version
      - name: channel
        in: query
        required: false
        schema:
          type: string
          default: prod
          title: Channel
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /prompts/prompts/render:
    post:
      tags:
      - prompts
      summary: Render Prompt Template
      description: Render a prompt template with variables (for testing)
      operationId: render_prompt_template_prompts_prompts_render_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PromptTestRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /prompts/prompts/test-morning-checkin:
    post:
      tags:
      - prompts
      summary: Test Morning Checkin
      description: Test the morning checkin prompt from the registry
      operationId: test_morning_checkin_prompts_prompts_test_morning_checkin_post
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /prompts/prompts/test-evening-reflection:
    post:
      tags:
      - prompts
      summary: Test Evening Reflection
      description: Test the evening reflection prompt from the registry
      operationId: test_evening_reflection_prompts_prompts_test_evening_reflection_post
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /prompts/prompts/usage-stats:
    get:
      tags:
      - prompts
      summary: Get Prompt Usage Stats
      description: Get prompt usage statistics (placeholder for future implementation)
      operationId: get_prompt_usage_stats_prompts_prompts_usage_stats_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /checkins/morning:
    post:
      tags:
      - checkins
      summary: Morning Checkin
      description: 'Process morning check-in using prompt from registry.


        The morning check-in:

        1. Captures a vivid scene from the last 24h

        2. Tags relevant Pillars

        3. Records affect (valence/arousal)

        4. Documents intent and outcome

        5. Notes affordances used or missed

        6. Generates hypothesis if needed'
      operationId: morning_checkin_checkins_morning_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CheckinRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CheckinResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /checkins/evening:
    post:
      tags:
      - checkins
      summary: Evening Checkin
      description: 'Process evening check-in using prompt from registry.


        The evening check-in:

        1. Reviews overall day affect

        2. Checks if tests were run or affordances used

        3. Notes any mismatches with others

        4. Identifies active Pillars

        5. Updates hypotheses with evidence

        6. Generates recommendations'
      operationId: evening_checkin_checkins_evening_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CheckinRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CheckinResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /checkins/status/{user_id}:
    get:
      tags:
      - checkins
      summary: Get Checkin Status
      description: 'Get the check-in status for a user.

        Shows last morning and evening check-in times.'
      operationId: get_checkin_status_checkins_status__user_id__get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /self-narrative/generate:
    post:
      tags:
      - self-narrative
      summary: Generate Self Narrative
      description: 'Generate self-narrative from CLEAR self model.


        This endpoint:

        1. Takes CLEAR modality weights and attention policy

        2. Uses the self_narrative_synthesis prompt

        3. Returns current and future self narratives

        4. Identifies transformation path and key gaps'
      operationId: generate_self_narrative_self_narrative_generate_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SelfNarrativeRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SelfNarrativeResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /self-narrative/generate-from-scoring:
    post:
      tags:
      - self-narrative
      summary: Generate From Scoring Response
      description: 'Generate self-narrative directly from My Self Scoring response.


        This is a convenience endpoint that takes the raw scoring response

        and extracts the necessary data for narrative generation.'
      operationId: generate_from_scoring_response_self_narrative_generate_from_scoring_post
      parameters:
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          title: User Id
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: true
              title: Scoring Response
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /self-narrative/sample-input:
    get:
      tags:
      - self-narrative
      summary: Get Sample Input
      description: 'Get a sample CLEAR self model input for testing.


        This provides example data that can be used in the testing dashboard.'
      operationId: get_sample_input_self_narrative_sample_input_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /onboarding/test:
    get:
      tags:
      - onboarding
      summary: Test Onboarding
      description: Test if onboarding functionality is available
      operationId: test_onboarding_onboarding_test_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /onboarding/initialize:
    post:
      tags:
      - onboarding
      summary: Initialize Onboarding
      description: Initialize a new onboarding session for a user
      operationId: initialize_onboarding_onboarding_initialize_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Body_initialize_onboarding_onboarding_initialize_post'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /onboarding/questions:
    get:
      tags:
      - onboarding
      summary: Get Onboarding Questions
      description: 'Get questionnaire questions from My Self Scoring service.


        Progressive onboarding levels:

        - Level 1: Clarity Seeker (minimal_0_1_0) - Foundation

        - Level 2: Insight Builder (level_2_0_1_0) - Wellness expansion

        - Level 3: Pattern Mapper (level_3_0_1_0) - Complete coverage

        - Level 4: Meaning Maker (level_4_0_1_0) - Mental health deep dive

        - Level 5: Growth Master (level_5_0_1_0) - Integration & balance


        Use level parameter (1-5) for progressive onboarding.

        Use set parameter to override and request specific question set.'
      operationId: get_onboarding_questions_onboarding_questions_get
      parameters:
      - name: set
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: Set
      - name: user_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: User Id
      - name: level
        in: query
        required: false
        schema:
          anyOf:
          - type: integer
          - type: 'null'
          title: Level
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /onboarding/score:
    post:
      tags:
      - onboarding
      summary: Score Onboarding Answers
      description: 'Process questionnaire responses and generate user self-model.


        This endpoint:

        1. Scores answers using My Self Scoring API

        2. Generates modality weights and attention policy

        3. Creates initial beliefs and projected episodes

        4. Calculates initial residuals

        5. Stores the self-model in the database

        6. Calculates and persists initial alignment score'
      operationId: score_onboarding_answers_onboarding_score_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Body_score_onboarding_answers_onboarding_score_post'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /onboarding/self-model:
    post:
      tags:
      - onboarding
      summary: Create Or Update Self Model
      description: 'Create a self-model directly from scoring data (for external integrations).


        This endpoint allows external systems to create a self-model by providing

        pre-computed modality weights and attention policy.'
      operationId: create_or_update_self_model_onboarding_self_model_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Body_create_or_update_self_model_onboarding_self_model_post'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /onboarding/level-up:
    post:
      tags:
      - onboarding
      summary: Level Up User
      description: 'Advance user to next level in progressive onboarding.


        This endpoint:

        1. Validates user is at previous level

        2. Updates user''s current_level

        3. Records last_level_at timestamp

        4. Can be used to track progressive onboarding completion


        Note: Level must be sequential (current_level + 1).

        Levels range from 1-5.'
      operationId: level_up_user_onboarding_level_up_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Body_level_up_user_onboarding_level_up_post'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /onboarding/users/{user_id}/progress:
    get:
      tags:
      - onboarding
      summary: Get User Progress
      description: Get user's onboarding progression status
      operationId: get_user_progress_onboarding_users__user_id__progress_get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /onboarding/demo_data:
    post:
      tags:
      - onboarding
      summary: Generate Demo Data
      description: Generate realistic sample data for immediate user value demonstration
      operationId: generate_demo_data_onboarding_demo_data_post
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /memory/stm:
    get:
      tags:
      - memory
      summary: Get Stm Memories
      description: Get Short-Term Memory entries
      operationId: get_stm_memories_memory_stm_get
      parameters:
      - name: memory_type
        in: query
        required: false
        schema:
          type: string
          enum:
          - all
          - episode
          - belief
          default: all
          title: Memory Type
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /memory/ltm:
    get:
      tags:
      - memory
      summary: Get Ltm Memories
      description: Get Long-Term Memory entries (promoted memories)
      operationId: get_ltm_memories_memory_ltm_get
      parameters:
      - name: memory_type
        in: query
        required: false
        schema:
          type: string
          enum:
          - all
          - episode
          - belief
          default: all
          title: Memory Type
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /memory/consolidate:
    post:
      tags:
      - memory
      summary: Run Consolidation
      description: Manual memory consolidation - clean up old STM entries
      operationId: run_consolidation_memory_consolidate_post
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /memory/statistics:
    get:
      tags:
      - memory
      summary: Get Memory Statistics
      description: Get comprehensive memory system statistics and analytics
      operationId: get_memory_statistics_memory_statistics_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /memory/adaptive/status:
    get:
      tags:
      - memory
      summary: Get Adaptive Status
      description: Get current adaptive threshold management status
      operationId: get_adaptive_status_memory_adaptive_status_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /memory/adaptive/analyze:
    post:
      tags:
      - memory
      summary: Run Adaptive Analysis
      description: Run adaptive threshold analysis manually
      operationId: run_adaptive_analysis_memory_adaptive_analyze_post
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /monitoring/performance:
    get:
      tags:
      - monitoring
      - scheduler
      summary: Get Performance Metrics
      description: Get current performance metrics and recent request logs
      operationId: get_performance_metrics_monitoring_performance_get
      parameters:
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          maximum: 1000
          description: Number of recent logs to return
          default: 50
          title: Limit
        description: Number of recent logs to return
      - name: max_endpoints
        in: query
        required: false
        schema:
          type: integer
          default: 500
          title: Max Endpoints
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /monitoring/health:
    get:
      tags:
      - monitoring
      - scheduler
      summary: Get Detailed Health
      description: Get comprehensive system health status
      operationId: get_detailed_health_monitoring_health_get
      parameters:
      - name: max_endpoints
        in: query
        required: false
        schema:
          type: integer
          default: 500
          title: Max Endpoints
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /scheduler/status:
    get:
      tags:
      - monitoring
      - scheduler
      summary: Get Scheduler Status
      description: Get background task scheduler status and statistics
      operationId: get_scheduler_status_scheduler_status_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /scheduler/start:
    post:
      tags:
      - monitoring
      - scheduler
      summary: Start Scheduler
      description: Start the background task scheduler
      operationId: start_scheduler_scheduler_start_post
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /scheduler/stop:
    post:
      tags:
      - monitoring
      - scheduler
      summary: Stop Scheduler
      description: Stop the background task scheduler
      operationId: stop_scheduler_scheduler_stop_post
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /scheduler/consolidation/run:
    post:
      tags:
      - monitoring
      - scheduler
      summary: Run Consolidation Task
      description: Manually trigger memory consolidation task
      operationId: run_consolidation_task_scheduler_consolidation_run_post
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /embeddings/info:
    get:
      tags:
      - embeddings
      summary: Get Embedding Info
      description: Get detailed information about the embedding system
      operationId: get_embedding_info_embeddings_info_get
      parameters:
      - name: openai_client
        in: query
        required: false
        schema:
          title: Openai Client
      - name: embedder
        in: query
        required: false
        schema:
          title: Embedder
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /embeddings/similarity:
    post:
      tags:
      - embeddings
      summary: Compute Similarity
      description: Compute similarity between two text strings
      operationId: compute_similarity_embeddings_similarity_post
      parameters:
      - name: text1
        in: query
        required: true
        schema:
          type: string
          description: First text to compare
          title: Text1
        description: First text to compare
      - name: text2
        in: query
        required: true
        schema:
          type: string
          description: Second text to compare
          title: Text2
        description: Second text to compare
      - name: openai_client
        in: query
        required: false
        schema:
          title: Openai Client
      - name: embedder
        in: query
        required: false
        schema:
          title: Embedder
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/users/{user_id}/self-model:
    get:
      tags:
      - users
      summary: Get User Self Model
      description: Get user's self-model data
      operationId: get_user_self_model_api_users__user_id__self_model_get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: onboarding_service
        in: query
        required: false
        schema:
          title: Onboarding Service
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/users/{user_id}/context:
    get:
      tags:
      - users
      summary: Get User Context
      description: Get comprehensive user context including episodes, beliefs, and
        alignment data
      operationId: get_user_context_api_users__user_id__context_get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: include_episodes
        in: query
        required: false
        schema:
          type: boolean
          default: true
          title: Include Episodes
      - name: include_beliefs
        in: query
        required: false
        schema:
          type: boolean
          default: true
          title: Include Beliefs
      - name: include_alignment
        in: query
        required: false
        schema:
          type: boolean
          default: true
          title: Include Alignment
      - name: onboarding_service
        in: query
        required: false
        schema:
          title: Onboarding Service
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/users/{user_id}/progress:
    get:
      tags:
      - users
      summary: Get User Progress
      description: 'Get user''s progression status including level history.


        This endpoint provides:

        - Current level

        - Levels completed

        - Progress percentage (current_level / 5 * 100)

        - Version history with modality weights'
      operationId: get_user_progress_api_users__user_id__progress_get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: onboarding_service
        in: query
        required: false
        schema:
          title: Onboarding Service
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/users/:
    options:
      tags:
      - users
      summary: Users Options
      description: CORS preflight for user listing endpoint
      operationId: users_options_api_users__options
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
    get:
      tags:
      - users
      summary: List Users
      description: List all users with pagination
      operationId: list_users_api_users__get
      parameters:
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          maximum: 1000
          default: 100
          title: Limit
      - name: offset
        in: query
        required: false
        schema:
          type: integer
          minimum: 0
          default: 0
          title: Offset
      - name: onboarding_service
        in: query
        required: false
        schema:
          title: Onboarding Service
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/users/{user_id}:
    delete:
      tags:
      - users
      summary: Delete User
      description: 'Delete a user and all associated data. Idempotent.


        Requires BOTH:

        - X-API-Key header (application-level auth)

        - Authorization: Bearer <supabase_jwt> (user-level auth)


        The JWT''s user ID must match the path parameter.

        Rate limited to 3 attempts per user per hour.'
      operationId: delete_user_api_users__user_id__delete
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: onboarding_service
        in: query
        required: false
        schema:
          title: Onboarding Service
      - name: authorization
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: Authorization
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /users/{user_id}/self-model:
    get:
      tags:
      - users
      summary: Get User Self Model
      description: Get user's self-model data
      operationId: get_user_self_model_users__user_id__self_model_get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: onboarding_service
        in: query
        required: false
        schema:
          title: Onboarding Service
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /users/{user_id}/context:
    get:
      tags:
      - users
      summary: Get User Context
      description: Get comprehensive user context including episodes, beliefs, and
        alignment data
      operationId: get_user_context_users__user_id__context_get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: include_episodes
        in: query
        required: false
        schema:
          type: boolean
          default: true
          title: Include Episodes
      - name: include_beliefs
        in: query
        required: false
        schema:
          type: boolean
          default: true
          title: Include Beliefs
      - name: include_alignment
        in: query
        required: false
        schema:
          type: boolean
          default: true
          title: Include Alignment
      - name: onboarding_service
        in: query
        required: false
        schema:
          title: Onboarding Service
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /users/{user_id}/progress:
    get:
      tags:
      - users
      summary: Get User Progress
      description: 'Get user''s progression status including level history.


        This endpoint provides:

        - Current level

        - Levels completed

        - Progress percentage (current_level / 5 * 100)

        - Version history with modality weights'
      operationId: get_user_progress_users__user_id__progress_get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: onboarding_service
        in: query
        required: false
        schema:
          title: Onboarding Service
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /users/:
    options:
      tags:
      - users
      summary: Users Options
      description: CORS preflight for user listing endpoint
      operationId: users_options_users__options
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
    get:
      tags:
      - users
      summary: List Users
      description: List all users with pagination
      operationId: list_users_users__get
      parameters:
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          maximum: 1000
          default: 100
          title: Limit
      - name: offset
        in: query
        required: false
        schema:
          type: integer
          minimum: 0
          default: 0
          title: Offset
      - name: onboarding_service
        in: query
        required: false
        schema:
          title: Onboarding Service
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /users/{user_id}:
    delete:
      tags:
      - users
      summary: Delete User
      description: 'Delete a user and all associated data. Idempotent.


        Requires BOTH:

        - X-API-Key header (application-level auth)

        - Authorization: Bearer <supabase_jwt> (user-level auth)


        The JWT''s user ID must match the path parameter.

        Rate limited to 3 attempts per user per hour.'
      operationId: delete_user_users__user_id__delete
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: onboarding_service
        in: query
        required: false
        schema:
          title: Onboarding Service
      - name: authorization
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: Authorization
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/alignment/{user_id}:
    options:
      tags:
      - alignment
      summary: Alignment Options
      description: Handle preflight requests for alignment endpoint (CORS)
      operationId: alignment_options_api_alignment__user_id__options
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    get:
      tags:
      - alignment
      summary: Get User Alignment
      description: 'Get complete alignment data for a user.


        This provides the main alignment score and related metrics.

        For backward compatibility, this endpoint is maintained at the root

        alongside the more specific /score/{user_id} endpoint.'
      operationId: get_user_alignment_api_alignment__user_id__get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: include_temporal
        in: query
        required: false
        schema:
          type: boolean
          description: Include temporal alignment data
          default: true
          title: Include Temporal
        description: Include temporal alignment data
      - name: include_ambiguity
        in: query
        required: false
        schema:
          type: boolean
          description: Include ambiguity measures
          default: true
          title: Include Ambiguity
        description: Include ambiguity measures
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/alignment/score/{user_id}:
    get:
      tags:
      - alignment
      summary: Get Alignment Score
      description: 'Get current alignment score for a user.


        This calculates the alignment between the user''s recent activity

        and their desired trajectory from current to target self.'
      operationId: get_alignment_score_api_alignment_score__user_id__get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: window_days
        in: query
        required: false
        schema:
          type: integer
          maximum: 30
          minimum: 1
          description: Days to look back for activity
          default: 7
          title: Window Days
        description: Days to look back for activity
      - name: include_details
        in: query
        required: false
        schema:
          type: boolean
          description: Include telos and recent vectors
          default: true
          title: Include Details
        description: Include telos and recent vectors
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AlignmentMetrics'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/alignment/calculate/{user_id}:
    post:
      tags:
      - alignment
      summary: Trigger Calculation
      description: 'Trigger alignment score calculation for a user.


        This will calculate and store the alignment score. Use force=true

        to recalculate even if a recent score exists.'
      operationId: trigger_calculation_api_alignment_calculate__user_id__post
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: force
        in: query
        required: false
        schema:
          type: boolean
          description: Force recalculation even if recent exists
          default: false
          title: Force
        description: Force recalculation even if recent exists
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AlignmentMetrics'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/alignment/history/{user_id}:
    get:
      tags:
      - alignment
      summary: Get Alignment History
      description: 'Get historical alignment scores for trend analysis.


        Returns a list of alignment scores over the specified time period.'
      operationId: get_alignment_history_api_alignment_history__user_id__get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: days
        in: query
        required: false
        schema:
          type: integer
          maximum: 90
          minimum: 7
          description: Days of history to retrieve
          default: 30
          title: Days
        description: Days of history to retrieve
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/alignment/profile/{user_id}:
    get:
      tags:
      - alignment
      summary: Get Alignment Profile
      description: 'Get complete alignment profile including self models and insights.


        This provides a comprehensive view for debugging and inspection.'
      operationId: get_alignment_profile_api_alignment_profile__user_id__get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserAlignmentProfile'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/alignment/batch-calculate:
    post:
      tags:
      - alignment
      summary: Batch Calculate Alignment
      description: 'Calculate alignment scores for multiple users.


        Useful for batch processing and testing.'
      operationId: batch_calculate_alignment_api_alignment_batch_calculate_post
      parameters:
      - name: window_days
        in: query
        required: false
        schema:
          type: integer
          maximum: 30
          minimum: 1
          default: 7
          title: Window Days
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: array
              items:
                type: string
              title: User Ids
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/alignment/by-email/{email}:
    get:
      tags:
      - alignment
      summary: Get Alignment By Email
      description: 'Get alignment data for a user by their email address.


        This endpoint looks up the user_id from email and returns their stored alignment
        data.

        Useful for frontend components that only have access to email from session.'
      operationId: get_alignment_by_email_api_alignment_by_email__email__get
      parameters:
      - name: email
        in: path
        required: true
        schema:
          type: string
          title: Email
      - name: include_temporal
        in: query
        required: false
        schema:
          type: boolean
          description: Include temporal alignment data
          default: true
          title: Include Temporal
        description: Include temporal alignment data
      - name: include_ambiguity
        in: query
        required: false
        schema:
          type: boolean
          description: Include ambiguity measures
          default: true
          title: Include Ambiguity
        description: Include ambiguity measures
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /inputs/:
    post:
      tags:
      - inputs
      - Unified Input Architecture
      summary: Process User Input
      description: "Process input envelope from Clarity\n\nThis is the unified entry\
        \ point for all input types. The endpoint:\n1. Validates the input envelope\
        \ structure\n2. Creates an ingestion_event record for tracking\n3. Routes\
        \ to the appropriate handler based on input_type\n4. Updates the ingestion_event\
        \ with results\n5. Returns standardized response\n\n**Supported Input Types:**\n\
        - `likert`: Likert scale responses (1-5, 1-7, etc.)\n- `reflection`: Guided\
        \ reflection prompt responses\n- `narrative`: Journal entries and free-form\
        \ narratives\n- `slider`: Continuous scale responses (0-100)\n- `ranking`:\
        \ Item ranking by preference/importance\n- `experiential`: CLEAR Experiential\
        \ reflections (Create, Learn, Explore, Act, Recover)\n- `backcasting`: Future-oriented\
        \ backcasting exercises\n\n**Args:**\n    envelope: Input envelope with type-specific\
        \ data\n\n**Returns:**\n    Standardized response with processing results\n\
        \n**Raises:**\n    HTTPException: If envelope validation fails or processing\
        \ errors occur"
      operationId: process_input_inputs__post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/src__api__routes__inputs__InputEnvelope'
        required: true
      responses:
        '200':
          description: Input processed successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InputResponse'
              example:
                status: success
                envelope_id: 123e4567-e89b-12d3-a456-426614174000
                ingestion_event_id: evt_abc123
                results:
                  episode_id: 42
                  belief_ids:
                  - 101
                  - 102
                  self_model_updated: true
                  errors: []
                errors: []
        '400':
          description: Invalid input data or handler error
        '422':
          description: Invalid envelope structure
        '500':
          description: Processing failed
        '503':
          description: Database unavailable
  /inputs/health:
    get:
      tags:
      - inputs
      - Unified Input Architecture
      summary: Inputs Health Check
      description: 'Health check for /inputs endpoint


        Verifies:

        - PostgreSQL is available

        - Handler registry is accessible

        - Ingestion events table exists


        Returns overall health status and component details.'
      operationId: inputs_health_inputs_health_get
      responses:
        '200':
          description: Health check results
          content:
            application/json:
              schema:
                additionalProperties: true
                type: object
                title: Response Inputs Health Inputs Health Get
              example:
                status: healthy
                timestamp: '2025-01-15T12:00:00.000Z'
                components:
                  postgres:
                    status: healthy
                    ingestion_events: 1234
                  handlers:
                    status: available
                    registered:
                    - likert
                    - reflection
                    - narrative
                    - slider
                    - ranking
                    - experiential
                    - backcasting
                    count: 7
  /input/:
    post:
      tags:
      - input-async
      summary: Submit Input Envelope
      description: Submit an input envelope for async processing. Returns immediately
        with envelope_id for status polling.
      operationId: submit_input_input__post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/InputEnvelopeCreate'
        required: true
      responses:
        '202':
          description: Envelope accepted and queued for processing
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InputEnvelopeResponse'
        '400':
          description: Invalid input type or payload
        '404':
          description: User not found
        '503':
          description: Database or queue not available
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /input/{envelope_id}:
    get:
      tags:
      - input-async
      summary: Get Envelope Status
      description: Check the processing status of a submitted envelope.
      operationId: get_input_status_input__envelope_id__get
      parameters:
      - name: envelope_id
        in: path
        required: true
        schema:
          type: string
          format: uuid
          title: Envelope Id
      responses:
        '200':
          description: Envelope status returned
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InputEnvelopeStatus'
        '404':
          description: Envelope not found
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /input/stats/:
    get:
      tags:
      - input-async
      summary: Get Envelope Statistics
      description: Get counts of envelopes by status.
      operationId: get_stats_input_stats__get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/EnvelopeStatsResponse'
  /input/session/{session_id}:
    get:
      tags:
      - input-async
      summary: Get Session Envelopes
      description: Get all envelopes for a specific session.
      operationId: get_session_envelopes_input_session__session_id__get
      parameters:
      - name: session_id
        in: path
        required: true
        schema:
          type: string
          title: Session Id
      responses:
        '200':
          description: Envelopes returned
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/EnvelopeListResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /input/retry-pending:
    post:
      tags:
      - input-async
      summary: Retry Pending Envelopes
      description: Re-queue all pending envelopes that failed to be queued initially.
        Used for recovery after queue outages.
      operationId: retry_pending_envelopes_input_retry_pending_post
      parameters:
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          default: 100
          title: Limit
      responses:
        '200':
          description: Retry results returned
          content:
            application/json:
              schema:
                type: object
                additionalProperties: true
                title: Response Retry Pending Envelopes Input Retry Pending Post
        '503':
          description: Database not available
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /sessions/:
    post:
      tags:
      - sessions
      summary: Create Session
      description: 'Create a new self-model update session.


        This endpoint is called by Clarity to initiate a session before sending envelopes.'
      operationId: create_session_sessions__post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/src__api__routes__sessions__CreateSessionRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateSessionResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /sessions/{session_id}:
    get:
      tags:
      - sessions
      summary: Get Session
      description: 'Get session details by ID.


        Returns current session status, episode counts, and completion data if available.'
      operationId: get_session_sessions__session_id__get
      parameters:
      - name: session_id
        in: path
        required: true
        schema:
          type: string
          title: Session Id
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/src__api__routes__sessions__SessionResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /sessions/{session_id}/episodes:
    post:
      tags:
      - sessions
      summary: Register Episode
      description: 'Register an episode with a session.


        This increments the processed_episode_count and triggers session completion

        if all expected episodes have been processed.


        Called by input handlers after creating an episode from an envelope.'
      operationId: register_episode_sessions__session_id__episodes_post
      parameters:
      - name: session_id
        in: path
        required: true
        schema:
          type: string
          title: Session Id
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RegisterEpisodeRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/src__api__routes__sessions__SessionResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /sessions/{session_id}/fail:
    post:
      tags:
      - sessions
      summary: Mark Session Failed
      description: 'Mark a session as failed.


        Called when episode processing encounters an unrecoverable error.'
      operationId: mark_session_failed_sessions__session_id__fail_post
      parameters:
      - name: session_id
        in: path
        required: true
        schema:
          type: string
          title: Session Id
      - name: error_message
        in: query
        required: true
        schema:
          type: string
          title: Error Message
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /sessions/cleanup/stale:
    post:
      tags:
      - sessions
      summary: Cleanup Stale Sessions
      description: 'Mark stale sessions as abandoned.


        Finds sessions that have been in_progress for longer than timeout_minutes

        and marks them as abandoned.


        Called by monitoring/cleanup jobs.'
      operationId: cleanup_stale_sessions_sessions_cleanup_stale_post
      parameters:
      - name: timeout_minutes
        in: query
        required: false
        schema:
          type: integer
          default: 60
          title: Timeout Minutes
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/onboarding:
    post:
      tags:
      - external
      summary: Register External User
      description: "Register or lookup an external user (idempotent).\n\nIf external_id\
        \ is provided:\n- Returns existing user if external_id is already mapped\n\
        - Creates new user and mapping if external_id is new\n\nIf only email is provided:\n\
        - Returns existing user if email exists (in user_self_models or external_user_mappings)\n\
        - Creates new user if email is new\n\nReturns:\n    - 201 Created: New user\
        \ was created (created=true)\n    - 200 OK: Existing user was found (created=false)"
      operationId: register_external_user_external_onboarding_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OnboardingRequest'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OnboardingResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    get:
      tags:
      - external
      summary: Get External User
      description: 'Get user by user_id or external_id.


        At least one of user_id or external_id must be provided.'
      operationId: get_external_user_external_onboarding_get
      parameters:
      - name: user_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Internal user ID
          title: User Id
        description: Internal user ID
      - name: external_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: External system user ID
          title: External Id
        description: External system user ID
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OnboardingResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/input:
    post:
      tags:
      - external
      summary: Process Input
      description: 'Process an input envelope.


        This is the main endpoint for submitting user inputs for processing.

        The envelope is routed to the appropriate handler based on input_type.


        **Supported Input Types:**

        - `likert`: Likert scale responses (1-5, 1-7, etc.)

        - `reflection`: Guided reflection prompt responses

        - `narrative`: Journal entries and free-form narratives

        - `slider`: Continuous scale responses (0-100)

        - `ranking`: Item ranking by preference/importance

        - `experiential`: CLEAR Experiential reflections

        - `backcasting`: Future-oriented backcasting exercises

        - `transcript`: Meeting transcripts (async — returns 202, poll for results)


        **Workflow:**

        1. Create session via POST /external/sessions

        2. Submit envelopes via POST /external/input (this endpoint)

        3. For transcript: poll GET /external/input/{envelope_id}/status

        4. For other types: response is synchronous (200)'
      operationId: process_input_external_input_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/src__api__routes__external__InputEnvelope'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/input/{envelope_id}/status:
    get:
      tags:
      - external
      summary: Get Envelope Status
      description: 'Poll the processing status of an async input envelope.


        Use this after receiving a 202 from POST /external/input for transcript envelopes.


        **Status values:**

        - `pending`: Stored but not yet queued

        - `queued`: In the processing queue

        - `processing`: Worker is actively processing

        - `completed`: Done — episode_id and belief_ids available

        - `failed`: Processing failed — see error_message'
      operationId: get_envelope_status_external_input__envelope_id__status_get
      parameters:
      - name: envelope_id
        in: path
        required: true
        schema:
          type: string
          title: Envelope Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/EnvelopeStatusResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/sessions:
    post:
      tags:
      - external
      summary: Create Session
      description: 'Create a new self-model update session.


        This should be called before sending envelopes to establish the session context.

        The user_id must exist (created via POST /external/onboarding).'
      operationId: create_session_external_sessions_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/src__api__routes__external__CreateSessionRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateSessionResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/sessions/{session_id}:
    get:
      tags:
      - external
      summary: Get Session
      description: 'Get session details by ID.


        Returns current status, episode counts, and completion data.'
      operationId: get_session_external_sessions__session_id__get
      parameters:
      - name: session_id
        in: path
        required: true
        schema:
          type: string
          title: Session Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/src__api__routes__external__SessionResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/sessions/{session_id}/fail:
    post:
      tags:
      - external
      summary: Mark Session Failed
      description: 'Mark a session as failed.


        Called when processing encounters an unrecoverable error.'
      operationId: mark_session_failed_external_sessions__session_id__fail_post
      parameters:
      - name: session_id
        in: path
        required: true
        schema:
          type: string
          title: Session Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/FailSessionRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/sessions/cleanup:
    post:
      tags:
      - external
      summary: Cleanup Stale Sessions
      description: 'Cleanup stale sessions by marking them as abandoned.


        Finds sessions in_progress for longer than timeout_minutes.'
      operationId: cleanup_stale_sessions_external_sessions_cleanup_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CleanupRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CleanupResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/context:
    post:
      tags:
      - external
      summary: Assemble Context
      description: "Assemble context for a self-model.\n\n**Authorization**: The requesting_user_id\
        \ must match the owner of the self-model.\nThis prevents unauthorized access\
        \ to other users' context.\n\nContext is assembled from the self-model's projection\
        \ data and formatted\naccording to the requested format:\n\n- **ai_ready**:\
        \ Optimized for LLM consumption with narrative elements\n- **raw**: Full projection\
        \ data for programmatic access\n- **summary**: Condensed overview for dashboards\n\
        \n**Example Request:**\n```json\n{\n    \"self_model_id\": 123,\n    \"format\"\
        : \"ai_ready\",\n    \"include_beliefs\": true,\n    \"include_narrative\"\
        : true,\n    \"max_beliefs\": 50\n}\n```\n\n**Alternative with user_id:**\n\
        ```json\n{\n    \"user_id\": \"user_abc123\",\n    \"format\": \"summary\"\
        \n}\n```"
      operationId: assemble_context_external_context_post
      parameters:
      - name: requesting_user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: Requesting User Id
        description: User ID for authorization
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ContextRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ContextResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/context/formats:
    get:
      tags:
      - external
      summary: List Context Formats
      description: 'List available context formats and their descriptions.


        Returns information about each format type to help developers

        choose the right format for their use case.'
      operationId: list_context_formats_external_context_formats_get
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListFormatsResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models:
    post:
      tags:
      - self-models
      summary: Create Self Model
      description: "Create a new self-model for a user.\n\nUsers can have multiple\
        \ self-models with unique names.\nEach self-model has its own domain configuration,\
        \ modes, and views.\n\n**Example Request:**\n```json\n{\n    \"name\": \"\
        Clarity Health Self\",\n    \"description\": \"Self-model for health and wellness\
        \ tracking\",\n    \"self_model_type\": \"primary\",\n    \"domains\": [\n\
        \        {\"id\": \"physical_health\", \"name\": \"Physical Health\"},\n \
        \       {\"id\": \"mental_health\", \"name\": \"Mental Health\"}\n    ],\n\
        \    \"modes\": [\n        {\"id\": \"create\", \"name\": \"Create\", \"target_engagement\"\
        : {\"energy\": {\"budget_cognitive\": 0.7}}}\n    ],\n    \"views\": [\n \
        \       {\"id\": \"current\", \"role\": \"being\", \"label\": \"Current Self\"\
        }\n    ]\n}\n```"
      operationId: create_self_model_external_self_models_post
      parameters:
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for the self-model
          title: User Id
        description: User ID for the self-model
      - name: email
        in: query
        required: true
        schema:
          type: string
          description: User email for the self-model
          title: Email
        description: User email for the self-model
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateSelfModelRequest'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateSelfModelResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    get:
      tags:
      - self-models
      summary: List Self Models
      description: 'List self-models with optional filtering.


        Admin mode: Omit user_id to list ALL self-models across all users.

        Supports filtering by user_id, app_id, and self_model_type.


        Response formats:

        - format=full (default): Returns full SelfModelResponse objects (backward
        compatible)

        - format=admin: Returns simplified AdminSelfModelListItem with external_id/app_id'
      operationId: list_self_models_external_self_models_get
      parameters:
      - name: user_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by user ID (admin mode if omitted)
          title: User Id
        description: Filter by user ID (admin mode if omitted)
      - name: app_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by application ID (e.g., mystica, clarity)
          title: App Id
        description: Filter by application ID (e.g., mystica, clarity)
      - name: self_model_type
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: 'Filter by type: primary, archetype, experimental, snapshot'
          title: Self Model Type
        description: 'Filter by type: primary, archetype, experimental, snapshot'
      - name: format
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: 'Response format: ''full'' (default) or ''admin'' (simplified)'
          default: full
          title: Format
        description: 'Response format: ''full'' (default) or ''admin'' (simplified)'
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}:
    get:
      tags:
      - self-models
      summary: Get Self Model
      description: 'Get a self-model by ID.


        Returns the full self-model definition including domains, modes, and views.

        Requires user_id to verify ownership.'
      operationId: get_self_model_external_self_models__self_model_id__get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: User Id
        description: User ID for authorization
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SelfModelResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    put:
      tags:
      - self-models
      summary: Update Self Model
      description: 'Update an existing self-model.


        Supports partial updates - only provided fields are updated.

        Updates increment the version number.

        Requires user_id to verify ownership.'
      operationId: update_self_model_external_self_models__self_model_id__put
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: User Id
        description: User ID for authorization
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateSelfModelRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UpdateSelfModelResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    delete:
      tags:
      - self-models
      summary: Delete Self Model
      description: 'Delete a self-model.


        Warning: This will also delete associated episodes and beliefs.

        Consider using a soft-delete or archiving approach in production.

        Requires user_id to verify ownership.'
      operationId: delete_self_model_external_self_models__self_model_id__delete
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: User Id
        description: User ID for authorization
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '204':
          description: Successful Response
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/by-name/{name}:
    get:
      tags:
      - self-models
      summary: Get Self Model By Name
      description: 'Get a self-model by user_id and name.


        Useful when you know the self-model name but not the ID.'
      operationId: get_self_model_by_name_external_self_models_by_name__name__get
      parameters:
      - name: name
        in: path
        required: true
        schema:
          type: string
          title: Name
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID to lookup self-model for
          title: User Id
        description: User ID to lookup self-model for
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SelfModelResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/by-external-id/{external_id}:
    get:
      tags:
      - self-models
      summary: Get Self Model By External Id
      description: 'Lookup a self-model by app-specific external_id.


        Enables idempotent self-model management — apps can reference

        self-models by their own identifiers (e.g., tenant:relationship_psychics)

        without storing Clarity API IDs locally.


        Requires user_id to verify ownership.'
      operationId: get_self_model_by_external_id_external_self_models_by_external_id__external_id__get
      parameters:
      - name: external_id
        in: path
        required: true
        schema:
          type: string
          title: External Id
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application ID that owns this external_id
          title: App Id
        description: Application ID that owns this external_id
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: User Id
        description: User ID for authorization
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SelfModelResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/backfill-app-id:
    post:
      tags:
      - self-models
      summary: Backfill Self Model App Id
      description: 'Backfill app_id on self-models that have app_id = NULL.


        Used after batch imports that created self-models without app_id.

        Optionally filter by self-model name pattern (e.g., ''Mystica%'').'
      operationId: backfill_self_model_app_id_external_self_models_backfill_app_id_post
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application ID to set (e.g., mystica)
          title: App Id
        description: Application ID to set (e.g., mystica)
      - name: name_pattern
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Only update self-models matching this name pattern (SQL LIKE)
          title: Name Pattern
        description: Only update self-models matching this name pattern (SQL LIKE)
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/episodes:
    post:
      tags:
      - observation-contexts
      summary: Create episode with context
      description: 'Create an episode with observation context support.


        Episodes can reference specific observation contexts within pillars,

        track customer journey stages, and categorize by episode type.


        **Path Parameters:**

        - `self_model_id`: ID of the self-model


        **Request Body:**

        - `domain_id`: Pillar (must be one of 9 pillars)

        - `observation_context_id`: Optional context within the pillar

        - `customer_journey_stage`: Optional journey stage

        - `episode_type`: Optional episode type

        - `content`: Episode content

        - `engagement`: Optional engagement state'
      operationId: create_episode_with_context_external_self_models__self_model_id__episodes_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateEpisodeWithContextRequest'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/EpisodeWithContextResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    get:
      tags:
      - self-models
      summary: List Episodes For Self Model
      description: 'List episodes for a self-model.


        Optionally filter by domain, inferred mode, app_id, date range, or search
        text.

        Requires user_id to verify ownership.'
      operationId: list_episodes_for_self_model_external_self_models__self_model_id__episodes_get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: User Id
        description: User ID for authorization
      - name: domain_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by domain
          title: Domain Id
        description: Filter by domain
      - name: inferred_mode_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by inferred mode
          title: Inferred Mode Id
        description: Filter by inferred mode
      - name: app_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by app_id (e.g., clarity-claw, mystica)
          title: App Id
        description: Filter by app_id (e.g., clarity-claw, mystica)
      - name: date_from
        in: query
        required: false
        schema:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          description: Filter episodes created after this ISO datetime
          title: Date From
        description: Filter episodes created after this ISO datetime
      - name: date_to
        in: query
        required: false
        schema:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          description: Filter episodes created before this ISO datetime
          title: Date To
        description: Filter episodes created before this ISO datetime
      - name: search_text
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Search in episode content
          title: Search Text
        description: Search in episode content
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          maximum: 200
          minimum: 1
          description: Maximum episodes to return
          default: 50
          title: Limit
        description: Maximum episodes to return
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/episodes/batch:
    post:
      tags:
      - self-models
      summary: Batch Create Episodes
      description: 'Create multiple episodes in a single batch request.


        Accepts up to 500 episodes and inserts them in a single database transaction.

        Mode inference runs for each episode that includes engagement data.'
      operationId: batch_create_episodes_external_self_models__self_model_id__episodes_batch_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: User Id
        description: User ID for authorization
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BatchCreateEpisodesRequest'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BatchCreateEpisodesResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/episodes/by-context:
    delete:
      tags:
      - self-models
      summary: Delete Episodes By Context
      description: 'Delete episodes matching specific observation contexts within
        an app.

        Used for cleanup of aggregate episodes after per-post backfill.'
      operationId: delete_episodes_by_context_external_episodes_by_context_delete
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: App ID to scope deletion
          title: App Id
        description: App ID to scope deletion
      - name: observation_context_ids
        in: query
        required: true
        schema:
          type: string
          description: Comma-separated observation_context_ids to delete
          title: Observation Context Ids
        description: Comma-separated observation_context_ids to delete
      - name: source
        in: query
        required: false
        schema:
          type: string
          description: metadata.source filter
          default: substack_import
          title: Source
        description: metadata.source filter
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/episodes/{episode_id}:
    get:
      tags:
      - self-models
      summary: Get Episode With Engagement
      description: 'Get a specific episode with its engagement state.

        Requires user_id to verify ownership.'
      operationId: get_episode_with_engagement_external_self_models__self_model_id__episodes__episode_id__get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: episode_id
        in: path
        required: true
        schema:
          type: integer
          title: Episode Id
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: User Id
        description: User ID for authorization
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/views:
    get:
      tags:
      - self-models
      summary: Compute All Views
      description: "Compute all temporal views for a self-model with optional alignment\
        \ data (Phase 7).\n\nViews are defined in the self-model's definition and\
        \ include:\n- BEING: Current state from recent episodes (last 7 days)\n- BECOMING:\
        \ Trajectory toward future goals\n- TELOS: Ideal/theoretical optimum state\n\
        - ARCHETYPE: Reusable persona patterns\n\nEach view aggregates:\n- Domain\
        \ metrics (episode counts, engagement, mode distribution)\n- Overall engagement\
        \ state\n- Dominant mode and mode distribution\n\nWhen include_alignment=true\
        \ (default), the response also includes:\n- overall_score: 0-100 alignment\
        \ score\n- telos_vector: Direction from current state to target\n- on_course_status:\
        \ Status indicator (improving, stable, declining, etc.)\n- components: Breakdown\
        \ of alignment score\n- primary_focus_areas: Areas needing attention\n- suggested_actions:\
        \ Recommended next steps\n\nRequires requesting_user_id to verify ownership.\n\
        \n**Example Response:**\n```json\n{\n    \"views\": [\n        {\n       \
        \     \"view_id\": \"being\",\n            \"role\": \"being\",\n        \
        \    \"label\": \"Current State\",\n            \"computed_at\": \"2025-12-04T10:30:00Z\"\
        ,\n            \"domain_metrics\": {...},\n            \"overall_engagement\"\
        : {...},\n            \"dominant_mode\": \"create\",\n            \"mode_distribution\"\
        : {\"create\": 0.4, \"learn\": 0.3}\n        }\n    ],\n    \"alignment\"\
        : {\n        \"overall_score\": 72.5,\n        \"telos_vector\": {\n     \
        \       \"mode_delta\": {\"create\": 0.2, \"learn\": -0.1},\n            \"\
        domain_delta\": {\"physical_health\": 0.3},\n            \"magnitude\": 0.45,\n\
        \            \"primary_shifts\": [\"physical_health: +0.30\"]\n        },\n\
        \        \"on_course_status\": \"improving\",\n        \"belief_coherence\"\
        : 0.68,\n        \"confidence\": 0.85,\n        \"components\": {...},\n \
        \       \"primary_focus_areas\": [\"Increase physical health activities\"\
        ],\n        \"suggested_actions\": [\"Try starting a creative project\"]\n\
        \    },\n    \"computed_at\": \"2025-12-04T10:30:00Z\"\n}\n```"
      operationId: compute_all_views_external_self_models__self_model_id__views_get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: requesting_user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: Requesting User Id
        description: User ID for authorization
      - name: include_alignment
        in: query
        required: false
        schema:
          type: boolean
          description: Include alignment data in response
          default: true
          title: Include Alignment
        description: Include alignment data in response
      - name: app_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter views to episodes from this app
          title: App Id
        description: Filter views to episodes from this app
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/views/{view_id}:
    get:
      tags:
      - self-models
      summary: Compute Single View
      description: 'Compute a specific temporal view for a self-model.


        If the view_id matches a defined view, uses that definition.

        Otherwise, treats view_id as a role (being, becoming, telos, archetype)

        and computes with defaults.

        Requires user_id to verify ownership.'
      operationId: compute_single_view_external_self_models__self_model_id__views__view_id__get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: view_id
        in: path
        required: true
        schema:
          type: string
          title: View Id
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: User Id
        description: User ID for authorization
      - name: app_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter view to episodes from this app
          title: App Id
        description: Filter view to episodes from this app
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/project/engagement:
    post:
      tags:
      - self-models
      summary: Project Engagement
      description: "Project future self-model state based on hypothetical engagements.\n\
        \nUse this endpoint for \"what-if\" analysis:\n- \"What if I engage more with\
        \ physical_health domain?\"\n- \"What mode would I be in if I had high curiosity\
        \ and low energy?\"\n\nRequires user_id to verify ownership.\n\n**Example\
        \ Request:**\n```json\n{\n    \"hypotheses\": [\n        {\n            \"\
        domain_id\": \"physical_health\",\n            \"engagement\": {\n       \
        \         \"energy\": {\"budget_physical\": 0.8},\n                \"drive\"\
        : {\"valence\": \"approach\"}\n            },\n            \"description\"\
        : \"Morning workout routine\"\n        }\n    ],\n    \"horizon_days\": 7\n\
        }\n```"
      operationId: project_engagement_external_self_models__self_model_id__project_engagement_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: User Id
        description: User ID for authorization
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProjectEngagementRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/project/mode-transition:
    post:
      tags:
      - self-models
      summary: Project Mode Transition
      description: "Project what engagement changes are needed to transition to a\
        \ target mode.\n\nUse this for mode planning:\n- \"What do I need to change\
        \ to enter CREATE mode?\"\n- \"How do I transition from RECOVER to ACTIVATE?\"\
        \n\nRequires user_id to verify ownership.\n\n**Example Request:**\n```json\n\
        {\n    \"target_mode_id\": \"create\",\n    \"horizon_days\": 7\n}\n```"
      operationId: project_mode_transition_external_self_models__self_model_id__project_mode_transition_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: User Id
        description: User ID for authorization
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProjectModeTransitionRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/project/goal:
    post:
      tags:
      - self-models
      summary: Project Goal
      description: "Project path to reach a goal engagement state.\n\nUse this for\
        \ goal-setting and planning:\n- \"How do I reach my ideal (telos) state?\"\
        \n- \"What changes would get me to this engagement pattern?\"\n\nRequires\
        \ user_id to verify ownership.\n\n**Example Request:**\n```json\n{\n    \"\
        goal_engagement\": {\n        \"energy\": {\"budget_cognitive\": 0.8, \"budget_physical\"\
        : 0.6},\n        \"epistemic\": {\"curiosity\": 0.7},\n        \"drive\":\
        \ {\"orientation\": \"self-in-world\", \"valence\": \"approach\"}\n    },\n\
        \    \"horizon_days\": 30\n}\n```"
      operationId: project_goal_external_self_models__self_model_id__project_goal_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: user_id
        in: query
        required: true
        schema:
          type: string
          description: User ID for authorization
          title: User Id
        description: User ID for authorization
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProjectGoalRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/metadata:
    patch:
      tags:
      - self-models
      summary: Update Self Model Metadata
      description: 'Merge keys into self-model metadata JSONB.


        Uses PostgreSQL || concat to merge new keys into existing metadata

        without overwriting unrelated keys.'
      operationId: update_self_model_metadata_external_self_models__self_model_id__metadata_patch
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: true
              title: Metadata Patch
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/stakeholder-profiles:
    get:
      tags:
      - self-models
      summary: Get Stakeholder Profiles
      description: 'Return all stakeholder profiles (from user_self_models metadata)

        plus the value chain definition.


        Profiles include: display_name, role, base_weight, weight_source,

        observation_stage, observation_rationale.'
      operationId: get_stakeholder_profiles_external_stakeholder_profiles_get
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/pillar-templates:
    get:
      tags:
      - observation-contexts
      summary: List all pillar templates
      description: 'Get all 9 pillar templates.


        Pillar templates provide default structures for creating observation

        contexts within each pillar. Each template includes standard states

        (thriving, stable, struggling, crisis).


        **Response:**

        - `templates`: Array of pillar templates

        - `count`: Total number of templates (always 9)'
      operationId: get_pillar_templates_external_pillar_templates_get
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListPillarTemplatesResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/contexts:
    post:
      tags:
      - observation-contexts
      summary: Create observation context
      description: 'Create a new observation context for a self-model.


        Observation contexts provide app-specific granularity within pillars.

        For example, "emotional_stability" within "mental_health".


        **Path Parameters:**

        - `self_model_id`: ID of the self-model


        **Request Body:**

        - `context_id`: Unique identifier (snake_case)

        - `name`: Human-readable name

        - `domain_id`: Parent pillar (must be one of 9 pillars)

        - `description`: Optional description

        - `possible_states`: Optional list of possible states'
      operationId: create_observation_context_external_self_models__self_model_id__contexts_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateObservationContextRequest'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ObservationContextResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    get:
      tags:
      - observation-contexts
      summary: List observation contexts
      description: 'List observation contexts for a self-model.


        **Path Parameters:**

        - `self_model_id`: ID of the self-model


        **Query Parameters:**

        - `domain_id`: Optional filter by pillar'
      operationId: list_observation_contexts_external_self_models__self_model_id__contexts_get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: domain_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by pillar
          title: Domain Id
        description: Filter by pillar
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListObservationContextsResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/provision-contexts:
    post:
      tags:
      - observation-contexts
      summary: Provision observation contexts from journey spec
      description: 'Provision all observation contexts for a self-model from its journey
        spec.


        Loads the journey spec based on the self-model''s app_id, then provisions

        all observation contexts with goal_states from the spec''s stages.


        If app_id is provided as a query param, it overrides the self-model''s

        app_id and backfills it on the self-model record.


        Idempotent — safe to call multiple times.'
      operationId: provision_contexts_from_spec_external_self_models__self_model_id__provision_contexts_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: app_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Override app_id (also backfills self-model)
          title: App Id
        description: Override app_id (also backfills self-model)
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/seed-states:
    post:
      tags:
      - observation-contexts
      summary: Seed initial current_state on observation contexts
      description: 'Set current_state on observation contexts that don''t have one
        yet.


        Only transitions contexts where current_state_id IS NULL (first transition).

        Contexts that already have a current_state are skipped — this is safe to

        call repeatedly without overwriting existing state.'
      operationId: seed_context_states_external_self_models__self_model_id__seed_states_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SeedStatesRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/contexts/{context_id}/metadata:
    patch:
      tags:
      - observation-contexts
      summary: Merge metadata into an observation context
      description: 'Merge metadata fields into an observation context''s metadata
        JSONB.


        Uses PostgreSQL `||` operator to merge — existing keys are preserved

        unless overwritten by the request. Pass `{"metadata": {"key": "value"}}`.'
      operationId: patch_context_metadata_external_self_models__self_model_id__contexts__context_id__metadata_patch
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: context_id
        in: path
        required: true
        schema:
          type: string
          title: Context Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: true
              title: Request
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/contexts/clone:
    post:
      tags:
      - observation-contexts
      summary: Clone from pillar template
      description: 'Clone a pillar template to create a new observation context.


        The new context inherits the template''s possible_states unless

        custom states are provided.


        **Path Parameters:**

        - `self_model_id`: ID of the self-model


        **Request Body:**

        - `pillar_id`: Source pillar template

        - `context_id`: New context ID

        - `name`: New context name

        - `description`: Optional custom description

        - `possible_states`: Optional custom states'
      operationId: clone_context_from_template_external_self_models__self_model_id__contexts_clone_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CloneFromTemplateRequest'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ObservationContextResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/beliefs:
    post:
      tags:
      - observation-contexts
      summary: Create beliefs from claims
      description: 'Create one or more beliefs linked to an observation context.


        Used to sync essay claims to the self-model belief system.


        **Path Parameters:**

        - `self_model_id`: ID of the self-model


        **Request Body:**

        - `beliefs`: Array of beliefs to create

        - `observation_context_id`: Default context for all beliefs


        **Returns:**

        - Created beliefs with IDs and timestamps'
      operationId: create_beliefs_external_self_models__self_model_id__beliefs_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateBeliefsRequest'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateBeliefsResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    get:
      tags:
      - observation-contexts
      summary: List beliefs
      description: 'List beliefs for a self-model with optional filtering.


        **Path Parameters:**

        - `self_model_id`: ID of the self-model


        **Query Parameters:**

        - `observation_context_id`: Filter by observation context

        - `pillar`: Filter by pillar

        - `category`: Filter by belief category


        **Returns:**

        - List of beliefs matching filters'
      operationId: list_beliefs_external_self_models__self_model_id__beliefs_get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: observation_context_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by observation context
          title: Observation Context Id
        description: Filter by observation context
      - name: pillar
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by pillar
          title: Pillar
        description: Filter by pillar
      - name: category
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by category
          title: Category
        description: Filter by category
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListBeliefsResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/beliefs/{belief_id}:
    get:
      tags:
      - observation-contexts
      summary: Get belief by ID
      description: 'Get a single belief by ID.


        **Path Parameters:**

        - `self_model_id`: ID of the self-model

        - `belief_id`: ID of the belief


        **Returns:**

        - Belief details'
      operationId: get_belief_external_self_models__self_model_id__beliefs__belief_id__get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: belief_id
        in: path
        required: true
        schema:
          type: integer
          title: Belief Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BeliefResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    delete:
      tags:
      - observation-contexts
      summary: Delete belief by ID
      description: Delete a single belief by ID.
      operationId: delete_belief_external_self_models__self_model_id__beliefs__belief_id__delete
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: belief_id
        in: path
        required: true
        schema:
          type: integer
          title: Belief Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/beliefs/delete:
    post:
      tags:
      - observation-contexts
      summary: Batch delete beliefs
      description: Delete multiple beliefs by IDs. Only deletes beliefs belonging
        to the self-model.
      operationId: batch_delete_beliefs_external_self_models__self_model_id__beliefs_delete_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DeleteBeliefsRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/context-beliefs:
    post:
      tags:
      - observation-contexts
      summary: Create a belief linked to an observation context
      description: 'Create a belief for a self-model, linked to an observation context.


        Used for curated (manually authored) beliefs and programmatic belief creation.'
      operationId: create_context_belief_external_self_models__self_model_id__context_beliefs_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateContextBeliefRequest'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/state-residuals:
    get:
      tags:
      - observation-contexts
      summary: State residuals — predicted vs observed distance
      description: 'State residuals for all contexts of a self-model.


        Returns per-context residuals (predicted vs observed ordinal distance)

        and aggregate accuracy metrics. Separate from coding residuals at

        /analytics/residuals.'
      operationId: get_state_residuals_external_self_models__self_model_id__state_residuals_get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/self-models/{self_model_id}/proposed-contexts:
    get:
      tags:
      - observation-contexts
      summary: List proposed (unapproved) contexts
      description: List all proposed observation contexts awaiting review.
      operationId: list_proposed_contexts_external_admin_self_models__self_model_id__proposed_contexts_get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/self-models/{self_model_id}/contexts/{context_id}/approve:
    post:
      tags:
      - observation-contexts
      summary: Approve a proposed context
      description: Approve a proposed context — sets status to 'active'.
      operationId: approve_context_external_admin_self_models__self_model_id__contexts__context_id__approve_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: context_id
        in: path
        required: true
        schema:
          type: string
          title: Context Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ApproveContextRequest'
              default: {}
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/self-models/{self_model_id}/contexts/{context_id}/reject:
    post:
      tags:
      - observation-contexts
      summary: Reject a proposed context
      description: Reject a proposed context — sets status to 'rejected'.
      operationId: reject_context_external_admin_self_models__self_model_id__contexts__context_id__reject_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: context_id
        in: path
        required: true
        schema:
          type: string
          title: Context Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/self-models/{self_model_id}/contexts/merge:
    post:
      tags:
      - observation-contexts
      summary: Merge source context into target
      description: 'Merge source context into target: reassign beliefs, union episodes,
        mark source as merged.'
      operationId: merge_contexts_external_admin_self_models__self_model_id__contexts_merge_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MergeContextsRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/self-models/{self_model_id}/contexts/{context_id}/retire:
    post:
      tags:
      - observation-contexts
      summary: Retire a context
      description: Retire a context — sets status to 'retired'.
      operationId: retire_context_external_admin_self_models__self_model_id__contexts__context_id__retire_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: context_id
        in: path
        required: true
        schema:
          type: string
          title: Context Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/self-models/{self_model_id}/context-lifecycle:
    get:
      tags:
      - observation-contexts
      summary: Full context lifecycle — all statuses
      description: Return all contexts for a self-model regardless of status.
      operationId: get_context_lifecycle_external_admin_self_models__self_model_id__context_lifecycle_get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/journey-spec:
    get:
      tags:
      - observation-contexts
      summary: Dynamic journey spec — YAML + discovered contexts
      description: 'Return a dynamic journey spec merging YAML spec with discovered
        DB contexts.


        Includes stages, provisioned contexts, discovered contexts (sorted by

        belief density), and modes/forces from the YAML spec.'
      operationId: get_dynamic_journey_spec_external_self_models__self_model_id__journey_spec_get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/stages:
    get:
      tags:
      - journey
      summary: List Journey Stages
      description: "List journey stages for an application.\n\nReturns stages in funnel\
        \ order. Falls back to default stages if\nthe app has no custom stages configured.\n\
        \n**Example Response:**\n```json\n{\n    \"app_id\": \"mystica\",\n    \"\
        stages\": [\n        {\"name\": \"awareness\", \"display_name\": \"Awareness\"\
        , \"stage_order\": 1},\n        {\"name\": \"consideration\", \"display_name\"\
        : \"Consideration\", \"stage_order\": 2},\n        {\"name\": \"decision\"\
        , \"display_name\": \"Decision\", \"stage_order\": 3},\n        {\"name\"\
        : \"retention\", \"display_name\": \"Retention\", \"stage_order\": 4}\n  \
        \  ]\n}\n```"
      operationId: list_journey_stages_external_admin_journey_stages_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/JourneyStagesResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    post:
      tags:
      - journey
      summary: Create Journey Stage
      description: "Create a new journey stage for an application.\n\nStages must\
        \ have unique names and orders within an app.\n\n**Example Request:**\n```json\n\
        {\n    \"name\": \"trial\",\n    \"display_name\": \"Free Trial\",\n    \"\
        stage_order\": 3,\n    \"description\": \"User started free trial\"\n}\n```"
      operationId: create_journey_stage_external_admin_journey_stages_post
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/JourneyStageCreate'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/JourneyStage'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/funnel:
    get:
      tags:
      - journey
      summary: Get Funnel Analytics
      description: "Get funnel analytics for an application.\n\nReturns stage metrics\
        \ and transition conversion rates.\n\n**Metrics Included:**\n- User count\
        \ per stage\n- Episode count per stage\n- Conversion rate between stages\n\
        - Average time to convert\n- Top 20% vs Bottom 80% comparison (when cohort\
        \ data available)\n\n**Example Response:**\n```json\n{\n    \"app_id\": \"\
        mystica\",\n    \"stages\": [\n        {\"name\": \"awareness\", \"user_count\"\
        : 1000, \"episode_count\": 2500},\n        {\"name\": \"consideration\", \"\
        user_count\": 600, \"episode_count\": 1200}\n    ],\n    \"transitions\":\
        \ [\n        {\n            \"from_stage\": \"awareness\",\n            \"\
        to_stage\": \"consideration\",\n            \"conversion_rate\": 0.60,\n \
        \           \"user_count\": 1000,\n            \"avg_time_days\": 3.5\n  \
        \      }\n    ],\n    \"summary\": {\n        \"total_users\": 1000,\n   \
        \     \"biggest_gap_pp\": 15,\n        \"avg_gap_pp\": 10.5\n    }\n}\n```"
      operationId: get_funnel_analytics_external_admin_journey_funnel_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: date_from
        in: query
        required: false
        schema:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          description: Start date filter (ISO 8601)
          title: Date From
        description: Start date filter (ISO 8601)
      - name: date_to
        in: query
        required: false
        schema:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          description: End date filter (ISO 8601)
          title: Date To
        description: End date filter (ISO 8601)
      - name: segment
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: 'Cohort segment: all, top_20, bottom_80'
          title: Segment
        description: 'Cohort segment: all, top_20, bottom_80'
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunnelResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/transition/{from_stage}/{to_stage}:
    get:
      tags:
      - journey
      summary: Get Transition Detail
      description: "Get detailed metrics for a specific transition.\n\nProvides deeper\
        \ analysis than the funnel endpoint:\n- Time distribution (p25, median, p75)\n\
        - 30-day conversion trend\n- User lists (converted, pending, dropped)\n- Data\
        \ quality score\n\n**Example Response:**\n```json\n{\n    \"app_id\": \"mystica\"\
        ,\n    \"from_stage\": \"awareness\",\n    \"to_stage\": \"consideration\"\
        ,\n    \"metrics\": {\n        \"conversion_rate\": 0.60,\n        \"user_count\"\
        : 1000,\n        \"avg_time_days\": 3.5\n    },\n    \"time_distribution\"\
        : {\n        \"median_days\": 3.0,\n        \"p25_days\": 1.5,\n        \"\
        p75_days\": 7.0,\n        \"optimal_window\": \"< 7 days\"\n    },\n    \"\
        trend_30d\": [\n        {\"date\": \"2026-01-01\", \"rate\": 0.58},\n    \
        \    {\"date\": \"2026-01-02\", \"rate\": 0.61}\n    ],\n    \"data_quality\"\
        : 0.85\n}\n```"
      operationId: get_transition_detail_external_admin_journey_transition__from_stage___to_stage__get
      parameters:
      - name: from_stage
        in: path
        required: true
        schema:
          type: string
          title: From Stage
      - name: to_stage
        in: path
        required: true
        schema:
          type: string
          title: To Stage
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: date_from
        in: query
        required: false
        schema:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          description: Start date filter
          title: Date From
        description: Start date filter
      - name: date_to
        in: query
        required: false
        schema:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          description: End date filter
          title: Date To
        description: End date filter
      - name: include_users
        in: query
        required: false
        schema:
          type: boolean
          description: Include user ID lists
          default: false
          title: Include Users
        description: Include user ID lists
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TransitionDetailResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/bets:
    get:
      tags:
      - journey
      summary: List Bets
      description: "List bets for an application.\n\n**Filters:**\n- status: active,\
        \ paused, won, lost, cancelled\n- from_stage: Filter by source stage\n- to_stage:\
        \ Filter by target stage\n\n**Example Response:**\n```json\n{\n    \"bets\"\
        : [\n        {\n            \"id\": 1,\n            \"name\": \"Email Verification\
        \ Sprint\",\n            \"from_stage\": \"signup\",\n            \"to_stage\"\
        : \"email_verified\",\n            \"baseline_rate\": 0.45,\n            \"\
        goal_rate\": 0.65,\n            \"current_rate\": 0.52,\n            \"status\"\
        : \"active\"\n        }\n    ],\n    \"total\": 1\n}\n```"
      operationId: list_bets_external_admin_journey_bets_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: status
        in: query
        required: false
        schema:
          anyOf:
          - $ref: '#/components/schemas/BetStatus'
          - type: 'null'
          description: Filter by status
          title: Status
        description: Filter by status
      - name: from_stage
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by source stage
          title: From Stage
        description: Filter by source stage
      - name: to_stage
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by target stage
          title: To Stage
        description: Filter by target stage
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          maximum: 1000
          minimum: 1
          description: Maximum results
          default: 100
          title: Limit
        description: Maximum results
      - name: offset
        in: query
        required: false
        schema:
          type: integer
          minimum: 0
          description: Skip first N results
          default: 0
          title: Offset
        description: Skip first N results
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BetsListResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    post:
      tags:
      - journey
      summary: Create Bet
      description: "Create a new bet.\n\nA bet represents a probability-based experiment\
        \ targeting a\ntransition improvement. The goal is to move from baseline_rate\n\
        to goal_rate by the deadline.\n\n**Example Request:**\n```json\n{\n    \"\
        app_id\": \"mystica\",\n    \"name\": \"Email Verification Sprint\",\n   \
        \ \"description\": \"Improve email verification through reminder emails\"\
        ,\n    \"from_stage\": \"signup\",\n    \"to_stage\": \"email_verified\",\n\
        \    \"baseline_rate\": 0.45,\n    \"goal_rate\": 0.65,\n    \"expected_value\"\
        : 50000.00,\n    \"deadline\": \"2026-03-01T00:00:00Z\"\n}\n```"
      operationId: create_bet_external_admin_journey_bets_post
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BetCreate'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Bet'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/bets/summary:
    get:
      tags:
      - journey
      summary: Get Bets Summary
      description: "Get dashboard summary of bets for an application.\n\n**Example\
        \ Response:**\n```json\n{\n    \"total_bet_value\": 150000.00,\n    \"active_bets\"\
        : 5,\n    \"won_bets\": 12,\n    \"lost_bets\": 3,\n    \"avg_win_rate\":\
        \ 0.80,\n    \"projected_revenue\": 150000.00\n}\n```"
      operationId: get_bets_summary_external_admin_journey_bets_summary_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BetsSummary'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/bets/suggest:
    get:
      tags:
      - journey
      summary: Suggest Bet
      description: Get an AI-generated bet suggestion with confidence scoring.
      operationId: suggest_bet_external_admin_journey_bets_suggest_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: from_stage
        in: query
        required: true
        schema:
          type: string
          description: Source stage
          title: From Stage
        description: Source stage
      - name: to_stage
        in: query
        required: true
        schema:
          type: string
          description: Target stage
          title: To Stage
        description: Target stage
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BetSuggestion'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/bets/{bet_id}:
    get:
      tags:
      - journey
      summary: Get Bet
      description: "Get a bet by ID with progress metrics.\n\nReturns the bet details\
        \ plus computed progress:\n- progress_pct: Percentage toward goal\n- improvement_pp:\
        \ Percentage points improved\n- days_remaining: Days until deadline\n- status_indicator:\
        \ on_track, behind, ahead, at_risk\n\n**Example Response:**\n```json\n{\n\
        \    \"id\": 1,\n    \"name\": \"Email Verification Sprint\",\n    \"baseline_rate\"\
        : 0.45,\n    \"goal_rate\": 0.65,\n    \"current_rate\": 0.52,\n    \"progress\"\
        : {\n        \"progress_pct\": 35.0,\n        \"improvement_pp\": 7.0,\n \
        \       \"days_remaining\": 28,\n        \"status_indicator\": \"on_track\"\
        \n    }\n}\n```"
      operationId: get_bet_external_admin_journey_bets__bet_id__get
      parameters:
      - name: bet_id
        in: path
        required: true
        schema:
          type: integer
          title: Bet Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BetWithProgress'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    patch:
      tags:
      - journey
      summary: Update Bet
      description: "Update a bet.\n\nAll fields are optional. Only provided fields\
        \ will be updated.\n\n**Example Request:**\n```json\n{\n    \"name\": \"Email\
        \ Verification Sprint v2\",\n    \"current_rate\": 0.55,\n    \"status\":\
        \ \"paused\"\n}\n```"
      operationId: update_bet_external_admin_journey_bets__bet_id__patch
      parameters:
      - name: bet_id
        in: path
        required: true
        schema:
          type: integer
          title: Bet Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BetUpdate'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Bet'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    delete:
      tags:
      - journey
      summary: Delete Bet
      description: 'Cancel a bet (soft delete).


        Sets the bet status to ''cancelled''. The bet data is preserved

        for historical analysis.'
      operationId: delete_bet_external_admin_journey_bets__bet_id__delete
      parameters:
      - name: bet_id
        in: path
        required: true
        schema:
          type: integer
          title: Bet Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '204':
          description: Successful Response
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/bets/{bet_id}/resolve:
    post:
      tags:
      - journey
      summary: Resolve Bet
      description: "Resolve a bet (mark as won or lost).\n\n**Example Request:**\n\
        ```json\n{\n    \"outcome\": \"won\",\n    \"notes\": \"Achieved 68% conversion\
        \ rate, exceeding goal\",\n    \"actual_value\": 62000.00\n}\n```"
      operationId: resolve_bet_external_admin_journey_bets__bet_id__resolve_post
      parameters:
      - name: bet_id
        in: path
        required: true
        schema:
          type: integer
          title: Bet Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BetResolve'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Bet'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/bets/refresh-rates:
    post:
      tags:
      - journey
      summary: Refresh Bet Rates
      description: "Refresh current_rate for all active bets in an application.\n\n\
        This recalculates current_rate based on the latest funnel data.\nShould be\
        \ called periodically or after significant data changes.\n\n**Returns:**\n\
        ```json\n{\n    \"updated_count\": 5,\n    \"app_id\": \"mystica\"\n}\n```"
      operationId: refresh_bet_rates_external_admin_journey_bets_refresh_rates_post
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/bets/{bet_id}/episodes:
    get:
      tags:
      - journey
      summary: Get Bet Episodes
      description: "Get episodes linked to a bet.\n\nReturns all episodes that have\
        \ been linked to this bet as supporting evidence.\n\n**Example Response:**\n\
        ```json\n{\n    \"episodes\": [\n        {\n            \"id\": 123,\n   \
        \         \"user_id\": \"user_456\",\n            \"app_id\": \"mystica\"\
        ,\n            \"customer_journey_stage\": \"active_looking\",\n         \
        \   \"raw_input\": \"User feedback content...\",\n            \"created_at\"\
        : \"2026-01-15T10:30:00Z\",\n            \"archetype_id\": \"crisis_stabilizer\"\
        ,\n            \"key_themes\": [\"frustration\", \"urgency\"],\n         \
        \   \"linked_at\": \"2026-02-01T14:00:00Z\",\n            \"linked_by\": \"\
        agent\"\n        }\n    ],\n    \"total\": 1\n}\n```"
      operationId: get_bet_episodes_external_admin_journey_bets__bet_id__episodes_get
      parameters:
      - name: bet_id
        in: path
        required: true
        schema:
          type: integer
          title: Bet Id
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          maximum: 500
          minimum: 1
          description: Maximum episodes
          default: 100
          title: Limit
        description: Maximum episodes
      - name: offset
        in: query
        required: false
        schema:
          type: integer
          minimum: 0
          description: Pagination offset
          default: 0
          title: Offset
        description: Pagination offset
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BetEpisodesResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    post:
      tags:
      - journey
      summary: Link Episode To Bet
      description: "Link an episode to a bet as supporting evidence.\n\n**Example\
        \ Request:**\n```json\n{\n    \"episode_id\": 123\n}\n```\n\n**Example Response:**\n\
        ```json\n{\n    \"status\": \"linked\",\n    \"bet_id\": 1,\n    \"episode_id\"\
        : 123\n}\n```"
      operationId: link_episode_to_bet_external_admin_journey_bets__bet_id__episodes_post
      parameters:
      - name: bet_id
        in: path
        required: true
        schema:
          type: integer
          title: Bet Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BetEpisodeLinkCreate'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/bets/{bet_id}/episodes/{episode_id}:
    delete:
      tags:
      - journey
      summary: Unlink Episode From Bet
      description: "Unlink an episode from a bet.\n\n**Example Response:**\n```json\n\
        {\n    \"status\": \"unlinked\",\n    \"bet_id\": 1,\n    \"episode_id\":\
        \ 123\n}\n```"
      operationId: unlink_episode_from_bet_external_admin_journey_bets__bet_id__episodes__episode_id__delete
      parameters:
      - name: bet_id
        in: path
        required: true
        schema:
          type: integer
          title: Bet Id
      - name: episode_id
        in: path
        required: true
        schema:
          type: integer
          title: Episode Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/bets/{bet_id}/episodes/count:
    get:
      tags:
      - journey
      summary: Get Bet Episode Count
      description: "Get count of episodes linked to a bet.\n\n**Example Response:**\n\
        ```json\n{\n    \"bet_id\": 1,\n    \"episode_count\": 5\n}\n```"
      operationId: get_bet_episode_count_external_admin_journey_bets__bet_id__episodes_count_get
      parameters:
      - name: bet_id
        in: path
        required: true
        schema:
          type: integer
          title: Bet Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/users/{user_id}/jtbd:
    get:
      tags:
      - journey
      summary: Get User Jtbd Phases
      description: "Get JTBD phases for a user.\n\nReturns all phases the user has\
        \ been through, their current phase,\nand summary metrics for each phase.\n\
        \n**JTBD Phases:**\n1. First Thought - Initial awareness\n2. Passive Looking\
        \ - Research mode\n3. Active Looking - Comparison shopping\n4. Deciding -\
        \ Purchase decision\n5. Experiencing - Post-purchase usage\n6. Looking Back\
        \ - Reflection/renewal\n\n**Example Response:**\n```json\n{\n    \"user_id\"\
        : \"user_123\",\n    \"app_id\": \"mystica\",\n    \"current_phase\": \"active_looking\"\
        ,\n    \"phases\": [\n        {\n            \"phase\": \"first_thought\"\
        ,\n            \"phase_name\": \"First Thought\",\n            \"entered_at\"\
        : \"2026-01-01\",\n            \"episode_count\": 5,\n            \"duration_days\"\
        : 3\n        }\n    ]\n}\n```"
      operationId: get_user_jtbd_phases_external_admin_journey_users__user_id__jtbd_get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserJTBDPhases'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/users/{user_id}/jtbd/{phase}:
    get:
      tags:
      - journey
      summary: Get User Jtbd Phase Detail
      description: "Get detailed JTBD analysis for a specific phase.\n\nIncludes force\
        \ analysis, attention policy, solutions considered,\nand expressed beliefs.\n\
        \n**Forces (JTBD Framework):**\n- **Push**: Pain pushing away from current\
        \ situation\n- **Pull**: Desire pulling toward new solution\n- **Habit**:\
        \ Inertia from existing behaviors\n- **Anxiety**: Fear and uncertainty about\
        \ change\n\n**Example Response:**\n```json\n{\n    \"user_id\": \"user_123\"\
        ,\n    \"phase\": \"first_thought\",\n    \"phase_name\": \"First Thought\"\
        ,\n    \"job_type\": \"Emotional: Managing uncertainty\",\n    \"attention_policy\"\
        : {\n        \"summary\": \"Focused on: understanding options\",\n       \
        \ \"focus_areas\": [\"research\", \"comparison\"],\n        \"quotes\": [\"\
        I need to figure this out\"]\n    },\n    \"forces\": {\n        \"push\"\
        : {\n            \"summary\": \"Expressed frustration in 3 areas\",\n    \
        \        \"strength\": 0.75,\n            \"evidence\": [\"tired of current\
        \ situation\"]\n        },\n        \"pull\": {\n            \"summary\":\
        \ \"Shows interest in 2 desired outcomes\",\n            \"strength\": 0.60,\n\
        \            \"evidence\": [\"want to improve\"]\n        },\n        \"net_motivation\"\
        : 0.35,\n        \"dominant_force\": \"push\"\n    }\n}\n```"
      operationId: get_user_jtbd_phase_detail_external_admin_journey_users__user_id__jtbd__phase__get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: phase
        in: path
        required: true
        schema:
          $ref: '#/components/schemas/JTBDPhase'
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/JTBDPhaseDetail'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/cohorts:
    get:
      tags:
      - journey
      summary: Get Cohort Segments
      description: "Segment users by a metric percentile.\n\n**Metrics:**\n- **ltv**:\
        \ Customer lifetime value (or proxy)\n- **engagement**: Activity level (episode\
        \ count weighted by recency)\n- **conversion**: Speed through funnel (faster\
        \ = higher)\n\n**Example Response:**\n```json\n{\n    \"app_id\": \"mystica\"\
        ,\n    \"metric\": \"ltv\",\n    \"percentile\": 20,\n    \"threshold_value\"\
        : 500.00,\n    \"segments\": {\n        \"top\": {\n            \"user_count\"\
        : 58,\n            \"avg_value\": 850.00,\n            \"conversion_rate\"\
        : 0.72\n        },\n        \"bottom\": {\n            \"user_count\": 235,\n\
        \            \"avg_value\": 120.00,\n            \"conversion_rate\": 0.38\n\
        \        }\n    }\n}\n```"
      operationId: get_cohort_segments_external_admin_journey_cohorts_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: metric
        in: query
        required: false
        schema:
          type: string
          description: 'Segmentation metric: ltv, engagement, or conversion'
          default: ltv
          title: Metric
        description: 'Segmentation metric: ltv, engagement, or conversion'
      - name: percentile
        in: query
        required: false
        schema:
          type: integer
          maximum: 99
          minimum: 1
          description: Percentile cutoff (e.g., 20 for top 20%)
          default: 20
          title: Percentile
        description: Percentile cutoff (e.g., 20 for top 20%)
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CohortResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/cohorts/compare:
    get:
      tags:
      - journey
      summary: Compare Cohorts
      description: "Compare top vs bottom cohorts for a specific transition.\n\nShows\
        \ the conversion rate and timing gap between high-value\nand low-value user\
        \ segments.\n\n**Example Response:**\n```json\n{\n    \"app_id\": \"mystica\"\
        ,\n    \"metric\": \"ltv\",\n    \"from_stage\": \"awareness\",\n    \"to_stage\"\
        : \"consideration\",\n    \"top_segment\": {\n        \"user_count\": 58,\n\
        \        \"conversion_rate\": 0.72,\n        \"avg_time_days\": 2.1\n    },\n\
        \    \"bottom_segment\": {\n        \"user_count\": 235,\n        \"conversion_rate\"\
        : 0.38,\n        \"avg_time_days\": 8.5\n    },\n    \"gap\": {\n        \"\
        conversion_pp\": 34,\n        \"time_days\": 6.4\n    }\n}\n```"
      operationId: compare_cohorts_external_admin_journey_cohorts_compare_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: metric
        in: query
        required: false
        schema:
          type: string
          description: Segmentation metric
          default: ltv
          title: Metric
        description: Segmentation metric
      - name: from_stage
        in: query
        required: true
        schema:
          type: string
          description: Source stage
          title: From Stage
        description: Source stage
      - name: to_stage
        in: query
        required: true
        schema:
          type: string
          description: Target stage
          title: To Stage
        description: Target stage
      - name: percentile
        in: query
        required: false
        schema:
          type: integer
          maximum: 99
          minimum: 1
          description: Percentile cutoff
          default: 20
          title: Percentile
        description: Percentile cutoff
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CohortCompareResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/cohorts/users:
    get:
      tags:
      - journey
      summary: Get Cohort Users
      description: "Get user IDs in a cohort segment.\n\nUseful for drilling down\
        \ into specific segments or\nrunning targeted campaigns.\n\n**Returns:**\n\
        ```json\n{\n    \"app_id\": \"mystica\",\n    \"metric\": \"ltv\",\n    \"\
        segment\": \"top\",\n    \"user_ids\": [\"user_1\", \"user_2\", \"user_3\"\
        ],\n    \"total\": 58\n}\n```"
      operationId: get_cohort_users_external_admin_journey_cohorts_users_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: metric
        in: query
        required: false
        schema:
          type: string
          description: Segmentation metric
          default: ltv
          title: Metric
        description: Segmentation metric
      - name: percentile
        in: query
        required: false
        schema:
          type: integer
          maximum: 99
          minimum: 1
          description: Percentile cutoff
          default: 20
          title: Percentile
        description: Percentile cutoff
      - name: segment
        in: query
        required: true
        schema:
          type: string
          description: 'Segment: top or bottom'
          title: Segment
        description: 'Segment: top or bottom'
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          maximum: 1000
          minimum: 1
          description: Maximum users to return
          default: 100
          title: Limit
        description: Maximum users to return
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/tools:
    get:
      tags:
      - journey
      summary: List Journey Tools
      description: "List available journey dashboard tools for agent use.\n\n**Formats:**\n\
        - **standard**: Full tool definitions with endpoints\n- **claude**: Claude\
        \ API tool_use format\n\n**Approval Levels:**\n- **auto**: Read-only tools,\
        \ executed immediately\n- **confirm**: Write tools, require user confirmation\n\
        \n**Example Response (standard):**\n```json\n{\n    \"tools\": [\n       \
        \ {\n            \"name\": \"get_funnel\",\n            \"description\": \"\
        Get the customer journey funnel...\",\n            \"parameters\": {...},\n\
        \            \"endpoint\": \"/external/admin/journey/funnel\",\n         \
        \   \"method\": \"GET\",\n            \"approval\": \"auto\"\n        }\n\
        \    ],\n    \"total\": 15\n}\n```"
      operationId: list_journey_tools_external_admin_journey_tools_get
      parameters:
      - name: format
        in: query
        required: false
        schema:
          type: string
          description: 'Format: standard or claude'
          default: standard
          title: Format
        description: 'Format: standard or claude'
      - name: approval
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: 'Filter by approval level: auto or confirm'
          title: Approval
        description: 'Filter by approval level: auto or confirm'
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/tools/{tool_name}:
    get:
      tags:
      - journey
      summary: Get Journey Tool
      description: 'Get a specific tool definition by name.


        Returns the full tool definition including parameters,

        endpoint, and approval level.'
      operationId: get_journey_tool_external_admin_journey_tools__tool_name__get
      parameters:
      - name: tool_name
        in: path
        required: true
        schema:
          type: string
          title: Tool Name
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/transition/{from_stage}/{to_stage}/statistics:
    get:
      tags:
      - journey
      summary: Get Transition Statistics
      description: "Get statistical analysis of a transition gap.\n\nReturns p-value,\
        \ confidence interval, sample sizes, LTV correlation,\nand data quality score\
        \ for the gap between top 20% and bottom 80%.\n\n**Example Response:**\n```json\n\
        {\n    \"p_value\": 0.0001,\n    \"is_significant\": true,\n    \"significance_label\"\
        : \"Statistically significant\",\n    \"confidence_interval_low\": 5.2,\n\
        \    \"confidence_interval_high\": 12.8,\n    \"sample_size_top\": 200,\n\
        \    \"sample_size_bottom\": 800,\n    \"sample_size_total\": 1000,\n    \"\
        ltv_correlation\": 0.65,\n    \"ltv_correlation_label\": \"Moderate\",\n \
        \   \"data_quality_score\": 0.85,\n    \"data_quality_label\": \"High confidence\"\
        \n}\n```"
      operationId: get_transition_statistics_external_admin_journey_transition__from_stage___to_stage__statistics_get
      parameters:
      - name: from_stage
        in: path
        required: true
        schema:
          type: string
          title: From Stage
      - name: to_stage
        in: path
        required: true
        schema:
          type: string
          title: To Stage
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/StatisticalEvidence'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/transition/{from_stage}/{to_stage}/insights:
    get:
      tags:
      - journey
      summary: Get Transition Insights
      description: "Get AI-generated insights for a transition gap.\n\nGenerates causal\
        \ narrative insights that explain why users\nstruggle at this transition,\
        \ which archetypes are affected,\nand what opportunities exist for improvement.\n\
        \n**Example Response:**\n```json\n{\n    \"app_id\": \"mystica\",\n    \"\
        from_stage\": \"first_thought\",\n    \"to_stage\": \"passive_looking\",\n\
        \    \"insights\": [{\n        \"id\": \"ins_abc123\",\n        \"archetype_id\"\
        : \"crisis_stabilizer\",\n        \"archetype_name\": \"Crisis Stabilizer\"\
        ,\n        \"title\": \"Crisis Stabilizers struggle with initial complexity\"\
        ,\n        \"description\": \"Users in the Crisis Stabilizer archetype show\
        \ 25% lower conversion...\",\n        \"causal_mechanism\": {\n          \
        \  \"steps\": [\n                {\"label\": \"Many options shown\"},\n  \
        \              {\"label\": \"Decision paralysis\"},\n                {\"label\"\
        : \"Abandonment\"}\n            ],\n            \"summary\": \"Overwhelmed\
        \ users abandon before taking action\"\n        },\n        \"evidence\":\
        \ {\n            \"episode_count\": 47,\n            \"confidence\": 0.85,\n\
        \            \"sample_quotes\": [\"I felt overwhelmed by all the choices...\"\
        ]\n        },\n        \"opportunity\": {\n            \"value_usd\": 24500,\n\
        \            \"target_improvement_pp\": 8,\n            \"hypothesis\": \"\
        Reducing initial choices will increase conversion\",\n            \"suggested_actions\"\
        : [\"Simplify onboarding\", \"Add guided path\"]\n        }\n    }],\n   \
        \ \"primary_insight\": {...},\n    \"generated_at\": \"2026-02-04T08:00:00Z\"\
        \n}\n```"
      operationId: get_transition_insights_external_admin_journey_transition__from_stage___to_stage__insights_get
      parameters:
      - name: from_stage
        in: path
        required: true
        schema:
          type: string
          title: From Stage
      - name: to_stage
        in: path
        required: true
        schema:
          type: string
          title: To Stage
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TransitionInsightResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/conversation/{from_stage}/{to_stage}:
    get:
      tags:
      - journey
      summary: Get Conversation Context
      description: "Get conversation history for a transition.\n\nReturns the conversation\
        \ context with message history for\nthe specified transition. Creates a new\
        \ conversation if none exists.\n\n**Example Response:**\n```json\n{\n    \"\
        id\": 1,\n    \"app_id\": \"mystica\",\n    \"from_stage\": \"signup\",\n\
        \    \"to_stage\": \"verified\",\n    \"title\": \"signup → verified Analysis\"\
        ,\n    \"summary\": \"Found significant 21pp gap...\",\n    \"message_count\"\
        : 5,\n    \"messages\": [\n        {\"role\": \"user\", \"content\": \"Why\
        \ is conversion low?\"},\n        {\"role\": \"assistant\", \"content\": \"\
        The data shows...\"}\n    ]\n}\n```"
      operationId: get_conversation_context_external_admin_journey_conversation__from_stage___to_stage__get
      parameters:
      - name: from_stage
        in: path
        required: true
        schema:
          type: string
          title: From Stage
      - name: to_stage
        in: path
        required: true
        schema:
          type: string
          title: To Stage
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: max_messages
        in: query
        required: false
        schema:
          type: integer
          maximum: 100
          minimum: 1
          description: Maximum messages to return
          default: 20
          title: Max Messages
        description: Maximum messages to return
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TransitionConversationWithMessages'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/conversation/{from_stage}/{to_stage}/messages:
    post:
      tags:
      - journey
      summary: Add Conversation Message
      description: "Add a message to the conversation for a transition.\n\n**Example\
        \ Request:**\n```json\n{\n    \"role\": \"assistant\",\n    \"content\": \"\
        Based on my analysis...\",\n    \"metadata\": {\"tool_name\": \"get_transition_statistics\"\
        }\n}\n```"
      operationId: add_conversation_message_external_admin_journey_conversation__from_stage___to_stage__messages_post
      parameters:
      - name: from_stage
        in: path
        required: true
        schema:
          type: string
          title: From Stage
      - name: to_stage
        in: path
        required: true
        schema:
          type: string
          title: To Stage
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ConversationMessageCreate'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/conversations:
    get:
      tags:
      - journey
      summary: List Conversations
      description: List all conversations for an application.
      operationId: list_conversations_external_admin_journey_conversations_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          maximum: 100
          minimum: 1
          description: Maximum conversations
          default: 50
          title: Limit
        description: Maximum conversations
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ConversationListResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/conversation/{from_stage}/{to_stage}/summary:
    patch:
      tags:
      - journey
      summary: Update Conversation Summary
      description: Update the AI-generated summary of a conversation.
      operationId: update_conversation_summary_external_admin_journey_conversation__from_stage___to_stage__summary_patch
      parameters:
      - name: from_stage
        in: path
        required: true
        schema:
          type: string
          title: From Stage
      - name: to_stage
        in: path
        required: true
        schema:
          type: string
          title: To Stage
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: summary
        in: query
        required: true
        schema:
          type: string
          description: Summary text
          title: Summary
        description: Summary text
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/archetypes:
    get:
      tags:
      - journey
      summary: Get Archetype Definitions
      description: 'Get all archetype definitions.


        Returns JTBD-derived archetypes with criteria and recommended approaches.'
      operationId: get_archetype_definitions_external_admin_journey_archetypes_get
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/users/{user_id}/archetype:
    get:
      tags:
      - journey
      summary: Classify User Archetype
      description: "Classify a user into an archetype.\n\n**Example Response:**\n\
        ```json\n{\n    \"user_id\": \"user123\",\n    \"app_id\": \"mystica\",\n\
        \    \"archetype_id\": \"crisis_stabilizer\",\n    \"archetype_name\": \"\
        Crisis Stabilizer\",\n    \"confidence\": 0.85,\n    \"matching_criteria\"\
        : [\"crisis_language\", \"urgency\"]\n}\n```"
      operationId: classify_user_archetype_external_admin_journey_users__user_id__archetype_get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: force_recalculate
        in: query
        required: false
        schema:
          type: boolean
          description: Recalculate even if cached
          default: false
          title: Force Recalculate
        description: Recalculate even if cached
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserArchetype'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/archetypes/distribution:
    get:
      tags:
      - journey
      summary: Get Archetype Distribution
      description: Get distribution of archetypes across users.
      operationId: get_archetype_distribution_external_admin_journey_archetypes_distribution_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: from_stage
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by source stage
          title: From Stage
        description: Filter by source stage
      - name: to_stage
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by target stage
          title: To Stage
        description: Filter by target stage
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ArchetypeDistribution'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/bets/confidence:
    get:
      tags:
      - journey
      summary: Get Bet Confidence
      description: "Calculate confidence score for a potential bet.\n\nUses weighted\
        \ factors: significance (30%), sample size (25%),\ndata quality (20%), historical\
        \ win rate (15%), CI width (10%).\n\n**Example Response:**\n```json\n{\n \
        \   \"overall_score\": 0.78,\n    \"confidence_label\": \"High\",\n    \"\
        factors\": {\n        \"significance_score\": 0.9,\n        \"sample_size_score\"\
        : 0.8,\n        \"data_quality_score\": 0.85,\n        \"historical_win_rate\"\
        : 0.7,\n        \"ci_width_score\": 0.75\n    },\n    \"recommendation\":\
        \ \"Strong statistical evidence...\",\n    \"warnings\": []\n}\n```"
      operationId: get_bet_confidence_external_admin_journey_bets_confidence_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: from_stage
        in: query
        required: true
        schema:
          type: string
          description: Source stage
          title: From Stage
        description: Source stage
      - name: to_stage
        in: query
        required: true
        schema:
          type: string
          description: Target stage
          title: To Stage
        description: Target stage
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BetConfidenceScore'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/episodes:
    get:
      tags:
      - journey
      summary: List Episodes
      description: List episodes with optional filtering.
      operationId: list_episodes_external_admin_journey_episodes_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: user_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by user
          title: User Id
        description: Filter by user
      - name: stage
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by journey stage
          title: Stage
        description: Filter by journey stage
      - name: archetype_id
        in: query
        required: false
        schema:
          anyOf:
          - $ref: '#/components/schemas/ArchetypeId'
          - type: 'null'
          description: Filter by archetype
          title: Archetype Id
        description: Filter by archetype
      - name: date_from
        in: query
        required: false
        schema:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          description: Start date
          title: Date From
        description: Start date
      - name: date_to
        in: query
        required: false
        schema:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          description: End date
          title: Date To
        description: End date
      - name: search_text
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Search in content
          title: Search Text
        description: Search in content
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          maximum: 200
          minimum: 1
          description: Maximum episodes
          default: 50
          title: Limit
        description: Maximum episodes
      - name: offset
        in: query
        required: false
        schema:
          type: integer
          minimum: 0
          description: Pagination offset
          default: 0
          title: Offset
        description: Pagination offset
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/EpisodeListResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/episodes/{episode_id}:
    get:
      tags:
      - journey
      summary: Get Episode
      description: Get a single episode by ID.
      operationId: get_episode_external_admin_journey_episodes__episode_id__get
      parameters:
      - name: episode_id
        in: path
        required: true
        schema:
          type: integer
          title: Episode Id
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/src__models__journey__JourneyEpisode'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/episodes/summary:
    get:
      tags:
      - journey
      summary: Get Episode Summary
      description: Get summary statistics for episodes.
      operationId: get_episode_summary_external_admin_journey_episodes_summary_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: stage
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by stage
          title: Stage
        description: Filter by stage
      - name: user_id
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by user
          title: User Id
        description: Filter by user
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/EpisodeSummary'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/prompts:
    get:
      tags:
      - journey
      summary: List Prompt Templates
      description: List all available prompt templates.
      operationId: list_prompt_templates_external_admin_journey_prompts_get
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PromptListResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/prompts/{template_id}:
    get:
      tags:
      - journey
      summary: Get Prompt Template
      description: Get a specific prompt template.
      operationId: get_prompt_template_external_admin_journey_prompts__template_id__get
      parameters:
      - name: template_id
        in: path
        required: true
        schema:
          type: string
          title: Template Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PromptTemplate'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/prompts/{template_id}/render:
    post:
      tags:
      - journey
      summary: Render Prompt Template
      description: "Render a prompt template with context values.\n\n**Example Request:**\n\
        ```json\n{\n    \"app_id\": \"mystica\",\n    \"from_stage\": \"signup\",\n\
        \    \"to_stage\": \"verified\"\n}\n```"
      operationId: render_prompt_template_external_admin_journey_prompts__template_id__render_post
      parameters:
      - name: template_id
        in: path
        required: true
        schema:
          type: string
          title: Template Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: true
              title: Context
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/journey/prompts/suggest:
    post:
      tags:
      - journey
      summary: Get Suggested Prompts
      description: Get suggested prompts based on current context.
      operationId: get_suggested_prompts_external_admin_journey_prompts_suggest_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: true
              title: Context
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/episodes/aggregate:
    post:
      tags:
      - analytics
      summary: Aggregate Episodes
      description: 'Aggregate episodes by metadata fields with GROUP BY.


        Supports grouping by: event_type, ad_hook, ad_story, ad_close,

        traffic_source, customer_journey_stage, domain_id.


        Metrics: count, unique_users.

        Filters: any dimension as equality filter, plus date_from/date_to.'
      operationId: aggregate_episodes_external_analytics_episodes_aggregate_post
      parameters:
      - name: format
        in: query
        required: false
        schema:
          enum:
          - json
          - csv
          type: string
          description: Response format
          default: json
          title: Format
        description: Response format
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AggregateRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AggregateResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/users/{user_id}/journey:
    get:
      tags:
      - analytics
      summary: Get User Journey
      description: 'Get full episode timeline for a user with stage transitions.


        Returns episodes in chronological order, detected JTBD stage

        transitions with duration, and optional behavioral signals

        (ad_velocity, purchase_count, has_chat, etc.).'
      operationId: get_user_journey_external_analytics_users__user_id__journey_get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: include_signals
        in: query
        required: false
        schema:
          type: boolean
          description: Include behavioral signals
          default: false
          title: Include Signals
        description: Include behavioral signals
      - name: max_episodes
        in: query
        required: false
        schema:
          type: integer
          maximum: 50000
          description: 'Maximum episodes to return (default: all)'
          title: Max Episodes
        description: 'Maximum episodes to return (default: all)'
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/JourneyResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/episodes/metadata:
    post:
      tags:
      - analytics
      summary: Aggregate Metadata
      description: 'Aggregate episodes by a metadata field with optional cross-tabulation.


        Focused on metadata exploration: group by a single metadata field

        (e.g., ad_hook) with optional second dimension for cross-tabulation

        (e.g., customer_journey_stage).'
      operationId: aggregate_metadata_external_analytics_episodes_metadata_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MetadataAggregateRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MetadataAggregateResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/cohorts/segment:
    post:
      tags:
      - analytics
      summary: Segment Cohorts
      description: 'Segment users by metric percentile with optional metadata/date
        filters.


        Splits users into top N% vs bottom (100-N)% by LTV, engagement,

        or conversion speed. Supports filtering by any metadata dimension

        (ad_hook, traffic_source, etc.) and date ranges.'
      operationId: segment_cohorts_external_analytics_cohorts_segment_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CohortSegmentRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CohortResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/cohorts/profile:
    post:
      tags:
      - analytics
      summary: Profile Cohorts
      description: 'Profile metadata fields across top/bottom cohort segments with
        whale index.


        The whale index shows how much more prevalent a metadata value is in

        the top segment vs the bottom. E.g., whale_index=11 for "spiritual"

        ad_hook means it appears 11x more often in top 20% LTV users.'
      operationId: profile_cohorts_external_analytics_cohorts_profile_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CohortProfileRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CohortProfileResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/cohorts/compare:
    post:
      tags:
      - analytics
      summary: Compare Cohorts
      description: 'Compare top vs bottom cohorts for a specific stage transition.


        Shows conversion rate and time differences between segments for

        a given from_stage → to_stage transition, with optional filters.'
      operationId: compare_cohorts_external_analytics_cohorts_compare_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CohortCompareRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CohortCompareResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/cohorts/users:
    get:
      tags:
      - analytics
      summary: Get Cohort Users
      description: 'List user IDs in a cohort segment for targeting or export.


        Returns user IDs belonging to the top or bottom segment,

        sorted by metric value descending.'
      operationId: get_cohort_users_external_analytics_cohorts_users_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: metric
        in: query
        required: false
        schema:
          type: string
          description: ltv, engagement, or conversion
          default: ltv
          title: Metric
        description: ltv, engagement, or conversion
      - name: percentile
        in: query
        required: false
        schema:
          type: integer
          maximum: 99
          minimum: 1
          description: Percentile cutoff
          default: 20
          title: Percentile
        description: Percentile cutoff
      - name: segment
        in: query
        required: false
        schema:
          type: string
          description: 'Segment: ''top'' or ''bottom'''
          default: top
          title: Segment
        description: 'Segment: ''top'' or ''bottom'''
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          maximum: 10000
          description: Maximum users to return
          default: 100
          title: Limit
        description: Maximum users to return
      - name: format
        in: query
        required: false
        schema:
          enum:
          - json
          - csv
          type: string
          description: Response format
          default: json
          title: Format
        description: Response format
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CohortUsersResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/archetypes:
    get:
      tags:
      - analytics
      summary: Get Archetypes
      description: 'List all archetype definitions.


        Returns JTBD-derived archetypes with criteria and recommended approaches.'
      operationId: get_archetypes_external_analytics_archetypes_get
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/archetypes/distribution:
    get:
      tags:
      - analytics
      summary: Get Archetype Distribution
      description: 'Get distribution of archetypes across users.


        Returns counts and percentages per archetype, optionally filtered

        by stage transition.'
      operationId: get_archetype_distribution_external_analytics_archetypes_distribution_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: from_stage
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by source stage
          title: From Stage
        description: Filter by source stage
      - name: to_stage
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: Filter by target stage
          title: To Stage
        description: Filter by target stage
      - name: format
        in: query
        required: false
        schema:
          enum:
          - json
          - csv
          type: string
          description: Response format
          default: json
          title: Format
        description: Response format
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ArchetypeDistribution'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/users/{user_id}/archetype:
    get:
      tags:
      - analytics
      summary: Get User Archetype
      description: 'Classify a user into an archetype based on behavioral data.


        Returns the best-matching archetype with confidence score and

        matching criteria. Returns 404 if insufficient data for classification.'
      operationId: get_user_archetype_external_analytics_users__user_id__archetype_get
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserArchetype'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/funnel:
    get:
      tags:
      - analytics
      summary: Get Funnel
      description: 'Get funnel conversion metrics for an application.


        Returns stage metrics (user/episode counts) and transition conversion rates

        with optional cohort segmentation and date filtering.'
      operationId: get_funnel_external_analytics_funnel_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: date_from
        in: query
        required: false
        schema:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          description: Start date filter (ISO 8601)
          title: Date From
        description: Start date filter (ISO 8601)
      - name: date_to
        in: query
        required: false
        schema:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          description: End date filter (ISO 8601)
          title: Date To
        description: End date filter (ISO 8601)
      - name: segment
        in: query
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          description: 'Cohort segment: all, top_20, bottom_80'
          title: Segment
        description: 'Cohort segment: all, top_20, bottom_80'
      - name: format
        in: query
        required: false
        schema:
          enum:
          - json
          - csv
          type: string
          description: Response format
          default: json
          title: Format
        description: Response format
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FunnelResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/funnel/transition/{from_stage}/{to_stage}:
    get:
      tags:
      - analytics
      summary: Get Funnel Transition Detail
      description: 'Get detailed metrics for a specific funnel transition.


        Provides time distribution (p25/median/p75), 30-day conversion trend,

        statistical evidence for cohort gaps, and optional user lists.'
      operationId: get_funnel_transition_detail_external_analytics_funnel_transition__from_stage___to_stage__get
      parameters:
      - name: from_stage
        in: path
        required: true
        schema:
          type: string
          title: From Stage
      - name: to_stage
        in: path
        required: true
        schema:
          type: string
          title: To Stage
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: date_from
        in: query
        required: false
        schema:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          description: Start date filter (ISO 8601)
          title: Date From
        description: Start date filter (ISO 8601)
      - name: date_to
        in: query
        required: false
        schema:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          description: End date filter (ISO 8601)
          title: Date To
        description: End date filter (ISO 8601)
      - name: include_users
        in: query
        required: false
        schema:
          type: boolean
          description: Include user ID lists
          default: false
          title: Include Users
        description: Include user ID lists
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TransitionDetailResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/alignment/batch:
    post:
      tags:
      - analytics
      summary: Batch Alignment Score
      description: 'Batch alignment scoring for multiple stakeholders.


        Read-only: scores content against each target''s observation contexts.

        No episodes or beliefs created. Uses context-delta relevance scoring.'
      operationId: batch_alignment_score_external_analytics_alignment_batch_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BatchAlignmentRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BatchAlignmentResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/alignment/cohort:
    post:
      tags:
      - analytics
      summary: Cohort Alignment Score
      description: 'Cohort-based alignment scoring using journey spec set_points.


        Builds synthetic observation contexts from the journey spec''s per-stage

        set_points and scores content against each stage. Optionally weights

        by funnel user counts.'
      operationId: cohort_alignment_score_external_analytics_alignment_cohort_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CohortAlignmentRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CohortAlignmentResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/evidence/{self_model_id}/{context_id}:
    get:
      tags:
      - analytics
      summary: Get Context Evidence
      description: 'Get evidence chain for an observation context: context → beliefs
        → evidence (source_spans).


        Returns all beliefs for this context organized in a belief-first hierarchy.

        Each belief includes its evidence_source (''curated'', ''llm_extraction'',
        or legacy None)

        and any source_spans from transcript episodes.'
      operationId: get_context_evidence_external_analytics_evidence__self_model_id___context_id__get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: context_id
        in: path
        required: true
        schema:
          type: string
          title: Context Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/analytics/residuals/{self_model_id}:
    get:
      tags:
      - analytics
      summary: Get Residuals
      description: 'Compute residuals from coded observations and detect learning
        gaps (PR-H).


        Maps coding accuracy judgments to objective residual components,

        detects lacunae (high-residual contexts), and suggests evidence to collect.'
      operationId: get_residuals_external_analytics_residuals__self_model_id__get
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: stakeholder_name
        in: query
        required: true
        schema:
          type: string
          description: Stakeholder name to compute residuals for
          title: Stakeholder Name
        description: Stakeholder name to compute residuals for
      - name: min_codings
        in: query
        required: false
        schema:
          type: integer
          description: Minimum codings per context to include
          default: 3
          title: Min Codings
        description: Minimum codings per context to include
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/recommendations:
    post:
      tags:
      - recommendations
      summary: Create Recommendation
      description: Create a new recommendation prediction.
      operationId: create_recommendation_external_recommendations_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RecommendationCreate'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Recommendation'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    get:
      tags:
      - recommendations
      summary: List Recommendations
      description: List recommendations with optional filters.
      operationId: list_recommendations_external_recommendations_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: status
        in: query
        required: false
        schema:
          type: string
          description: 'Filter by status: active, resolved, cancelled'
          title: Status
        description: 'Filter by status: active, resolved, cancelled'
      - name: limit
        in: query
        required: false
        schema:
          type: integer
          maximum: 1000
          description: Maximum results
          default: 100
          title: Limit
        description: Maximum results
      - name: offset
        in: query
        required: false
        schema:
          type: integer
          minimum: 0
          description: Skip first N results
          default: 0
          title: Offset
        description: Skip first N results
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RecommendationsListResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/recommendations/accuracy:
    get:
      tags:
      - recommendations
      summary: Get Accuracy Dashboard
      description: Get accuracy dashboard with aggregated prediction metrics.
      operationId: get_accuracy_dashboard_external_recommendations_accuracy_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AccuracyDashboardResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/recommendations/insights/creative:
    get:
      tags:
      - recommendations
      summary: Get Creative Insights
      description: Get per-dimension creative accuracy insights from resolved recommendations.
      operationId: get_creative_insights_external_recommendations_insights_creative_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: dimension
        in: query
        required: false
        schema:
          type: string
          description: 'Filter to single dimension: ad_hook, ad_story, ad_close, traffic_source'
          title: Dimension
        description: 'Filter to single dimension: ad_hook, ad_story, ad_close, traffic_source'
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreativeInsightsResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/recommendations/insights/trend:
    get:
      tags:
      - recommendations
      summary: Get Accuracy Trend
      description: Get accuracy trending across time windows (7d, 30d, 90d, all).
      operationId: get_accuracy_trend_external_recommendations_insights_trend_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AccuracyTrendResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/recommendations/insights/calibration:
    get:
      tags:
      - recommendations
      summary: Get Confidence Calibration
      description: Get confidence calibration analysis (does confidence predict accuracy?).
      operationId: get_confidence_calibration_external_recommendations_insights_calibration_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: bucket_count
        in: query
        required: false
        schema:
          type: integer
          maximum: 10
          minimum: 2
          description: Number of confidence buckets
          default: 5
          title: Bucket Count
        description: Number of confidence buckets
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ConfidenceCalibrationResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/recommendations/insights/features:
    get:
      tags:
      - recommendations
      summary: Get Feature Importance
      description: Rank creative dimensions by predictive power (accuracy range).
      operationId: get_feature_importance_external_recommendations_insights_features_get
      parameters:
      - name: app_id
        in: query
        required: true
        schema:
          type: string
          description: Application identifier
          title: App Id
        description: Application identifier
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FeatureImportanceResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/recommendations/predict:
    post:
      tags:
      - recommendations
      summary: Get Calibrated Prediction
      description: Get a calibrated prediction based on historical creative performance.
      operationId: get_calibrated_prediction_external_recommendations_predict_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PredictionInput'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CalibratedPrediction'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/recommendations/{recommendation_id}:
    get:
      tags:
      - recommendations
      summary: Get Recommendation
      description: Get a recommendation by ID.
      operationId: get_recommendation_external_recommendations__recommendation_id__get
      parameters:
      - name: recommendation_id
        in: path
        required: true
        schema:
          type: integer
          title: Recommendation Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Recommendation'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    patch:
      tags:
      - recommendations
      summary: Update Recommendation
      description: Update a recommendation.
      operationId: update_recommendation_external_recommendations__recommendation_id__patch
      parameters:
      - name: recommendation_id
        in: path
        required: true
        schema:
          type: integer
          title: Recommendation Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RecommendationUpdate'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Recommendation'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/recommendations/{recommendation_id}/resolve:
    post:
      tags:
      - recommendations
      summary: Resolve Recommendation
      description: Resolve a recommendation with actual outcome value.
      operationId: resolve_recommendation_external_recommendations__recommendation_id__resolve_post
      parameters:
      - name: recommendation_id
        in: path
        required: true
        schema:
          type: integer
          title: Recommendation Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RecommendationResolve'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Recommendation'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/recommendations/{recommendation_id}/episodes:
    post:
      tags:
      - recommendations
      summary: Link Episodes
      description: Link episodes to a recommendation.
      operationId: link_episodes_external_recommendations__recommendation_id__episodes_post
      parameters:
      - name: recommendation_id
        in: path
        required: true
        schema:
          type: integer
          title: Recommendation Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/LinkEpisodesRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/LinkEpisodesResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/recommendations/{recommendation_id}/auto-match:
    post:
      tags:
      - recommendations
      summary: Auto Match Episodes
      description: Auto-match episodes by creative metadata fields.
      operationId: auto_match_episodes_external_recommendations__recommendation_id__auto_match_post
      parameters:
      - name: recommendation_id
        in: path
        required: true
        schema:
          type: integer
          title: Recommendation Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AutoMatchRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AutoMatchResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/recommendations/{recommendation_id}/outcomes:
    get:
      tags:
      - recommendations
      summary: Get Recommendation Outcomes
      description: Get recommendation with linked episode summaries.
      operationId: get_recommendation_outcomes_external_recommendations__recommendation_id__outcomes_get
      parameters:
      - name: recommendation_id
        in: path
        required: true
        schema:
          type: integer
          title: Recommendation Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RecommendationOutcome'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/admin/agent/chat:
    post:
      tags:
      - agent
      summary: Agent Chat
      description: Stream agent chat response via SSE.
      operationId: agent_chat_external_admin_agent_chat_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AgentChatRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/share:
    post:
      tags:
      - sharing
      summary: Grant Access
      description: 'Grant a user access to a self-model.


        Only the owner or an admin can grant access.'
      operationId: grant_access_external_self_models__self_model_id__share_post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: requesting_user_id
        in: query
        required: true
        schema:
          type: string
          description: User granting access
          title: Requesting User Id
        description: User granting access
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ShareRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ShareResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/{self_model_id}/share/{user_id}:
    delete:
      tags:
      - sharing
      summary: Revoke Access
      description: 'Revoke a user''s access to a self-model.


        Only the owner or an admin can revoke access.'
      operationId: revoke_access_external_self_models__self_model_id__share__user_id__delete
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: requesting_user_id
        in: query
        required: true
        schema:
          type: string
          description: User revoking access
          title: Requesting User Id
        description: User revoking access
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/self-models/shared:
    get:
      tags:
      - sharing
      summary: List Shared Models
      description: 'List self-models shared with the requesting user.


        Returns models where the user has been granted viewer, editor, or admin access.

        Does NOT include models the user owns (those come from the regular self-models
        endpoint).'
      operationId: list_shared_models_external_self_models_shared_get
      parameters:
      - name: requesting_user_id
        in: query
        required: true
        schema:
          type: string
          description: User to list shared models for
          title: Requesting User Id
        description: User to list shared models for
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/SharedModelResponse'
                title: Response List Shared Models External Self Models Shared Get
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /admin/backfill-beliefs:
    post:
      tags:
      - admin
      summary: Backfill Beliefs
      description: 'Retroactively run BehavioralBeliefExtractor on historical episodes

        that have no beliefs (belief_ids IS NULL or ''[]'').


        Use dry_run=true (default) to count before committing.'
      operationId: backfill_beliefs_admin_backfill_beliefs_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BackfillRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BackfillResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /admin/infer/{self_model_id}/{context_id}:
    post:
      tags:
      - admin
      summary: Infer state distribution for a single context
      description: 'Run belief-state inference for a single observation context.


        Shadow mode: writes state_distribution to metadata, never changes current_state_id.'
      operationId: infer_single_admin_infer__self_model_id___context_id__post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: context_id
        in: path
        required: true
        schema:
          type: string
          title: Context Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /admin/infer/{self_model_id}:
    post:
      tags:
      - admin
      summary: Infer state distributions for all contexts with beliefs
      description: 'Run belief-state inference for all contexts that have beliefs.


        Shadow mode: writes state_distribution to metadata, never changes current_state_id.'
      operationId: infer_all_admin_infer__self_model_id__post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /admin/confirm-prediction/{self_model_id}/{context_id}:
    post:
      tags:
      - admin
      summary: Confirm predicted state as observed
      description: 'Confirm the twin''s predicted state as the observed ground truth.


        Records provenance in observation_history for accuracy tracking.'
      operationId: confirm_prediction_admin_confirm_prediction__self_model_id___context_id__post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: context_id
        in: path
        required: true
        schema:
          type: string
          title: Context Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ConfirmPredictionRequest'
              default: {}
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /admin/observe/{self_model_id}/{context_id}:
    post:
      tags:
      - admin
      summary: Manually set observed state
      description: 'Manually set the observed state to an arbitrary value (correction
        path).


        Records provenance in observation_history.'
      operationId: observe_state_admin_observe__self_model_id___context_id__post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: context_id
        in: path
        required: true
        schema:
          type: string
          title: Context Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ObserveStateRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /admin/propose-goal/{self_model_id}/{context_id}:
    post:
      tags:
      - admin
      summary: Propose a new goal state
      description: Propose a new goal state for a context. Creates a pending proposal.
      operationId: propose_goal_admin_propose_goal__self_model_id___context_id__post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: context_id
        in: path
        required: true
        schema:
          type: string
          title: Context Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProposeGoalRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /admin/confirm-goal/{self_model_id}/{context_id}:
    post:
      tags:
      - admin
      summary: Confirm a pending goal proposal
      description: Confirm the most recent pending goal proposal. Updates goal_state_id.
      operationId: confirm_goal_admin_confirm_goal__self_model_id___context_id__post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: context_id
        in: path
        required: true
        schema:
          type: string
          title: Context Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ConfirmGoalRequest'
              default: {}
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /admin/reject-goal/{self_model_id}/{context_id}:
    post:
      tags:
      - admin
      summary: Reject a pending goal proposal
      description: Reject the most recent pending goal proposal. No goal change.
      operationId: reject_goal_admin_reject_goal__self_model_id___context_id__post
      parameters:
      - name: self_model_id
        in: path
        required: true
        schema:
          type: integer
          title: Self Model Id
      - name: context_id
        in: path
        required: true
        schema:
          type: string
          title: Context Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RejectGoalRequest'
              default: {}
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/codings:
    post:
      tags:
      - codings
      summary: Upsert Coding
      description: 'Create or update a single observation coding.


        Uses upsert semantics: if a coding with the same

        (pr_number, stakeholder_name, context_id, observation_type) exists,

        it is updated. Otherwise, a new coding is created.'
      operationId: upsert_coding_external_codings_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CodingUpsert'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CodingResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
    get:
      tags:
      - codings
      summary: List Codings
      description: List all codings for a PR number.
      operationId: list_codings_external_codings_get
      parameters:
      - name: pr_number
        in: query
        required: true
        schema:
          type: integer
          description: PR number to filter by
          title: Pr Number
        description: PR number to filter by
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CodingListResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/codings/batch:
    post:
      tags:
      - codings
      summary: Upsert Codings Batch
      description: 'Upsert multiple codings in a single transaction.


        Useful for saving all annotations for a PR at once.'
      operationId: upsert_codings_batch_external_codings_batch_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BatchCodingRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CodingListResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /external/codings/{coding_id}:
    get:
      tags:
      - codings
      summary: Get Coding
      description: Get a single coding by ID.
      operationId: get_coding_external_codings__coding_id__get
      parameters:
      - name: coding_id
        in: path
        required: true
        schema:
          type: integer
          title: Coding Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CodingResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/v1/episodes:
    post:
      tags:
      - v1-episodes
      summary: Create Episode
      description: 'Create an episode on a user''s self-model.


        Lightweight ingestion endpoint for external signals. Maps:

        - `context` → episode `intent`

        - `action`  → episode `outcome`

        - `domain`  → episode `domain_id`


        Deduplication: deterministic `source_event_id` from

        `sha256(user_id:context:action:timestamp)`. Duplicate submissions

        return `deduplicated: true` with `episode_id: null` and 200 status.'
      operationId: create_episode_api_v1_episodes_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/src__api__routes__v1_episodes__CreateEpisodeRequest'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/src__api__routes__v1_episodes__CreateEpisodeResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/v1/users/resolve:
    get:
      tags:
      - v1-users
      summary: Resolve Identity
      description: 'Resolve an external identity to a Clarity user.


        Returns the user_id, self_model_id, and all linked identities

        for the resolved user. Returns 404 if no match.


        Uses a single DB connection to avoid pool exhaustion under

        concurrent load.'
      operationId: resolve_identity_api_v1_users_resolve_get
      parameters:
      - name: provider
        in: query
        required: true
        schema:
          type: string
          description: Identity provider
          title: Provider
        description: Identity provider
      - name: external_id
        in: query
        required: true
        schema:
          type: string
          description: Provider-specific hashed ID
          title: External Id
        description: Provider-specific hashed ID
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ResolveResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/v1/users/soft:
    post:
      tags:
      - v1-users
      summary: Create Soft User
      description: 'Create a soft user with a minimal self-model and identity link.


        Idempotent: if the (source, external_id) identity already exists,

        returns the existing user with `is_new: false` and 200 status.


        The self-model is created with empty modality_weights and attention_policy,

        ready to accumulate episodes. No PII is stored — external_id should be

        a hash, and the email placeholder is `soft:{external_id}`.'
      operationId: create_soft_user_api_v1_users_soft_post
      parameters:
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateSoftUserRequest'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateSoftUserResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /api/v1/users/{user_id}/identities:
    post:
      tags:
      - v1-users
      summary: Add Identity
      description: 'Link an external identity to an existing user.


        Idempotent for same-user re-links: if the (provider, external_id) pair

        is already linked to THIS user, returns 200.

        Returns 409 if the pair is linked to a DIFFERENT user.'
      operationId: add_identity_api_v1_users__user_id__identities_post
      parameters:
      - name: user_id
        in: path
        required: true
        schema:
          type: string
          title: User Id
      - name: X-API-Key
        in: header
        required: false
        schema:
          anyOf:
          - type: string
          - type: 'null'
          title: X-Api-Key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AddIdentityRequest'
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AddIdentityResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
  /:
    get:
      summary: Root
      description: Root endpoint with service information
      operationId: root__get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
  /ping:
    get:
      summary: Ping
      description: Simple ping endpoint for quick health checks
      operationId: ping_ping_get
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
components:
  schemas:
    AIReadyContext:
      properties:
        user_summary:
          type: string
          title: User Summary
          description: Brief summary of the user and their self-model
        self_model_name:
          type: string
          title: Self Model Name
        current_view:
          type: string
          title: Current View
          description: 'The view used for context: being, becoming, etc.'
          default: being
        dominant_mode:
          anyOf:
          - type: string
          - type: 'null'
          title: Dominant Mode
          description: Currently dominant mode (e.g., create, recover)
        mode_confidence:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Mode Confidence
          description: Confidence in the mode inference
        domain_summaries:
          items:
            $ref: '#/components/schemas/DomainContext'
          type: array
          title: Domain Summaries
          description: Summary of each domain
        key_beliefs:
          items:
            $ref: '#/components/schemas/BeliefContext'
          type: array
          title: Key Beliefs
          description: Most relevant beliefs
        engagement_summary:
          additionalProperties: true
          type: object
          title: Engagement Summary
          description: Flattened engagement metrics
        recommendations:
          items:
            type: string
          type: array
          title: Recommendations
          description: Actionable recommendations
        narrative_summary:
          anyOf:
          - type: string
          - type: 'null'
          title: Narrative Summary
          description: Natural language summary for context injection
      type: object
      required:
      - user_summary
      - self_model_name
      title: AIReadyContext
      description: 'Context optimized for LLM consumption.


        Contains pre-formatted data suitable for direct injection into prompts.'
    AccuracyByMetric:
      properties:
        metric:
          type: string
          title: Metric
        count:
          type: integer
          title: Count
        avg_accuracy:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Accuracy
        avg_predicted:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Predicted
        avg_actual:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Actual
      type: object
      required:
      - metric
      - count
      - avg_accuracy
      - avg_predicted
      - avg_actual
      title: AccuracyByMetric
      description: Accuracy stats for a single predicted metric.
    AccuracyDashboardResponse:
      properties:
        total_recommendations:
          type: integer
          title: Total Recommendations
        resolved_count:
          type: integer
          title: Resolved Count
        avg_accuracy:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Accuracy
        accuracy_by_metric:
          items:
            $ref: '#/components/schemas/AccuracyByMetric'
          type: array
          title: Accuracy By Metric
        recent_recommendations:
          items:
            $ref: '#/components/schemas/Recommendation'
          type: array
          title: Recent Recommendations
      type: object
      required:
      - total_recommendations
      - resolved_count
      - avg_accuracy
      - accuracy_by_metric
      - recent_recommendations
      title: AccuracyDashboardResponse
      description: Dashboard-level accuracy aggregation.
    AccuracyTrendPoint:
      properties:
        window_label:
          type: string
          title: Window Label
        count:
          type: integer
          title: Count
        avg_accuracy:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Accuracy
        avg_confidence:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Confidence
      type: object
      required:
      - window_label
      - count
      - avg_accuracy
      - avg_confidence
      title: AccuracyTrendPoint
      description: Accuracy stats for a single time window.
    AccuracyTrendResponse:
      properties:
        app_id:
          type: string
          title: App Id
        windows:
          items:
            $ref: '#/components/schemas/AccuracyTrendPoint'
          type: array
          title: Windows
        improving:
          anyOf:
          - type: boolean
          - type: 'null'
          title: Improving
      type: object
      required:
      - app_id
      - windows
      title: AccuracyTrendResponse
      description: Accuracy trending across time windows.
    AddIdentityRequest:
      properties:
        provider:
          type: string
          maxLength: 50
          title: Provider
          description: Identity provider (e.g., 'posthog', 'resend', 'calcom')
        external_id:
          type: string
          maxLength: 255
          title: External Id
          description: Provider-specific hashed ID
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
      type: object
      required:
      - provider
      - external_id
      title: AddIdentityRequest
    AddIdentityResponse:
      properties:
        status:
          type: string
          title: Status
        provider:
          type: string
          title: Provider
      type: object
      required:
      - status
      - provider
      title: AddIdentityResponse
    Affect:
      properties:
        valence:
          type: number
          maximum: 2.0
          minimum: -2.0
          title: Valence
          description: Positive/negative feeling
        arousal:
          type: number
          maximum: 4.0
          minimum: 0.0
          title: Arousal
          description: Energy level
      type: object
      required:
      - valence
      - arousal
      title: Affect
    AgencyEngagement:
      properties:
        perceived_control:
          anyOf:
          - additionalProperties:
              type: number
            type: object
          - type: 'null'
          title: Perceived Control
          description: 'Control expectations by domain: bodily, cognitive, social,
            economic, etc.'
        available_actions:
          anyOf:
          - items:
              type: string
            type: array
          - type: 'null'
          title: Available Actions
          description: Classes of actions available in this episode
        chosen_policy:
          anyOf:
          - type: string
          - type: 'null'
          title: Chosen Policy
          description: Selected policy/action
      type: object
      title: AgencyEngagement
      description: 'Agency and perceived control across domains.


        What knobs can this self turn, and how abstract can they get?'
    AgentChatContext:
      properties:
        app_id:
          type: string
          title: App Id
          default: mystica
        type:
          type: string
          title: Type
          default: general
        selected_transition:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Selected Transition
      type: object
      title: AgentChatContext
    AgentChatRequest:
      properties:
        messages:
          items:
            $ref: '#/components/schemas/ChatMessageRequest'
          type: array
          title: Messages
        context:
          $ref: '#/components/schemas/AgentChatContext'
          default:
            app_id: mystica
            type: general
      type: object
      required:
      - messages
      title: AgentChatRequest
    AggregateGroup:
      properties:
        dimensions:
          additionalProperties:
            anyOf:
            - type: string
            - type: 'null'
          type: object
          title: Dimensions
        metrics:
          additionalProperties:
            type: integer
          type: object
          title: Metrics
      type: object
      required:
      - dimensions
      - metrics
      title: AggregateGroup
      description: Single group in aggregation response.
    AggregateRequest:
      properties:
        app_id:
          type: string
          title: App Id
        group_by:
          items:
            type: string
          type: array
          maxItems: 3
          minItems: 1
          title: Group By
        metrics:
          items:
            type: string
          type: array
          title: Metrics
          default:
          - count
        filters:
          additionalProperties:
            type: string
          type: object
          title: Filters
        date_from:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date From
        date_to:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date To
        limit:
          type: integer
          maximum: 1000.0
          title: Limit
          default: 100
      type: object
      required:
      - app_id
      - group_by
      title: AggregateRequest
      description: Request for episode aggregation (E.1).
    AggregateResponse:
      properties:
        groups:
          items:
            $ref: '#/components/schemas/AggregateGroup'
          type: array
          title: Groups
        total_count:
          type: integer
          title: Total Count
        total_unique_users:
          type: integer
          title: Total Unique Users
        query_time_ms:
          type: integer
          title: Query Time Ms
      type: object
      required:
      - groups
      - total_count
      - total_unique_users
      - query_time_ms
      title: AggregateResponse
      description: Response for episode aggregation.
    AlignmentComponents:
      properties:
        directional_alignment:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Directional Alignment
        modality_alignment:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Modality Alignment
        pillar_alignment:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Pillar Alignment
        belief_coherence:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Belief Coherence
        residual_progress:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Residual Progress
      type: object
      required:
      - directional_alignment
      - modality_alignment
      - pillar_alignment
      - belief_coherence
      - residual_progress
      title: AlignmentComponents
      description: Detailed breakdown of alignment score components.
    AlignmentMetrics:
      properties:
        overall_score:
          type: number
          maximum: 100.0
          minimum: 0.0
          title: Overall Score
        aligned_beliefs_count:
          type: integer
          minimum: 0.0
          title: Aligned Beliefs Count
        misaligned_beliefs_count:
          type: integer
          minimum: 0.0
          title: Misaligned Beliefs Count
        recent_actions_count:
          type: integer
          minimum: 0.0
          title: Recent Actions Count
        on_course_indicator:
          $ref: '#/components/schemas/OnCourseStatus'
        confidence_level:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Confidence Level
        components:
          $ref: '#/components/schemas/AlignmentComponents'
        pillar_scores:
          additionalProperties:
            type: number
          type: object
          title: Pillar Scores
        modality_scores:
          additionalProperties:
            type: number
          type: object
          title: Modality Scores
        pillar_modality_matrix:
          additionalProperties:
            additionalProperties:
              type: number
            type: object
          type: object
          title: Pillar Modality Matrix
        pillar_priorities:
          additionalProperties:
            type: integer
          type: object
          title: Pillar Priorities
        pillar_satisfaction:
          additionalProperties:
            type: number
          type: object
          title: Pillar Satisfaction
        telos_vector:
          anyOf:
          - $ref: '#/components/schemas/TelosVector'
          - type: 'null'
        recent_vector:
          anyOf:
          - $ref: '#/components/schemas/RecentActivityVector'
          - type: 'null'
        user_id:
          type: string
          title: User Id
        calculation_timestamp:
          type: string
          format: date-time
          title: Calculation Timestamp
        calculation_method:
          type: string
          title: Calculation Method
          default: telos_alignment_v1
        primary_focus_areas:
          items:
            type: string
          type: array
          title: Primary Focus Areas
        suggested_actions:
          items:
            type: string
          type: array
          title: Suggested Actions
      type: object
      required:
      - overall_score
      - aligned_beliefs_count
      - misaligned_beliefs_count
      - recent_actions_count
      - on_course_indicator
      - confidence_level
      - components
      - pillar_scores
      - modality_scores
      - user_id
      title: AlignmentMetrics
      description: Complete alignment score calculation results.
    ApproveContextRequest:
      properties:
        approved_by:
          anyOf:
          - type: string
          - type: 'null'
          title: Approved By
      type: object
      title: ApproveContextRequest
    ArchetypeDistribution:
      properties:
        app_id:
          type: string
          title: App Id
        total_users:
          type: integer
          title: Total Users
        distribution:
          additionalProperties:
            type: integer
          propertyNames:
            $ref: '#/components/schemas/ArchetypeId'
          type: object
          title: Distribution
          description: Count per archetype
        percentages:
          additionalProperties:
            type: number
          propertyNames:
            $ref: '#/components/schemas/ArchetypeId'
          type: object
          title: Percentages
          description: Percentage per archetype
      type: object
      required:
      - app_id
      - total_users
      title: ArchetypeDistribution
      description: Distribution of archetypes in a cohort.
    ArchetypeId:
      type: string
      enum:
      - crisis_stabilizer
      - unanchored_truth_seeker
      - wounded_validator
      - intuitive_integrator
      - private_rebuilder
      - self_reclaiming_seeker
      title: ArchetypeId
      description: JTBD-derived user archetypes.
    ArchetypeInsight:
      properties:
        archetype_id:
          type: string
          title: Archetype Id
        archetype_name:
          type: string
          title: Archetype Name
        user_count:
          type: integer
          minimum: 0.0
          title: User Count
        conversion_rate:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Conversion Rate
        rank:
          type: integer
          minimum: 1.0
          title: Rank
          description: Rank by conversion rate (1 = highest)
      type: object
      required:
      - archetype_id
      - archetype_name
      - user_count
      - conversion_rate
      - rank
      title: ArchetypeInsight
      description: Per-archetype metrics for a transition.
    AttentionPolicy:
      properties:
        summary:
          type: string
          title: Summary
        focus_areas:
          items:
            type: string
          type: array
          title: Focus Areas
        quotes:
          items:
            type: string
          type: array
          title: Quotes
          description: Direct quotes showing attention focus
      type: object
      required:
      - summary
      title: AttentionPolicy
      description: What the user is paying attention to in a phase.
    AutoMatchRequest:
      properties:
        date_from:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date From
        date_to:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date To
        dry_run:
          type: boolean
          title: Dry Run
          default: false
      type: object
      title: AutoMatchRequest
      description: Auto-match episodes by creative metadata.
    AutoMatchResponse:
      properties:
        matched_episode_ids:
          items:
            type: integer
          type: array
          title: Matched Episode Ids
        matched_count:
          type: integer
          title: Matched Count
        newly_linked:
          type: integer
          title: Newly Linked
        dry_run:
          type: boolean
          title: Dry Run
      type: object
      required:
      - matched_episode_ids
      - matched_count
      - newly_linked
      - dry_run
      title: AutoMatchResponse
      description: Response from auto-matching episodes.
    BackfillRequest:
      properties:
        app_id:
          type: string
          title: App Id
        batch_size:
          type: integer
          title: Batch Size
          default: 500
        dry_run:
          type: boolean
          title: Dry Run
          default: true
        date_from:
          anyOf:
          - type: string
          - type: 'null'
          title: Date From
        date_to:
          anyOf:
          - type: string
          - type: 'null'
          title: Date To
        self_model_ids:
          anyOf:
          - items:
              type: integer
            type: array
          - type: 'null'
          title: Self Model Ids
      type: object
      required:
      - app_id
      title: BackfillRequest
    BackfillResponse:
      properties:
        episodes_scanned:
          type: integer
          title: Episodes Scanned
        episodes_with_beliefs:
          type: integer
          title: Episodes With Beliefs
        episodes_skipped:
          type: integer
          title: Episodes Skipped
        beliefs_created:
          type: integer
          title: Beliefs Created
        belief_breakdown:
          additionalProperties:
            type: integer
          type: object
          title: Belief Breakdown
        errors:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Errors
        dry_run:
          type: boolean
          title: Dry Run
      type: object
      required:
      - episodes_scanned
      - episodes_with_beliefs
      - episodes_skipped
      - beliefs_created
      - belief_breakdown
      - errors
      - dry_run
      title: BackfillResponse
    BatchAlignmentRequest:
      properties:
        content:
          type: string
          title: Content
        beliefs:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Beliefs
        targets:
          items:
            $ref: '#/components/schemas/StakeholderTarget'
          type: array
          title: Targets
      type: object
      required:
      - content
      - targets
      title: BatchAlignmentRequest
      description: Request for batch alignment scoring (E.10).
    BatchAlignmentResponse:
      properties:
        scores:
          items:
            $ref: '#/components/schemas/StakeholderScore'
          type: array
          title: Scores
        duration_ms:
          type: integer
          title: Duration Ms
        errors:
          items:
            type: string
          type: array
          title: Errors
      type: object
      required:
      - scores
      - duration_ms
      title: BatchAlignmentResponse
      description: Response for batch alignment scoring.
    BatchCodingRequest:
      properties:
        codings:
          items:
            $ref: '#/components/schemas/CodingUpsert'
          type: array
          title: Codings
      type: object
      required:
      - codings
      title: BatchCodingRequest
      description: Upsert multiple codings in one request.
    BatchCreateEpisodesRequest:
      properties:
        episodes:
          items:
            $ref: '#/components/schemas/src__models__self_model__CreateEpisodeRequest'
          type: array
          maxItems: 500
          minItems: 1
          title: Episodes
          description: List of episodes to create
      type: object
      required:
      - episodes
      title: BatchCreateEpisodesRequest
      description: Request to create multiple episodes in a single batch.
    BatchCreateEpisodesResponse:
      properties:
        created_count:
          type: integer
          title: Created Count
          description: Number of episodes successfully created
        episode_ids:
          items:
            type: integer
          type: array
          title: Episode Ids
          description: IDs of created episodes
        skipped_count:
          type: integer
          title: Skipped Count
          description: Episodes skipped due to duplicate source_event_id
          default: 0
      type: object
      required:
      - created_count
      - episode_ids
      title: BatchCreateEpisodesResponse
      description: Response after batch creating episodes.
    BehavioralSignals:
      properties:
        total_episodes:
          type: integer
          title: Total Episodes
          default: 0
        ad_velocity:
          anyOf:
          - type: number
          - type: 'null'
          title: Ad Velocity
        unique_event_types:
          type: integer
          title: Unique Event Types
          default: 0
        stages_reached:
          type: integer
          title: Stages Reached
          default: 0
        first_to_purchase_hours:
          anyOf:
          - type: number
          - type: 'null'
          title: First To Purchase Hours
        has_chat:
          type: boolean
          title: Has Chat
          default: false
        purchase_count:
          type: integer
          title: Purchase Count
          default: 0
      type: object
      title: BehavioralSignals
      description: Computed behavioral signals for a user.
    Belief:
      properties:
        belief_id:
          type: string
          title: Belief Id
        kind:
          $ref: '#/components/schemas/BeliefKind'
        claim:
          type: string
          title: Claim
        observation_context:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Observation Context
        prediction:
          anyOf:
          - $ref: '#/components/schemas/Prediction'
          - type: 'null'
        evidence:
          items:
            $ref: '#/components/schemas/Evidence'
          type: array
          title: Evidence
        status:
          $ref: '#/components/schemas/BeliefStatus'
          default: draft
        confidence:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Confidence
          default: 0.5
      type: object
      required:
      - kind
      - claim
      title: Belief
    BeliefContext:
      properties:
        id:
          type: string
          title: Id
        content:
          type: string
          title: Content
        category:
          anyOf:
          - type: string
          - type: 'null'
          title: Category
        tags:
          anyOf:
          - items:
              type: string
            type: array
          - type: 'null'
          title: Tags
          description: Tags from JSONB column
        confidence:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Confidence
        evidence_source:
          anyOf:
          - type: string
          - type: 'null'
          title: Evidence Source
          description: Source of evidence for this belief
      type: object
      required:
      - id
      - content
      title: BeliefContext
      description: 'Belief information for context.


        Uses actual database schema columns: tags (JSONB), evidence_source, category'
    BeliefKind:
      type: string
      enum:
      - statement
      - falsifiable
      - predictive
      title: BeliefKind
    BeliefObject:
      properties:
        content:
          type: string
          title: Content
          description: Belief content/statement
        type:
          anyOf:
          - type: string
          - type: 'null'
          title: Type
          description: Belief type (e.g., 'statement')
        category:
          anyOf:
          - type: string
          - type: 'null'
          title: Category
          description: Belief category
        confidence:
          type: number
          title: Confidence
          description: Confidence score (0.0-1.0)
          default: 0.5
      type: object
      required:
      - content
      title: BeliefObject
      description: Belief object for syncing to Clarity
    BeliefResponse:
      properties:
        id:
          type: integer
          title: Id
        statement:
          type: string
          title: Statement
        category:
          anyOf:
          - type: string
          - type: 'null'
          title: Category
        pillar:
          anyOf:
          - type: string
          - type: 'null'
          title: Pillar
        observation_context_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Observation Context Id
        confidence:
          type: number
          title: Confidence
        connections:
          anyOf:
          - items:
              additionalProperties: true
              type: object
            type: array
          - type: 'null'
          title: Connections
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
        source_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Source Id
        created_at:
          type: string
          format: date-time
          title: Created At
      type: object
      required:
      - id
      - statement
      - confidence
      - created_at
      title: BeliefResponse
      description: Response for a single belief.
    BeliefStatus:
      type: string
      enum:
      - draft
      - testing
      - supported
      - refuted
      title: BeliefStatus
    Bet:
      properties:
        app_id:
          type: string
          title: App Id
        name:
          type: string
          maxLength: 200
          title: Name
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
        from_stage:
          type: string
          title: From Stage
        to_stage:
          type: string
          title: To Stage
        baseline_rate:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Baseline Rate
        goal_rate:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Goal Rate
        expected_value:
          anyOf:
          - type: string
          - type: 'null'
          title: Expected Value
        deadline:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Deadline
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
        id:
          type: integer
          title: Id
        current_rate:
          anyOf:
          - type: number
          - type: 'null'
          title: Current Rate
        status:
          $ref: '#/components/schemas/BetStatus'
          default: active
        created_at:
          type: string
          format: date-time
          title: Created At
        resolved_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Resolved At
        paused_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Paused At
        created_by:
          anyOf:
          - type: string
          - type: 'null'
          title: Created By
        resolved_by:
          anyOf:
          - type: string
          - type: 'null'
          title: Resolved By
        resolution_notes:
          anyOf:
          - type: string
          - type: 'null'
          title: Resolution Notes
        actual_value:
          anyOf:
          - type: string
          - type: 'null'
          title: Actual Value
        episode_count:
          anyOf:
          - type: integer
          - type: 'null'
          title: Episode Count
      type: object
      required:
      - app_id
      - name
      - from_stage
      - to_stage
      - baseline_rate
      - goal_rate
      - id
      - created_at
      title: Bet
      description: Full bet model with all fields.
    BetConfidenceFactors:
      properties:
        significance_score:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Significance Score
          description: 'Based on p-value (weight: 30%)'
        sample_size_score:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Sample Size Score
          description: 'Based on total samples (weight: 25%)'
        data_quality_score:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Data Quality Score
          description: 'Data quality metric (weight: 20%)'
        historical_win_rate:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Historical Win Rate
          description: 'Past bet performance (weight: 15%)'
        ci_width_score:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Ci Width Score
          description: 'Narrower CI = higher (weight: 10%)'
      type: object
      required:
      - significance_score
      - sample_size_score
      - data_quality_score
      - historical_win_rate
      - ci_width_score
      title: BetConfidenceFactors
      description: Individual factors contributing to bet confidence score.
    BetConfidenceScore:
      properties:
        overall_score:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Overall Score
          description: Weighted confidence (0-1)
        confidence_label:
          type: string
          title: Confidence Label
          description: '''High'', ''Medium'', or ''Low'''
        factors:
          $ref: '#/components/schemas/BetConfidenceFactors'
        recommendation:
          type: string
          title: Recommendation
          description: Recommendation based on score
        warnings:
          items:
            type: string
          type: array
          title: Warnings
          description: Risk factors or concerns
      type: object
      required:
      - overall_score
      - confidence_label
      - factors
      - recommendation
      title: BetConfidenceScore
      description: Confidence score for a bet suggestion.
    BetCreate:
      properties:
        app_id:
          type: string
          title: App Id
        name:
          type: string
          maxLength: 200
          title: Name
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
        from_stage:
          type: string
          title: From Stage
        to_stage:
          type: string
          title: To Stage
        baseline_rate:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Baseline Rate
        goal_rate:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Goal Rate
        expected_value:
          anyOf:
          - type: number
          - type: string
          - type: 'null'
          title: Expected Value
        deadline:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Deadline
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
      type: object
      required:
      - app_id
      - name
      - from_stage
      - to_stage
      - baseline_rate
      - goal_rate
      title: BetCreate
      description: Request model for creating a bet.
    BetEpisodeLinkCreate:
      properties:
        episode_id:
          type: integer
          title: Episode Id
      type: object
      required:
      - episode_id
      title: BetEpisodeLinkCreate
      description: Request to link an episode to a bet.
    BetEpisodesResponse:
      properties:
        episodes:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Episodes
        total:
          type: integer
          title: Total
      type: object
      required:
      - episodes
      - total
      title: BetEpisodesResponse
      description: Response containing episodes linked to a bet.
    BetProgress:
      properties:
        baseline_rate:
          type: number
          title: Baseline Rate
        current_rate:
          anyOf:
          - type: number
          - type: 'null'
          title: Current Rate
        goal_rate:
          type: number
          title: Goal Rate
        progress_pct:
          type: number
          title: Progress Pct
          description: Percentage progress toward goal (0-100)
        improvement_pp:
          type: number
          title: Improvement Pp
          description: Percentage points improved from baseline
        days_remaining:
          anyOf:
          - type: integer
          - type: 'null'
          title: Days Remaining
        status_indicator:
          $ref: '#/components/schemas/BetStatusIndicator'
      type: object
      required:
      - baseline_rate
      - current_rate
      - goal_rate
      - progress_pct
      - improvement_pp
      - status_indicator
      title: BetProgress
      description: Progress tracking for an active bet.
    BetResolve:
      properties:
        outcome:
          $ref: '#/components/schemas/BetStatus'
          description: Must be 'won' or 'lost'
        notes:
          anyOf:
          - type: string
          - type: 'null'
          title: Notes
        actual_value:
          anyOf:
          - type: number
          - type: string
          - type: 'null'
          title: Actual Value
      type: object
      required:
      - outcome
      title: BetResolve
      description: Request model for resolving a bet.
    BetStatus:
      type: string
      enum:
      - active
      - paused
      - won
      - lost
      - cancelled
      title: BetStatus
      description: Lifecycle status of a bet.
    BetStatusIndicator:
      type: string
      enum:
      - on_track
      - behind
      - ahead
      - at_risk
      title: BetStatusIndicator
      description: Progress indicator for active bets.
    BetSuggestion:
      properties:
        from_stage:
          type: string
          title: From Stage
        to_stage:
          type: string
          title: To Stage
        suggested_name:
          type: string
          title: Suggested Name
        suggested_description:
          type: string
          title: Suggested Description
        baseline_rate:
          type: number
          title: Baseline Rate
        suggested_goal_rate:
          type: number
          title: Suggested Goal Rate
        expected_improvement_pp:
          type: number
          title: Expected Improvement Pp
          description: Expected improvement in percentage points
        confidence:
          $ref: '#/components/schemas/BetConfidenceScore'
        rationale:
          type: string
          title: Rationale
          description: Why this bet is suggested
        similar_past_bets:
          items:
            type: integer
          type: array
          title: Similar Past Bets
          description: IDs of similar historical bets
      type: object
      required:
      - from_stage
      - to_stage
      - suggested_name
      - suggested_description
      - baseline_rate
      - suggested_goal_rate
      - expected_improvement_pp
      - confidence
      - rationale
      title: BetSuggestion
      description: AI-generated bet suggestion with confidence scoring.
    BetUpdate:
      properties:
        name:
          anyOf:
          - type: string
          - type: 'null'
          title: Name
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
        status:
          anyOf:
          - $ref: '#/components/schemas/BetStatus'
          - type: 'null'
        deadline:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Deadline
        current_rate:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Current Rate
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
      type: object
      title: BetUpdate
      description: Request model for updating a bet.
    BetWithProgress:
      properties:
        app_id:
          type: string
          title: App Id
        name:
          type: string
          maxLength: 200
          title: Name
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
        from_stage:
          type: string
          title: From Stage
        to_stage:
          type: string
          title: To Stage
        baseline_rate:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Baseline Rate
        goal_rate:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Goal Rate
        expected_value:
          anyOf:
          - type: string
          - type: 'null'
          title: Expected Value
        deadline:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Deadline
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
        id:
          type: integer
          title: Id
        current_rate:
          anyOf:
          - type: number
          - type: 'null'
          title: Current Rate
        status:
          $ref: '#/components/schemas/BetStatus'
          default: active
        created_at:
          type: string
          format: date-time
          title: Created At
        resolved_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Resolved At
        paused_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Paused At
        created_by:
          anyOf:
          - type: string
          - type: 'null'
          title: Created By
        resolved_by:
          anyOf:
          - type: string
          - type: 'null'
          title: Resolved By
        resolution_notes:
          anyOf:
          - type: string
          - type: 'null'
          title: Resolution Notes
        actual_value:
          anyOf:
          - type: string
          - type: 'null'
          title: Actual Value
        episode_count:
          anyOf:
          - type: integer
          - type: 'null'
          title: Episode Count
        progress:
          $ref: '#/components/schemas/BetProgress'
      type: object
      required:
      - app_id
      - name
      - from_stage
      - to_stage
      - baseline_rate
      - goal_rate
      - id
      - created_at
      - progress
      title: BetWithProgress
      description: Bet with computed progress metrics.
    BetsListResponse:
      properties:
        bets:
          items:
            $ref: '#/components/schemas/Bet'
          type: array
          title: Bets
        total:
          type: integer
          title: Total
      type: object
      required:
      - bets
      - total
      title: BetsListResponse
      description: Response model for listing bets.
    BetsSummary:
      properties:
        total_bet_value:
          type: string
          title: Total Bet Value
          description: Sum of expected_value for active bets
        active_bets:
          type: integer
          title: Active Bets
        won_bets:
          type: integer
          title: Won Bets
        lost_bets:
          type: integer
          title: Lost Bets
        avg_win_rate:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Win Rate
          description: Historical win rate (0-1)
        projected_revenue:
          anyOf:
          - type: string
          - type: 'null'
          title: Projected Revenue
          description: If all active bets win
      type: object
      required:
      - total_bet_value
      - active_bets
      - won_bets
      - lost_bets
      title: BetsSummary
      description: Dashboard summary of bets.
    Body_create_or_update_self_model_onboarding_self_model_post:
      properties:
        user_id:
          type: string
          title: User Id
        modality_weights:
          additionalProperties: true
          type: object
          title: Modality Weights
        attention_policy:
          additionalProperties: true
          type: object
          title: Attention Policy
      type: object
      required:
      - user_id
      - modality_weights
      - attention_policy
      title: Body_create_or_update_self_model_onboarding_self_model_post
    Body_initialize_onboarding_onboarding_initialize_post:
      properties:
        user_id:
          type: string
          title: User Id
        questionnaire_set:
          type: string
          title: Questionnaire Set
          default: minimal
      type: object
      required:
      - user_id
      title: Body_initialize_onboarding_onboarding_initialize_post
    Body_level_up_user_onboarding_level_up_post:
      properties:
        user_id:
          type: string
          title: User Id
        new_level:
          type: integer
          title: New Level
      type: object
      required:
      - user_id
      - new_level
      title: Body_level_up_user_onboarding_level_up_post
    Body_score_onboarding_answers_onboarding_score_post:
      properties:
        user_id:
          type: string
          title: User Id
        answers:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Answers
        session_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Session Id
      type: object
      required:
      - user_id
      - answers
      title: Body_score_onboarding_answers_onboarding_score_post
    CalibratedPrediction:
      properties:
        app_id:
          type: string
          title: App Id
        predicted_metric:
          type: string
          title: Predicted Metric
        predicted_value:
          anyOf:
          - type: number
          - type: 'null'
          title: Predicted Value
        suggested_confidence:
          anyOf:
          - type: number
          - type: 'null'
          title: Suggested Confidence
        historical_matches:
          items:
            $ref: '#/components/schemas/PredictionMatchDetail'
          type: array
          title: Historical Matches
        total_resolved:
          type: integer
          title: Total Resolved
        base_rate:
          anyOf:
          - type: number
          - type: 'null'
          title: Base Rate
        explanation:
          type: string
          title: Explanation
      type: object
      required:
      - app_id
      - predicted_metric
      - historical_matches
      - total_resolved
      - explanation
      title: CalibratedPrediction
      description: Calibrated prediction response.
    CausalMechanism:
      properties:
        steps:
          items:
            $ref: '#/components/schemas/CausalStep'
          type: array
          maxItems: 5
          minItems: 2
          title: Steps
        summary:
          type: string
          title: Summary
          description: One-sentence summary of the mechanism
      type: object
      required:
      - steps
      - summary
      title: CausalMechanism
      description: Causal mechanism explaining why users struggle at a transition.
    CausalStep:
      properties:
        label:
          type: string
          title: Label
          description: Short label for this step (e.g., 'Many options shown')
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
          description: Optional longer explanation
      type: object
      required:
      - label
      title: CausalStep
      description: A single step in a causal mechanism chain.
    ChatMessageRequest:
      properties:
        role:
          type: string
          title: Role
        content:
          type: string
          title: Content
      type: object
      required:
      - role
      - content
      title: ChatMessageRequest
    CheckinRequest:
      properties:
        user_id:
          type: string
          title: User Id
        scene_description:
          anyOf:
          - type: string
          - type: 'null'
          title: Scene Description
        pillar_tags:
          anyOf:
          - items:
              type: string
            type: array
          - type: 'null'
          title: Pillar Tags
        affect_valence:
          anyOf:
          - type: integer
          - type: 'null'
          title: Affect Valence
        affect_arousal:
          anyOf:
          - type: integer
          - type: 'null'
          title: Affect Arousal
        intent:
          anyOf:
          - type: string
          - type: 'null'
          title: Intent
        outcome:
          anyOf:
          - type: string
          - type: 'null'
          title: Outcome
        affordance_note:
          anyOf:
          - type: string
          - type: 'null'
          title: Affordance Note
        test_result:
          anyOf:
          - type: string
          - type: 'null'
          title: Test Result
        day_notes:
          anyOf:
          - type: string
          - type: 'null'
          title: Day Notes
      type: object
      required:
      - user_id
      title: CheckinRequest
      description: Request for morning/evening check-in
    CheckinResponse:
      properties:
        status:
          type: string
          title: Status
        episode_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Episode Id
        hypothesis_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Hypothesis Id
        recommendation:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Recommendation
        residuals:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Residuals
        invariant_candidates:
          anyOf:
          - items:
              type: string
            type: array
          - type: 'null'
          title: Invariant Candidates
        prompt_version:
          anyOf:
          - type: string
          - type: 'null'
          title: Prompt Version
        usage_metrics:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Usage Metrics
      type: object
      required:
      - status
      title: CheckinResponse
      description: Response from check-in processing
    CleanupRequest:
      properties:
        timeout_minutes:
          type: integer
          title: Timeout Minutes
          description: Minutes before session is considered stale
          default: 60
      type: object
      title: CleanupRequest
      description: Request to cleanup stale sessions
    CleanupResponse:
      properties:
        abandoned_count:
          type: integer
          title: Abandoned Count
        timeout_minutes:
          type: integer
          title: Timeout Minutes
      type: object
      required:
      - abandoned_count
      - timeout_minutes
      title: CleanupResponse
      description: Response after cleanup
    CloneFromTemplateRequest:
      properties:
        pillar_id:
          type: string
          title: Pillar Id
          description: Pillar to clone from
        context_id:
          type: string
          title: Context Id
          description: New context ID
        name:
          type: string
          title: Name
          description: New context name
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
          description: New context description
        possible_states:
          anyOf:
          - items:
              additionalProperties: true
              type: object
            type: array
          - type: 'null'
          title: Possible States
          description: Custom states (uses template states if not provided)
      type: object
      required:
      - pillar_id
      - context_id
      - name
      title: CloneFromTemplateRequest
      description: Request to clone a pillar template.
    CodingListResponse:
      properties:
        codings:
          items:
            $ref: '#/components/schemas/CodingResponse'
          type: array
          title: Codings
        total:
          type: integer
          title: Total
      type: object
      required:
      - codings
      - total
      title: CodingListResponse
      description: List of codings for a PR.
    CodingResponse:
      properties:
        id:
          type: integer
          title: Id
        pr_number:
          type: integer
          title: Pr Number
        stakeholder_name:
          type: string
          title: Stakeholder Name
        context_id:
          type: string
          title: Context Id
        observation_type:
          type: string
          title: Observation Type
        relevance_accurate:
          anyOf:
          - type: boolean
          - type: 'null'
          title: Relevance Accurate
        current_state_accurate:
          anyOf:
          - type: boolean
          - type: 'null'
          title: Current State Accurate
        goal_state_accurate:
          anyOf:
          - type: boolean
          - type: 'null'
          title: Goal State Accurate
        overall_score_accurate:
          anyOf:
          - type: boolean
          - type: 'null'
          title: Overall Score Accurate
        suggested_relevance:
          anyOf:
          - type: number
          - type: 'null'
          title: Suggested Relevance
        suggested_current_state:
          anyOf:
          - type: string
          - type: 'null'
          title: Suggested Current State
        suggested_goal_state:
          anyOf:
          - type: string
          - type: 'null'
          title: Suggested Goal State
        notes:
          anyOf:
          - type: string
          - type: 'null'
          title: Notes
        coded_by:
          anyOf:
          - type: string
          - type: 'null'
          title: Coded By
        error_category:
          anyOf:
          - type: string
          - type: 'null'
          title: Error Category
        rating:
          anyOf:
          - type: number
          - type: 'null'
          title: Rating
        created_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Created At
        updated_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Updated At
      type: object
      required:
      - id
      - pr_number
      - stakeholder_name
      - context_id
      - observation_type
      title: CodingResponse
      description: Single coding in API response.
    CodingUpsert:
      properties:
        pr_number:
          type: integer
          exclusiveMinimum: 0.0
          title: Pr Number
        stakeholder_name:
          type: string
          minLength: 1
          title: Stakeholder Name
        context_id:
          type: string
          minLength: 1
          title: Context Id
        observation_type:
          type: string
          minLength: 1
          title: Observation Type
          default: alignment_score
        relevance_accurate:
          anyOf:
          - type: boolean
          - type: 'null'
          title: Relevance Accurate
        current_state_accurate:
          anyOf:
          - type: boolean
          - type: 'null'
          title: Current State Accurate
        goal_state_accurate:
          anyOf:
          - type: boolean
          - type: 'null'
          title: Goal State Accurate
        overall_score_accurate:
          anyOf:
          - type: boolean
          - type: 'null'
          title: Overall Score Accurate
        suggested_relevance:
          anyOf:
          - type: number
          - type: 'null'
          title: Suggested Relevance
        suggested_current_state:
          anyOf:
          - type: string
          - type: 'null'
          title: Suggested Current State
        suggested_goal_state:
          anyOf:
          - type: string
          - type: 'null'
          title: Suggested Goal State
        notes:
          anyOf:
          - type: string
          - type: 'null'
          title: Notes
        coded_by:
          anyOf:
          - type: string
          - type: 'null'
          title: Coded By
        error_category:
          anyOf:
          - type: string
          - type: 'null'
          title: Error Category
        rating:
          anyOf:
          - type: number
          - type: 'null'
          title: Rating
      type: object
      required:
      - pr_number
      - stakeholder_name
      - context_id
      title: CodingUpsert
      description: Create or update a single observation coding.
    CohortAlignmentRequest:
      properties:
        app_id:
          type: string
          title: App Id
        content:
          type: string
          title: Content
        beliefs:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Beliefs
        context_impacts:
          anyOf:
          - additionalProperties:
              $ref: '#/components/schemas/ContextImpact'
            type: object
          - type: 'null'
          title: Context Impacts
        scoring_mode:
          anyOf:
          - type: string
          - type: 'null'
          title: Scoring Mode
      type: object
      required:
      - app_id
      - content
      title: CohortAlignmentRequest
      description: Request for cohort-based alignment scoring against journey spec
        set_points.
    CohortAlignmentResponse:
      properties:
        app_id:
          type: string
          title: App Id
        weighted_score:
          type: number
          title: Weighted Score
        stage_scores:
          items:
            $ref: '#/components/schemas/StageAlignmentScore'
          type: array
          title: Stage Scores
        total_users:
          type: integer
          title: Total Users
          default: 0
        weighting_method:
          type: string
          title: Weighting Method
          default: equal
        duration_ms:
          type: integer
          title: Duration Ms
        errors:
          items:
            type: string
          type: array
          title: Errors
      type: object
      required:
      - app_id
      - weighted_score
      - stage_scores
      - duration_ms
      title: CohortAlignmentResponse
      description: Response for cohort-based alignment scoring.
    CohortCompareRequest:
      properties:
        app_id:
          type: string
          title: App Id
        metric:
          type: string
          title: Metric
          default: ltv
        percentile:
          type: integer
          maximum: 99.0
          minimum: 1.0
          title: Percentile
          default: 20
        from_stage:
          type: string
          title: From Stage
        to_stage:
          type: string
          title: To Stage
        filters:
          additionalProperties:
            type: string
          type: object
          title: Filters
        date_from:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date From
        date_to:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date To
      type: object
      required:
      - app_id
      - from_stage
      - to_stage
      title: CohortCompareRequest
      description: Request for filtered cohort transition comparison.
    CohortCompareResponse:
      properties:
        app_id:
          type: string
          title: App Id
        metric:
          type: string
          title: Metric
        from_stage:
          anyOf:
          - type: string
          - type: 'null'
          title: From Stage
        to_stage:
          anyOf:
          - type: string
          - type: 'null'
          title: To Stage
        top_segment:
          $ref: '#/components/schemas/CohortSegment'
        bottom_segment:
          $ref: '#/components/schemas/CohortSegment'
        gap:
          additionalProperties:
            type: number
          type: object
          title: Gap
          description: Differences between segments
      type: object
      required:
      - app_id
      - metric
      - top_segment
      - bottom_segment
      - gap
      title: CohortCompareResponse
      description: Comparison of top vs bottom cohorts for a transition.
    CohortMetrics:
      properties:
        cohort_name:
          type: string
          title: Cohort Name
          description: Display name, e.g. 'Top 20%'
        user_count:
          type: integer
          minimum: 0.0
          title: User Count
        conversion_rate:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Conversion Rate
        dominant_mode:
          anyOf:
          - type: string
          - type: 'null'
          title: Dominant Mode
          description: Agent-internal mode ID
        dominant_mode_plain:
          anyOf:
          - type: string
          - type: 'null'
          title: Dominant Mode Plain
          description: Plain language description of dominant mode
        sample_behaviors:
          items:
            type: string
          type: array
          title: Sample Behaviors
          description: Example behaviors observed in this cohort
      type: object
      required:
      - cohort_name
      - user_count
      - conversion_rate
      title: CohortMetrics
      description: Metrics for a single cohort (top 20% or bottom 80%).
    CohortProfileRequest:
      properties:
        app_id:
          type: string
          title: App Id
        metric:
          type: string
          title: Metric
          default: ltv
        percentile:
          type: integer
          maximum: 99.0
          minimum: 1.0
          title: Percentile
          default: 20
        profile_fields:
          items:
            type: string
          type: array
          maxItems: 5
          minItems: 1
          title: Profile Fields
        filters:
          additionalProperties:
            type: string
          type: object
          title: Filters
        date_from:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date From
        date_to:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date To
      type: object
      required:
      - app_id
      - profile_fields
      title: CohortProfileRequest
      description: Request for metadata profiling per cohort segment.
    CohortProfileResponse:
      properties:
        app_id:
          type: string
          title: App Id
        metric:
          type: string
          title: Metric
        percentile:
          type: integer
          title: Percentile
        top_user_count:
          type: integer
          title: Top User Count
        bottom_user_count:
          type: integer
          title: Bottom User Count
        profiles:
          items:
            $ref: '#/components/schemas/FieldProfile'
          type: array
          title: Profiles
        query_time_ms:
          type: integer
          title: Query Time Ms
      type: object
      required:
      - app_id
      - metric
      - percentile
      - top_user_count
      - bottom_user_count
      - profiles
      - query_time_ms
      title: CohortProfileResponse
      description: Response for cohort metadata profiling.
    CohortResponse:
      properties:
        app_id:
          type: string
          title: App Id
        metric:
          type: string
          title: Metric
          description: ltv, engagement, or conversion
        percentile:
          type: integer
          title: Percentile
          description: Percentile cutoff (e.g., 20 for top 20%)
        threshold_value:
          anyOf:
          - type: number
          - type: 'null'
          title: Threshold Value
          description: Value at percentile boundary
        segments:
          additionalProperties:
            $ref: '#/components/schemas/CohortSegment'
          type: object
          title: Segments
          description: '''top'' and ''bottom'' segments'
      type: object
      required:
      - app_id
      - metric
      - percentile
      - segments
      title: CohortResponse
      description: Cohort segmentation response.
    CohortSegment:
      properties:
        user_count:
          type: integer
          title: User Count
        avg_value:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Value
        conversion_rate:
          anyOf:
          - type: number
          - type: 'null'
          title: Conversion Rate
        avg_time_days:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Time Days
      type: object
      required:
      - user_count
      title: CohortSegment
      description: Metrics for a cohort segment.
    CohortSegmentRequest:
      properties:
        app_id:
          type: string
          title: App Id
        metric:
          type: string
          title: Metric
          description: ltv, engagement, conversion, or purchase_count
          default: ltv
        percentile:
          type: integer
          maximum: 99.0
          minimum: 1.0
          title: Percentile
          default: 20
        filters:
          additionalProperties:
            type: string
          type: object
          title: Filters
        date_from:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date From
        date_to:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date To
      type: object
      required:
      - app_id
      title: CohortSegmentRequest
      description: Request for cohort segmentation with optional filters.
    CohortUsersResponse:
      properties:
        app_id:
          type: string
          title: App Id
        metric:
          type: string
          title: Metric
        segment:
          type: string
          title: Segment
        user_ids:
          items:
            type: string
          type: array
          title: User Ids
        total:
          type: integer
          title: Total
      type: object
      required:
      - app_id
      - metric
      - segment
      - user_ids
      - total
      title: CohortUsersResponse
      description: Response for listing users in a segment.
    Concept:
      properties:
        variables:
          items:
            $ref: '#/components/schemas/Variable'
          type: array
          title: Variables
        relations:
          items:
            $ref: '#/components/schemas/Relation'
          type: array
          title: Relations
        priors:
          additionalProperties: true
          type: object
          title: Priors
        confidence:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Confidence
          default: 0.5
        calibration:
          additionalProperties:
            type: number
          type: object
          title: Calibration
      type: object
      title: Concept
    ConfidenceBucket:
      properties:
        bucket_label:
          type: string
          title: Bucket Label
        bucket_low:
          type: number
          title: Bucket Low
        bucket_high:
          type: number
          title: Bucket High
        count:
          type: integer
          title: Count
        avg_accuracy:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Accuracy
        avg_confidence:
          type: number
          title: Avg Confidence
      type: object
      required:
      - bucket_label
      - bucket_low
      - bucket_high
      - count
      - avg_accuracy
      - avg_confidence
      title: ConfidenceBucket
      description: Accuracy stats for a confidence range bucket.
    ConfidenceCalibrationResponse:
      properties:
        app_id:
          type: string
          title: App Id
        buckets:
          items:
            $ref: '#/components/schemas/ConfidenceBucket'
          type: array
          title: Buckets
        is_calibrated:
          anyOf:
          - type: boolean
          - type: 'null'
          title: Is Calibrated
      type: object
      required:
      - app_id
      - buckets
      title: ConfidenceCalibrationResponse
      description: Confidence calibration analysis.
    ConfirmGoalRequest:
      properties:
        confirmed_by:
          anyOf:
          - type: string
          - type: 'null'
          title: Confirmed By
      type: object
      title: ConfirmGoalRequest
    ConfirmPredictionRequest:
      properties:
        observer:
          anyOf:
          - type: string
          - type: 'null'
          title: Observer
        evidence:
          anyOf:
          - type: string
          - type: 'null'
          title: Evidence
      type: object
      title: ConfirmPredictionRequest
    ContextFormat:
      type: string
      enum:
      - ai_ready
      - raw
      - summary
      title: ContextFormat
      description: Output format for context data.
    ContextImpact:
      properties:
        from_state:
          type: string
          title: From State
        to_state:
          type: string
          title: To State
        goal_state:
          anyOf:
          - type: string
          - type: 'null'
          title: Goal State
        relevance:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Relevance
          default: 1.0
        possible_states:
          anyOf:
          - items:
              type: string
            type: array
          - type: 'null'
          title: Possible States
      type: object
      required:
      - from_state
      - to_state
      title: ContextImpact
      description: Explicit impact of a PR on a specific observation context.
    ContextQuery:
      properties:
        query:
          type: string
          title: Query
        observation_context:
          anyOf:
          - $ref: '#/components/schemas/ObservationContext'
          - type: 'null'
        budget_tokens:
          type: integer
          title: Budget Tokens
          default: 3000
        user_id:
          anyOf:
          - type: string
          - type: 'null'
          title: User Id
        include_cross_user:
          type: boolean
          title: Include Cross User
          default: false
      type: object
      required:
      - query
      title: ContextQuery
      description: Query for context assembly
    ContextRequest:
      properties:
        self_model_id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Self Model Id
          description: ID of the self-model to get context for
        user_id:
          anyOf:
          - type: string
          - type: 'null'
          title: User Id
          description: User ID - will use their primary self-model
        view_id:
          anyOf:
          - type: string
          - type: 'null'
          title: View Id
          description: Specific view to compute (being, becoming, etc.)
        app_id:
          anyOf:
          - type: string
          - type: 'null'
          title: App Id
          description: Filter context to episodes from this app (e.g., clarity-claw,
            mystica)
        format:
          $ref: '#/components/schemas/ContextFormat'
          description: Output format for context data
          default: ai_ready
        include_beliefs:
          type: boolean
          title: Include Beliefs
          description: Include beliefs in context
          default: true
        include_narrative:
          type: boolean
          title: Include Narrative
          description: Include narrative summary
          default: true
        include_recommendations:
          type: boolean
          title: Include Recommendations
          description: Include actionable recommendations
          default: true
        max_beliefs:
          type: integer
          maximum: 200.0
          minimum: 1.0
          title: Max Beliefs
          description: Maximum number of beliefs to include
          default: 50
      type: object
      title: ContextRequest
      description: 'Request for context assembly.


        Either self_model_id or user_id must be provided.'
    ContextResponse:
      properties:
        context_id:
          type: string
          title: Context Id
          description: Unique identifier for this context assembly
        format:
          $ref: '#/components/schemas/ContextFormat'
        computed_at:
          type: string
          format: date-time
          title: Computed At
        ai_ready:
          anyOf:
          - $ref: '#/components/schemas/AIReadyContext'
          - type: 'null'
        raw:
          anyOf:
          - $ref: '#/components/schemas/RawContext'
          - type: 'null'
        summary:
          anyOf:
          - $ref: '#/components/schemas/SummaryContext'
          - type: 'null'
        self_model_id:
          type: integer
          title: Self Model Id
        user_id:
          type: string
          title: User Id
        cache_ttl_seconds:
          type: integer
          title: Cache Ttl Seconds
          description: 'Informational: suggested cache duration in seconds. This is
            a hint for consumers and not configurable via request.'
          default: 300
      type: object
      required:
      - context_id
      - format
      - computed_at
      - self_model_id
      - user_id
      title: ContextResponse
      description: 'Response from context API.


        Contains one of the format-specific contexts based on the requested format.'
    ConversationListResponse:
      properties:
        conversations:
          items:
            $ref: '#/components/schemas/TransitionConversation'
          type: array
          title: Conversations
        total:
          type: integer
          title: Total
      type: object
      required:
      - conversations
      - total
      title: ConversationListResponse
      description: Response for listing conversations.
    ConversationMessage:
      properties:
        id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Id
        role:
          $ref: '#/components/schemas/MessageRole'
        content:
          type: string
          title: Content
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
        created_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Created At
      type: object
      required:
      - role
      - content
      title: ConversationMessage
      description: A single message in a transition conversation.
    ConversationMessageCreate:
      properties:
        role:
          $ref: '#/components/schemas/MessageRole'
        content:
          type: string
          title: Content
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
      type: object
      required:
      - role
      - content
      title: ConversationMessageCreate
      description: Request model for adding a message to a conversation.
    CreateBeliefRequest:
      properties:
        statement:
          type: string
          minLength: 10
          title: Statement
          description: Belief statement text
        category:
          type: string
          title: Category
          description: STATEMENT, FALSIFIABLE, CAUSAL, or PREDICTIVE
        pillar:
          type: string
          title: Pillar
          description: Pillar ID
          default: intellectual_health
        observation_context_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Observation Context Id
          description: Observation context (e.g., essay_longevity_metamorphosis)
        confidence:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Confidence
          description: Confidence 0-1
          default: 0.8
        connections:
          anyOf:
          - items:
              additionalProperties: true
              type: object
            type: array
          - type: 'null'
          title: Connections
          description: Connections to other beliefs
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
          description: Additional metadata (source_id, supporting_points, etc.)
        source_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Source Id
          description: External source ID (e.g., claim-bio-age)
      type: object
      required:
      - statement
      - category
      title: CreateBeliefRequest
      description: Request to create a single belief from an essay claim.
    CreateBeliefsRequest:
      properties:
        beliefs:
          items:
            $ref: '#/components/schemas/CreateBeliefRequest'
          type: array
          minItems: 1
          title: Beliefs
        observation_context_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Observation Context Id
          description: Default context for all beliefs (can be overridden per belief)
      type: object
      required:
      - beliefs
      title: CreateBeliefsRequest
      description: Request to create multiple beliefs (batch).
    CreateBeliefsResponse:
      properties:
        beliefs:
          items:
            $ref: '#/components/schemas/BeliefResponse'
          type: array
          title: Beliefs
        count:
          type: integer
          title: Count
      type: object
      required:
      - beliefs
      - count
      title: CreateBeliefsResponse
      description: Response for batch belief creation.
    CreateContextBeliefRequest:
      properties:
        content:
          type: string
          title: Content
          description: Belief statement (first-person)
        confidence:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Confidence
          default: 0.6
        belief_type:
          type: string
          title: Belief Type
          description: STATEMENT, FALSIFIABLE, or CAUSAL
          default: STATEMENT
        category:
          anyOf:
          - type: string
          - type: 'null'
          title: Category
          description: value, assumption, self_perception, principle, goal
        evidence_source:
          type: string
          title: Evidence Source
          description: 'Source: ''curated'', ''llm_extraction'', etc.'
          default: curated
        observation_context_id:
          type: string
          title: Observation Context Id
          description: Context this belief is about
      type: object
      required:
      - content
      - observation_context_id
      title: CreateContextBeliefRequest
    CreateEpisodeWithContextRequest:
      properties:
        domain_id:
          type: string
          title: Domain Id
          description: Pillar ID
        observation_context_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Observation Context Id
          description: Observation context within the pillar
        customer_journey_stage:
          anyOf:
          - type: string
          - type: 'null'
          title: Customer Journey Stage
          description: Customer journey stage
        episode_type:
          anyOf:
          - type: string
          - type: 'null'
          title: Episode Type
          description: Type of episode
        content:
          type: string
          title: Content
          description: Episode content
        engagement:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Engagement
          description: Engagement state
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
          description: Additional metadata
      type: object
      required:
      - domain_id
      - content
      title: CreateEpisodeWithContextRequest
      description: Request to create an episode with observation context support.
    CreateObservationContextRequest:
      properties:
        context_id:
          type: string
          title: Context Id
          description: Unique identifier (snake_case)
        name:
          type: string
          title: Name
          description: Human-readable name
        domain_id:
          type: string
          title: Domain Id
          description: Parent pillar ID
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
          description: Context description
        parent_context_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Parent Context Id
          description: Parent context for hierarchy
        possible_states:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Possible States
          description: Possible states for this context
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
          description: Additional metadata
        viability:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Viability
          description: 'Levin: set_point, regulated_variables, viability_threat'
        allostasis:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Allostasis
          description: 'Barrett: anticipated_costs, bodily_signals, interpretation_patterns'
        valence_states:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Valence States
          description: 'Solms: keyed states with experiential, felt_quality, action_readiness'
        generative_model:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Generative Model
          description: 'Friston: predictions, policies, disconfirmations'
        depth:
          type: integer
          maximum: 2.0
          minimum: 0.0
          title: Depth
          description: 'Hierarchy level: 0=root, 1=child, 2=grandchild'
          default: 0
      type: object
      required:
      - context_id
      - name
      - domain_id
      title: CreateObservationContextRequest
      description: Request to create an observation context.
    CreateSelfModelRequest:
      properties:
        name:
          type: string
          maxLength: 255
          minLength: 1
          title: Name
          description: Self-model name
        description:
          anyOf:
          - type: string
            maxLength: 1000
          - type: 'null'
          title: Description
        self_model_type:
          $ref: '#/components/schemas/SelfModelType'
          default: primary
        app_id:
          anyOf:
          - type: string
            maxLength: 100
          - type: 'null'
          title: App Id
          description: Application identifier (e.g., mystica, clarity-claw)
        external_id:
          anyOf:
          - type: string
            maxLength: 255
          - type: 'null'
          title: External Id
          description: App-specific idempotent lookup key (e.g., tenant:relationship_psychics)
        domains:
          items:
            $ref: '#/components/schemas/DomainDefinition'
          type: array
          minItems: 1
          title: Domains
        modes:
          items:
            $ref: '#/components/schemas/ModeDefinition'
          type: array
          title: Modes
        views:
          items:
            $ref: '#/components/schemas/ViewDefinition'
          type: array
          title: Views
      type: object
      required:
      - name
      - domains
      title: CreateSelfModelRequest
      description: Request to create a new self-model.
    CreateSelfModelResponse:
      properties:
        self_model_id:
          type: integer
          title: Self Model Id
        version:
          type: integer
          title: Version
          default: 1
        name:
          type: string
          title: Name
        created_at:
          type: string
          format: date-time
          title: Created At
      type: object
      required:
      - self_model_id
      - name
      - created_at
      title: CreateSelfModelResponse
      description: Response after creating a self-model.
    CreateSessionResponse:
      properties:
        session_id:
          type: string
          title: Session Id
        status:
          type: string
          title: Status
          default: created
      type: object
      required:
      - session_id
      title: CreateSessionResponse
      description: Response after creating a session
    CreateSoftUserRequest:
      properties:
        external_id:
          type: string
          maxLength: 255
          title: External Id
          description: Hashed external identifier (e.g., sha256 of email)
        source:
          type: string
          maxLength: 50
          title: Source
          description: Source system / provider (e.g., 'blog', 'heyclarity-website',
            'posthog')
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
        app_id:
          anyOf:
          - type: string
            maxLength: 100
          - type: 'null'
          title: App Id
          description: Application ID — scopes the self-model so episodes with this
            app_id match
      type: object
      required:
      - external_id
      - source
      title: CreateSoftUserRequest
    CreateSoftUserResponse:
      properties:
        user_id:
          type: string
          title: User Id
        self_model_id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Self Model Id
        is_new:
          type: boolean
          title: Is New
      type: object
      required:
      - user_id
      - is_new
      title: CreateSoftUserResponse
    CreativeDimensionAccuracy:
      properties:
        dimension:
          type: string
          title: Dimension
        value:
          type: string
          title: Value
        count:
          type: integer
          title: Count
        avg_accuracy:
          type: number
          title: Avg Accuracy
        avg_confidence:
          type: number
          title: Avg Confidence
        avg_predicted:
          type: number
          title: Avg Predicted
        avg_actual:
          type: number
          title: Avg Actual
      type: object
      required:
      - dimension
      - value
      - count
      - avg_accuracy
      - avg_confidence
      - avg_predicted
      - avg_actual
      title: CreativeDimensionAccuracy
      description: Accuracy stats for a single creative dimension value.
    CreativeInsightsResponse:
      properties:
        app_id:
          type: string
          title: App Id
        dimension_accuracies:
          items:
            $ref: '#/components/schemas/CreativeDimensionAccuracy'
          type: array
          title: Dimension Accuracies
        total_resolved:
          type: integer
          title: Total Resolved
      type: object
      required:
      - app_id
      - dimension_accuracies
      - total_resolved
      title: CreativeInsightsResponse
      description: Per-dimension creative accuracy insights.
    DeleteBeliefsRequest:
      properties:
        belief_ids:
          items:
            type: integer
          type: array
          title: Belief Ids
          description: List of belief IDs to delete
      type: object
      required:
      - belief_ids
      title: DeleteBeliefsRequest
    DomainContext:
      properties:
        domain_id:
          type: string
          title: Domain Id
        domain_name:
          type: string
          title: Domain Name
        episode_count:
          type: integer
          title: Episode Count
          default: 0
        engagement:
          additionalProperties:
            type: number
          type: object
          title: Engagement
        dominant_mode:
          anyOf:
          - type: string
          - type: 'null'
          title: Dominant Mode
        trend:
          anyOf:
          - type: string
          - type: 'null'
          title: Trend
          description: 'Trend direction: improving, declining, stable'
      type: object
      required:
      - domain_id
      - domain_name
      title: DomainContext
      description: Domain metrics for context.
    DomainDefinition:
      properties:
        id:
          type: string
          title: Id
          description: Unique domain identifier
        name:
          type: string
          title: Name
          description: Human-readable name
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
          description: Domain description
        keywords:
          anyOf:
          - items:
              type: string
            type: array
          - type: 'null'
          title: Keywords
          description: Associated keywords for tagging
      type: object
      required:
      - id
      - name
      title: DomainDefinition
      description: 'A domain within a self-model (e.g., Physical Health, Career).


        Domains are app-specific areas of attention.'
    DriveEngagement:
      properties:
        orientation:
          anyOf:
          - $ref: '#/components/schemas/DriveOrientation'
          - type: 'null'
          description: self-in-world (exploratory) vs world-in-self (protective)
        valence:
          anyOf:
          - $ref: '#/components/schemas/DriveValence'
          - type: 'null'
          description: approach vs avoidance
        intensity:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Intensity
          description: Drive strength
        goal_frame:
          anyOf:
          - type: string
          - type: 'null'
          title: Goal Frame
          description: Current high-level goal
      type: object
      title: DriveEngagement
      description: 'Drive orientation: world-in-self vs self-in-world.


        Where is the optimization pressure pointed?'
    DriveOrientation:
      type: string
      enum:
      - self-in-world
      - world-in-self
      - balanced
      title: DriveOrientation
      description: 'Drive orientation: self-in-world vs world-in-self.'
    DriveValence:
      type: string
      enum:
      - approach
      - avoidance
      - mixed
      title: DriveValence
      description: 'Drive valence: approach vs avoidance.'
    EnergyEngagement:
      properties:
        budget_physical:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Budget Physical
          description: Physical effort capacity
        budget_cognitive:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Budget Cognitive
          description: Cognitive effort capacity
        volatility:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Volatility
          description: Energy variability/stability
        subjective_state:
          anyOf:
          - type: string
          - type: 'null'
          title: Subjective State
          description: tired-but-wired, rested, depleted, etc.
        arousal:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Arousal
          description: Physiological activation level
        valence:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: -1.0
          - type: 'null'
          title: Valence
          description: Affective valence (-1 negative to +1 positive)
      type: object
      title: EnergyEngagement
      description: 'Metabolic context for action and learning.


        What is the available budget for changing the world and updating the model?'
    EngagementHypothesis:
      properties:
        source_mode:
          anyOf:
          - type: string
          - type: 'null'
          title: Source Mode
          description: Inferred source mode ID (agent-only)
        target_mode:
          anyOf:
          - type: string
          - type: 'null'
          title: Target Mode
          description: Inferred target mode ID (agent-only)
        source_mode_plain:
          anyOf:
          - type: string
          - type: 'null'
          title: Source Mode Plain
          description: 'Plain language: what users are currently doing'
        target_mode_plain:
          anyOf:
          - type: string
          - type: 'null'
          title: Target Mode Plain
          description: 'Plain language: what users need to shift to'
        mode_distribution:
          anyOf:
          - additionalProperties:
              type: number
            type: object
          - type: 'null'
          title: Mode Distribution
          description: Mode frequency distribution across episodes
      type: object
      title: EngagementHypothesis
      description: 'Agent-inferred engagement mode transition hypothesis.

        Mode IDs are internal — UI shows only plain language descriptions.'
    EngagementState:
      properties:
        sensory:
          anyOf:
          - $ref: '#/components/schemas/SensoryEngagement'
          - type: 'null'
        agency:
          anyOf:
          - $ref: '#/components/schemas/AgencyEngagement'
          - type: 'null'
        energy:
          anyOf:
          - $ref: '#/components/schemas/EnergyEngagement'
          - type: 'null'
        drive:
          anyOf:
          - $ref: '#/components/schemas/DriveEngagement'
          - type: 'null'
        epistemic:
          anyOf:
          - $ref: '#/components/schemas/EpistemicEngagement'
          - type: 'null'
        provenance:
          anyOf:
          - $ref: '#/components/schemas/ProvenanceEngagement'
          - type: 'null'
      type: object
      title: EngagementState
      description: 'Complete 6-quality engagement substrate.


        Universal model for any self-model episode.'
    EnvelopeListResponse:
      properties:
        envelopes:
          items:
            $ref: '#/components/schemas/InputEnvelopeStatus'
          type: array
          title: Envelopes
          description: List of envelopes
        total:
          type: integer
          title: Total
          description: Total count
      type: object
      required:
      - envelopes
      - total
      title: EnvelopeListResponse
      description: Response model for listing envelopes.
    EnvelopeStatsResponse:
      properties:
        pending:
          type: integer
          title: Pending
          description: Envelopes waiting to be queued
          default: 0
        queued:
          type: integer
          title: Queued
          description: Envelopes in the queue
          default: 0
        processing:
          type: integer
          title: Processing
          description: Envelopes currently being processed
          default: 0
        completed:
          type: integer
          title: Completed
          description: Successfully processed envelopes
          default: 0
        failed:
          type: integer
          title: Failed
          description: Failed envelopes
          default: 0
        total:
          type: integer
          title: Total
          description: Total envelope count
          default: 0
      type: object
      title: EnvelopeStatsResponse
      description: Response model for envelope statistics.
    EnvelopeStatusResponse:
      properties:
        envelope_id:
          type: string
          title: Envelope Id
          description: Input envelope ID
        status:
          type: string
          title: Status
          description: 'Processing status: pending|queued|processing|completed|failed'
        episode_id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Episode Id
          description: Created episode ID (when completed)
        belief_ids:
          items:
            type: integer
          type: array
          title: Belief Ids
          description: Created belief IDs (when completed)
        error_message:
          anyOf:
          - type: string
          - type: 'null'
          title: Error Message
          description: Error message if failed
      type: object
      required:
      - envelope_id
      - status
      title: EnvelopeStatusResponse
      description: Response for envelope status polling.
    Episode:
      properties:
        id:
          anyOf:
          - type: integer
          - type: string
          title: Id
        who:
          type: string
          title: Who
          description: Self or other(s)
          default: self
        when:
          type: string
          format: date-time
          title: When
        where:
          anyOf:
          - type: string
          - type: 'null'
          title: Where
        affect:
          $ref: '#/components/schemas/Affect'
        intent:
          type: string
          title: Intent
          description: What was being attempted
        outcome:
          type: string
          title: Outcome
          description: What actually happened
        extracts:
          items:
            type: string
          type: array
          title: Extracts
          description: Key quotes/anchors
        pillar_tags:
          items:
            type: string
          type: array
          title: Pillar Tags
        beliefs_applied:
          items:
            type: string
          type: array
          title: Beliefs Applied
      type: object
      required:
      - affect
      - intent
      - outcome
      title: Episode
    EpisodeListResponse:
      properties:
        episodes:
          items:
            $ref: '#/components/schemas/src__models__journey__JourneyEpisode'
          type: array
          title: Episodes
        total:
          type: integer
          title: Total
        has_more:
          type: boolean
          title: Has More
      type: object
      required:
      - episodes
      - total
      - has_more
      title: EpisodeListResponse
      description: Response for listing episodes.
    EpisodeSummary:
      properties:
        total_episodes:
          type: integer
          title: Total Episodes
        by_stage:
          additionalProperties:
            type: integer
          type: object
          title: By Stage
        by_archetype:
          additionalProperties:
            type: integer
          type: object
          title: By Archetype
        date_range:
          anyOf:
          - type: string
          - type: 'null'
          title: Date Range
        avg_sentiment:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Sentiment
        common_themes:
          items:
            type: string
          type: array
          title: Common Themes
      type: object
      required:
      - total_episodes
      title: EpisodeSummary
      description: Summary statistics for a set of episodes.
    EpisodeWithContextResponse:
      properties:
        id:
          type: integer
          title: Id
        self_model_id:
          type: integer
          title: Self Model Id
        domain_id:
          type: string
          title: Domain Id
        observation_context_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Observation Context Id
        customer_journey_stage:
          anyOf:
          - type: string
          - type: 'null'
          title: Customer Journey Stage
        episode_type:
          anyOf:
          - type: string
          - type: 'null'
          title: Episode Type
        content:
          type: string
          title: Content
        engagement:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Engagement
        inferred_mode_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Inferred Mode Id
        created_at:
          type: string
          format: date-time
          title: Created At
      type: object
      required:
      - id
      - self_model_id
      - domain_id
      - content
      - created_at
      title: EpisodeWithContextResponse
      description: Response for episode with context.
    EpistemicEngagement:
      properties:
        curiosity:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Curiosity
          description: Interest in novelty
        confusion:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Confusion
          description: Bewilderment level
        boredom:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Boredom
          description: Disengagement level
        exploration_weight:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Exploration Weight
          description: Epistemic vs pragmatic value weighting
        uncertainty_tolerance:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Uncertainty Tolerance
          description: Comfort with ambiguity
        update_style:
          anyOf:
          - type: string
          - type: 'null'
          title: Update Style
          description: broad-exploration, narrow-confirmation, avoidance, etc.
      type: object
      title: EpistemicEngagement
      description: 'Epistemic emotions and learning orientation.


        How much do I care about uncertainty right now?'
    Evidence:
      properties:
        episode_id:
          type: string
          title: Episode Id
        metric:
          type: string
          title: Metric
        result:
          type: string
          title: Result
      type: object
      required:
      - episode_id
      - metric
      - result
      title: Evidence
    EvidenceItem:
      properties:
        source:
          type: string
          title: Source
        weight:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Weight
          description: Strength of evidence
        supports:
          type: boolean
          title: Supports
          description: True if evidence supports hypothesis
        timestamp:
          type: string
          format: date-time
          title: Timestamp
      type: object
      required:
      - source
      - weight
      - supports
      title: EvidenceItem
      description: Individual piece of evidence for/against hypothesis
    ExpressedBelief:
      properties:
        content:
          type: string
          title: Content
        confidence:
          type: number
          title: Confidence
        force_type:
          anyOf:
          - $ref: '#/components/schemas/src__models__journey__ForceType__1'
          - type: 'null'
        source_episode_id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Source Episode Id
      type: object
      required:
      - content
      - confidence
      title: ExpressedBelief
      description: A belief expressed during a JTBD phase.
    FailSessionRequest:
      properties:
        error_message:
          type: string
          title: Error Message
          description: Error message describing failure
      type: object
      required:
      - error_message
      title: FailSessionRequest
      description: Request to mark session as failed
    FeatureImportance:
      properties:
        dimension:
          type: string
          title: Dimension
        distinct_values:
          type: integer
          title: Distinct Values
        accuracy_range:
          type: number
          title: Accuracy Range
        best_value:
          anyOf:
          - type: string
          - type: 'null'
          title: Best Value
        best_accuracy:
          anyOf:
          - type: number
          - type: 'null'
          title: Best Accuracy
        worst_value:
          anyOf:
          - type: string
          - type: 'null'
          title: Worst Value
        worst_accuracy:
          anyOf:
          - type: number
          - type: 'null'
          title: Worst Accuracy
      type: object
      required:
      - dimension
      - distinct_values
      - accuracy_range
      - best_value
      - best_accuracy
      - worst_value
      - worst_accuracy
      title: FeatureImportance
      description: Predictive importance of a creative dimension.
    FeatureImportanceResponse:
      properties:
        app_id:
          type: string
          title: App Id
        features:
          items:
            $ref: '#/components/schemas/FeatureImportance'
          type: array
          title: Features
      type: object
      required:
      - app_id
      - features
      title: FeatureImportanceResponse
      description: Feature importance ranking across dimensions.
    FieldProfile:
      properties:
        field:
          type: string
          title: Field
        top_values:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Top Values
        bottom_values:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Bottom Values
        whale_index:
          items:
            $ref: '#/components/schemas/WhaleIndexEntry'
          type: array
          title: Whale Index
      type: object
      required:
      - field
      title: FieldProfile
      description: Profile of a single metadata field across segments.
    Force:
      properties:
        force_type:
          $ref: '#/components/schemas/src__models__journey__ForceType__1'
        summary:
          type: string
          title: Summary
          description: One-sentence summary of this force
        strength:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Strength
          description: Relative strength (0-1)
        evidence:
          items:
            type: string
          type: array
          title: Evidence
          description: Supporting quotes/observations
        belief_ids:
          items:
            type: integer
          type: array
          title: Belief Ids
          description: Related belief IDs
      type: object
      required:
      - force_type
      - summary
      - strength
      title: Force
      description: A single force in the JTBD framework.
    ForcesAnalysis:
      properties:
        push:
          $ref: '#/components/schemas/Force'
        pull:
          $ref: '#/components/schemas/Force'
        habit:
          $ref: '#/components/schemas/Force'
        anxiety:
          $ref: '#/components/schemas/Force'
        net_motivation:
          type: number
          title: Net Motivation
          description: (push + pull) - (habit + anxiety)
        dominant_force:
          $ref: '#/components/schemas/src__models__journey__ForceType__1'
      type: object
      required:
      - push
      - pull
      - habit
      - anxiety
      - net_motivation
      - dominant_force
      title: ForcesAnalysis
      description: Analysis of all forces for a user/phase.
    ForcesSummary:
      properties:
        forces:
          items:
            $ref: '#/components/schemas/InferredForce'
          type: array
          title: Forces
        dominant_force:
          anyOf:
          - $ref: '#/components/schemas/src__models__journey__ForceType__2'
          - type: 'null'
          description: The strongest force
        summary_text:
          type: string
          title: Summary Text
          description: One-sentence plain language summary
      type: object
      required:
      - summary_text
      title: ForcesSummary
      description: Summary of all inferred forces for a transition.
    FormatInfo:
      properties:
        id:
          type: string
          title: Id
        name:
          type: string
          title: Name
        description:
          type: string
          title: Description
        use_cases:
          items:
            type: string
          type: array
          title: Use Cases
      type: object
      required:
      - id
      - name
      - description
      title: FormatInfo
      description: Information about a context format.
    FunnelResponse:
      properties:
        app_id:
          type: string
          title: App Id
        date_from:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date From
        date_to:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date To
        segment:
          anyOf:
          - type: string
          - type: 'null'
          title: Segment
          description: all, top_20, or bottom_80
        stages:
          items:
            $ref: '#/components/schemas/StageMetrics'
          type: array
          title: Stages
        transitions:
          items:
            $ref: '#/components/schemas/TransitionMetrics'
          type: array
          title: Transitions
        summary:
          $ref: '#/components/schemas/FunnelSummary'
        computed_at:
          type: string
          format: date-time
          title: Computed At
      type: object
      required:
      - app_id
      - stages
      - transitions
      - summary
      - computed_at
      title: FunnelResponse
      description: Full funnel analytics response.
    FunnelSummary:
      properties:
        total_users:
          type: integer
          title: Total Users
        biggest_gap_pp:
          anyOf:
          - type: integer
          - type: 'null'
          title: Biggest Gap Pp
        avg_gap_pp:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Gap Pp
        total_opportunity:
          anyOf:
          - type: string
          - type: 'null'
          title: Total Opportunity
      type: object
      required:
      - total_users
      title: FunnelSummary
      description: Summary metrics for the entire funnel.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    Hypothesis:
      properties:
        hypothesis_id:
          type: string
          title: Hypothesis Id
        type:
          $ref: '#/components/schemas/HypothesisType'
        premise:
          type: string
          title: Premise
        expected_effect:
          additionalProperties:
            additionalProperties:
              type: number
            type: object
          type: object
          title: Expected Effect
        test:
          $ref: '#/components/schemas/TestDesign'
        evidence:
          items:
            $ref: '#/components/schemas/EvidenceItem'
          type: array
          title: Evidence
        acceptance_threshold:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Acceptance Threshold
          default: 0.6
        status:
          $ref: '#/components/schemas/HypothesisStatus'
          default: proposed
      type: object
      required:
      - type
      - premise
      - expected_effect
      - test
      title: Hypothesis
    HypothesisStatus:
      type: string
      enum:
      - proposed
      - running
      - accepted
      - rejected
      title: HypothesisStatus
    HypothesisType:
      type: string
      enum:
      - latent_factor
      - reframe
      - context_switch
      title: HypothesisType
    IdentityInfo:
      properties:
        provider:
          type: string
          title: Provider
        external_id:
          type: string
          title: External Id
        created_at:
          anyOf:
          - type: string
          - type: 'null'
          title: Created At
      type: object
      required:
      - provider
      - external_id
      title: IdentityInfo
    InferredForce:
      properties:
        force_type:
          $ref: '#/components/schemas/src__models__journey__ForceType__2'
        strength:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Strength
          description: How strongly this force is present (0-1)
        explanation:
          type: string
          title: Explanation
          description: Plain language explanation
        engagement_signals:
          items:
            type: string
          type: array
          title: Engagement Signals
          description: Engagement patterns that contributed
      type: object
      required:
      - force_type
      - strength
      - explanation
      title: InferredForce
      description: A single force inferred from engagement patterns.
    InputEnvelopeCreate:
      properties:
        user_id:
          type: string
          title: User Id
          description: User who submitted this envelope
        input_type:
          type: string
          title: Input Type
          description: Type of envelope
        payload:
          additionalProperties: true
          type: object
          title: Payload
          description: The envelope data
        session_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Session Id
          description: Optional session ID
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
          description: Optional metadata
        correlation_id:
          anyOf:
          - type: string
            format: uuid
          - type: 'null'
          title: Correlation Id
          description: For distributed tracing
        causation_id:
          anyOf:
          - type: string
            format: uuid
          - type: 'null'
          title: Causation Id
          description: For distributed tracing
      type: object
      required:
      - user_id
      - input_type
      - payload
      title: InputEnvelopeCreate
      description: Request model for creating an input envelope.
    InputEnvelopeResponse:
      properties:
        envelope_id:
          type: string
          format: uuid
          title: Envelope Id
          description: Unique envelope identifier
        status:
          type: string
          title: Status
          description: Current status (queued)
        message:
          type: string
          title: Message
          description: Human-readable message
      type: object
      required:
      - envelope_id
      - status
      - message
      title: InputEnvelopeResponse
      description: Response model for envelope submission (202 Accepted).
    InputEnvelopeStatus:
      properties:
        envelope_id:
          type: string
          format: uuid
          title: Envelope Id
          description: Unique envelope identifier
        status:
          type: string
          title: Status
          description: Processing status
        attempt_count:
          type: integer
          title: Attempt Count
          description: Number of processing attempts
        episode_id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Episode Id
          description: Episode ID if created
        belief_ids:
          items:
            type: integer
          type: array
          title: Belief Ids
          description: Belief IDs if extracted
        error_message:
          anyOf:
          - type: string
          - type: 'null'
          title: Error Message
          description: Error message if failed
        created_at:
          type: string
          format: date-time
          title: Created At
          description: When envelope was created
        completed_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Completed At
          description: When processing completed
      type: object
      required:
      - envelope_id
      - status
      - attempt_count
      - created_at
      title: InputEnvelopeStatus
      description: Response model for envelope status check.
    InputResponse:
      properties:
        status:
          type: string
          title: Status
          description: 'Processing status: success|partial|failed'
        envelope_id:
          type: string
          title: Envelope Id
          description: Input envelope ID
        ingestion_event_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Ingestion Event Id
          description: Ingestion event UUID
        results:
          $ref: '#/components/schemas/ProcessingResult'
          description: Processing results
        errors:
          items:
            type: string
          type: array
          title: Errors
          description: Top-level errors
      type: object
      required:
      - status
      - envelope_id
      - results
      title: InputResponse
      description: Response from /inputs endpoint
    InsightEvidence:
      properties:
        episode_count:
          type: integer
          title: Episode Count
          description: Number of episodes analyzed
        confidence:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Confidence
          description: Confidence score (0-1)
        sample_quotes:
          items:
            type: string
          type: array
          title: Sample Quotes
          description: Representative quotes from episodes
        statistical_significance:
          anyOf:
          - type: boolean
          - type: 'null'
          title: Statistical Significance
          description: Whether gap is statistically significant
      type: object
      required:
      - episode_count
      - confidence
      title: InsightEvidence
      description: Evidence supporting an insight.
    InsightOpportunity:
      properties:
        value_usd:
          anyOf:
          - type: number
          - type: 'null'
          title: Value Usd
          description: Estimated dollar value if addressed
        target_improvement_pp:
          type: number
          title: Target Improvement Pp
          description: Target improvement in percentage points
        hypothesis:
          type: string
          title: Hypothesis
          description: Hypothesis for why improvement would work
        suggested_actions:
          items:
            type: string
          type: array
          title: Suggested Actions
          description: Recommended actions
      type: object
      required:
      - target_improvement_pp
      - hypothesis
      title: InsightOpportunity
      description: Business opportunity associated with an insight.
    JTBDPhase:
      type: string
      enum:
      - first_thought
      - passive_looking
      - active_looking
      - deciding
      - consuming
      - satisfaction
      title: JTBDPhase
      description: Jobs-to-be-Done customer journey phases (6-stage JTBD Timeline).
    JTBDPhaseDetail:
      properties:
        user_id:
          type: string
          title: User Id
        app_id:
          type: string
          title: App Id
        phase:
          $ref: '#/components/schemas/JTBDPhase'
        phase_name:
          type: string
          title: Phase Name
        job_type:
          anyOf:
          - type: string
          - type: 'null'
          title: Job Type
          description: Inferred job type (Functional, Emotional, Social)
        attention_policy:
          $ref: '#/components/schemas/AttentionPolicy'
        solutions_considered:
          $ref: '#/components/schemas/SolutionsConsidered'
        forces:
          $ref: '#/components/schemas/ForcesAnalysis'
        expressed_beliefs:
          items:
            $ref: '#/components/schemas/ExpressedBelief'
          type: array
          title: Expressed Beliefs
        episode_count:
          type: integer
          title: Episode Count
        date_range:
          anyOf:
          - type: string
          - type: 'null'
          title: Date Range
        computed_at:
          type: string
          format: date-time
          title: Computed At
      type: object
      required:
      - user_id
      - app_id
      - phase
      - phase_name
      - attention_policy
      - solutions_considered
      - forces
      - episode_count
      - computed_at
      title: JTBDPhaseDetail
      description: Detailed JTBD analysis for a specific phase.
    JTBDPhaseSummary:
      properties:
        phase:
          $ref: '#/components/schemas/JTBDPhase'
        phase_name:
          type: string
          title: Phase Name
        entered_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Entered At
        exited_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Exited At
        episode_count:
          type: integer
          title: Episode Count
        duration_days:
          anyOf:
          - type: number
          - type: 'null'
          title: Duration Days
      type: object
      required:
      - phase
      - phase_name
      - episode_count
      title: JTBDPhaseSummary
      description: Summary of a single JTBD phase.
    JourneyResponse:
      properties:
        user_id:
          type: string
          title: User Id
        app_id:
          type: string
          title: App Id
        stages_visited:
          items:
            type: string
          type: array
          title: Stages Visited
        stage_transitions:
          items:
            $ref: '#/components/schemas/StageTransition'
          type: array
          title: Stage Transitions
        episodes:
          items:
            $ref: '#/components/schemas/src__models__analytics__JourneyEpisode'
          type: array
          title: Episodes
        signals:
          anyOf:
          - $ref: '#/components/schemas/BehavioralSignals'
          - type: 'null'
        episode_count:
          type: integer
          title: Episode Count
      type: object
      required:
      - user_id
      - app_id
      - stages_visited
      - stage_transitions
      - episodes
      - episode_count
      title: JourneyResponse
      description: Response for user journey query (E.2).
    JourneyStage:
      properties:
        id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Id
        app_id:
          type: string
          title: App Id
        name:
          type: string
          title: Name
          description: Stage identifier (e.g., 'awareness')
        display_name:
          anyOf:
          - type: string
          - type: 'null'
          title: Display Name
          description: Human-readable name
        stage_order:
          type: integer
          minimum: 1.0
          title: Stage Order
          description: Order in funnel (1 = first)
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
        created_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Created At
      type: object
      required:
      - app_id
      - name
      - stage_order
      title: JourneyStage
      description: A single stage in the customer journey funnel.
    JourneyStageCreate:
      properties:
        name:
          type: string
          title: Name
        display_name:
          anyOf:
          - type: string
          - type: 'null'
          title: Display Name
        stage_order:
          type: integer
          minimum: 1.0
          title: Stage Order
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
      type: object
      required:
      - name
      - stage_order
      title: JourneyStageCreate
      description: Request model for creating a journey stage.
    JourneyStagesResponse:
      properties:
        app_id:
          type: string
          title: App Id
        stages:
          items:
            $ref: '#/components/schemas/JourneyStage'
          type: array
          title: Stages
      type: object
      required:
      - app_id
      - stages
      title: JourneyStagesResponse
      description: Response model for listing journey stages.
    LinkEpisodesRequest:
      properties:
        episode_ids:
          items:
            type: integer
          type: array
          title: Episode Ids
      type: object
      required:
      - episode_ids
      title: LinkEpisodesRequest
      description: Link episodes to a recommendation.
    LinkEpisodesResponse:
      properties:
        linked_count:
          type: integer
          title: Linked Count
        already_linked:
          type: integer
          title: Already Linked
      type: object
      required:
      - linked_count
      - already_linked
      title: LinkEpisodesResponse
      description: Response from linking episodes.
    ListBeliefsResponse:
      properties:
        beliefs:
          items:
            $ref: '#/components/schemas/BeliefResponse'
          type: array
          title: Beliefs
        count:
          type: integer
          title: Count
      type: object
      required:
      - beliefs
      - count
      title: ListBeliefsResponse
      description: Response for listing beliefs.
    ListFormatsResponse:
      properties:
        formats:
          items:
            $ref: '#/components/schemas/FormatInfo'
          type: array
          title: Formats
        default_format:
          type: string
          title: Default Format
          default: ai_ready
      type: object
      required:
      - formats
      title: ListFormatsResponse
      description: Response listing available context formats.
    ListObservationContextsResponse:
      properties:
        contexts:
          items:
            $ref: '#/components/schemas/ObservationContextResponse'
          type: array
          title: Contexts
        count:
          type: integer
          title: Count
      type: object
      required:
      - contexts
      - count
      title: ListObservationContextsResponse
      description: Response for listing observation contexts.
    ListPillarTemplatesResponse:
      properties:
        templates:
          items:
            $ref: '#/components/schemas/PillarTemplateResponse'
          type: array
          title: Templates
        count:
          type: integer
          title: Count
      type: object
      required:
      - templates
      - count
      title: ListPillarTemplatesResponse
      description: Response for listing pillar templates.
    MergeContextsRequest:
      properties:
        source_context_id:
          type: string
          title: Source Context Id
        target_context_id:
          type: string
          title: Target Context Id
      type: object
      required:
      - source_context_id
      - target_context_id
      title: MergeContextsRequest
    MessageRole:
      type: string
      enum:
      - user
      - assistant
      - system
      title: MessageRole
      description: Role of message sender in conversation.
    MetadataAggregateRequest:
      properties:
        app_id:
          type: string
          title: App Id
        metadata_field:
          type: string
          title: Metadata Field
        metrics:
          items:
            type: string
          type: array
          title: Metrics
          default:
          - count
        filters:
          additionalProperties:
            type: string
          type: object
          title: Filters
        date_from:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date From
        date_to:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Date To
        cross_tabulate:
          anyOf:
          - type: string
          - type: 'null'
          title: Cross Tabulate
        limit:
          type: integer
          maximum: 1000.0
          title: Limit
          default: 100
      type: object
      required:
      - app_id
      - metadata_field
      title: MetadataAggregateRequest
      description: Request for metadata field aggregation (E.5).
    MetadataAggregateResponse:
      properties:
        field:
          type: string
          title: Field
        aggregations:
          items:
            $ref: '#/components/schemas/MetadataValue'
          type: array
          title: Aggregations
        query_time_ms:
          type: integer
          title: Query Time Ms
      type: object
      required:
      - field
      - aggregations
      - query_time_ms
      title: MetadataAggregateResponse
      description: Response for metadata aggregation.
    MetadataValue:
      properties:
        value:
          anyOf:
          - type: string
          - type: 'null'
          title: Value
        metrics:
          additionalProperties:
            type: integer
          type: object
          title: Metrics
        cross_tab:
          anyOf:
          - additionalProperties:
              additionalProperties:
                type: integer
              type: object
            type: object
          - type: 'null'
          title: Cross Tab
      type: object
      required:
      - value
      - metrics
      title: MetadataValue
      description: Aggregation for a single metadata value.
    ModeDefinition:
      properties:
        id:
          type: string
          title: Id
          description: Unique mode identifier
        name:
          type: string
          title: Name
          description: Human-readable name
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
          description: Mode description
        target_engagement:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Target Engagement
          description: Target engagement state for this mode (used for inference)
      type: object
      required:
      - id
      - name
      title: ModeDefinition
      description: 'A mode within a self-model (e.g., Create, Learn, Recover).


        Modes are composed engagement patterns that the app recognizes.'
    NarrativeCohortComparison:
      properties:
        top_cohort:
          $ref: '#/components/schemas/CohortMetrics'
        bottom_cohort:
          $ref: '#/components/schemas/CohortMetrics'
        key_differences:
          items:
            type: string
          type: array
          title: Key Differences
          description: Plain language behavioral differences
        comparison_narrative:
          type: string
          title: Comparison Narrative
          description: One-paragraph narrative explaining what top performers do differently
      type: object
      required:
      - top_cohort
      - bottom_cohort
      - comparison_narrative
      title: NarrativeCohortComparison
      description: 'Enhanced cohort comparison for agent narratives.

        Compares top 20% performers with bottom 80% using engagement data.'
    ObservationContext:
      properties:
        pillars:
          items:
            type: string
          type: array
          title: Pillars
        conditions:
          additionalProperties:
            type: string
          type: object
          title: Conditions
        time_range:
          anyOf:
          - type: string
          - type: 'null'
          title: Time Range
        social_context:
          anyOf:
          - type: string
          - type: 'null'
          title: Social Context
      type: object
      title: ObservationContext
      description: Context for observations and beliefs
    ObservationContextResponse:
      properties:
        id:
          type: integer
          title: Id
        context_id:
          type: string
          title: Context Id
        name:
          type: string
          title: Name
        domain_id:
          type: string
          title: Domain Id
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
        parent_context_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Parent Context Id
        possible_states:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Possible States
        current_state_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Current State Id
        observed_state_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Observed State Id
        predicted_state_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Predicted State Id
        goal_state_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Goal State Id
        engagement:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Engagement
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
        viability:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Viability
        allostasis:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Allostasis
        valence_states:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Valence States
        generative_model:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Generative Model
        depth:
          type: integer
          title: Depth
          default: 0
        created_at:
          type: string
          format: date-time
          title: Created At
        updated_at:
          type: string
          format: date-time
          title: Updated At
      type: object
      required:
      - id
      - context_id
      - name
      - domain_id
      - created_at
      - updated_at
      title: ObservationContextResponse
      description: Response for observation context.
    ObserveStateRequest:
      properties:
        observed_state:
          type: string
          title: Observed State
        observer:
          anyOf:
          - type: string
          - type: 'null'
          title: Observer
        confidence:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Confidence
          default: 1.0
        evidence:
          anyOf:
          - type: string
          - type: 'null'
          title: Evidence
      type: object
      required:
      - observed_state
      title: ObserveStateRequest
    OnCourseStatus:
      type: string
      enum:
      - strongly_aligned
      - newly_aligned
      - improving
      - stable
      - recovering
      - temporary_dip
      - declining
      - variable
      - insufficient_data
      title: OnCourseStatus
      description: Status indicators for alignment trajectory.
    OnboardingRequest:
      properties:
        email:
          type: string
          title: Email
          description: User email address
        external_id:
          anyOf:
          - type: string
          - type: 'null'
          title: External Id
          description: External system user ID
        app_id:
          anyOf:
          - type: string
          - type: 'null'
          title: App Id
          description: Application ID (e.g., mystica, clarity)
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
          description: Additional user metadata
          default: {}
      type: object
      required:
      - email
      title: OnboardingRequest
      description: Request to register/lookup an external user
    OnboardingResponse:
      properties:
        user_id:
          type: string
          title: User Id
          description: Internal SLA user ID
        external_id:
          anyOf:
          - type: string
          - type: 'null'
          title: External Id
          description: External system user ID
        email:
          type: string
          title: Email
          description: User email
        created:
          type: boolean
          title: Created
          description: True if user was newly created
        self_model_id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Self Model Id
          description: Self-model ID if exists
      type: object
      required:
      - user_id
      - email
      - created
      title: OnboardingResponse
      description: Response with user registration details
    PillarTemplateResponse:
      properties:
        id:
          type: string
          title: Id
        name:
          type: string
          title: Name
        description:
          type: string
          title: Description
        possible_states:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Possible States
      type: object
      required:
      - id
      - name
      - description
      - possible_states
      title: PillarTemplateResponse
      description: Response for a pillar template.
    Prediction:
      properties:
        target:
          type: string
          title: Target
        forecast:
          additionalProperties: true
          type: object
          title: Forecast
      type: object
      required:
      - target
      - forecast
      title: Prediction
    PredictionInput:
      properties:
        app_id:
          type: string
          title: App Id
        predicted_metric:
          type: string
          title: Predicted Metric
        ad_hook:
          anyOf:
          - type: string
          - type: 'null'
          title: Ad Hook
        ad_story:
          anyOf:
          - type: string
          - type: 'null'
          title: Ad Story
        ad_close:
          anyOf:
          - type: string
          - type: 'null'
          title: Ad Close
        traffic_source:
          anyOf:
          - type: string
          - type: 'null'
          title: Traffic Source
      type: object
      required:
      - app_id
      - predicted_metric
      title: PredictionInput
      description: Input for calibrated prediction.
    PredictionMatchDetail:
      properties:
        dimension:
          type: string
          title: Dimension
        value:
          type: string
          title: Value
        match_count:
          type: integer
          title: Match Count
        avg_accuracy:
          type: number
          title: Avg Accuracy
        avg_actual:
          type: number
          title: Avg Actual
      type: object
      required:
      - dimension
      - value
      - match_count
      - avg_accuracy
      - avg_actual
      title: PredictionMatchDetail
      description: Historical match detail for a single dimension.
    ProcessingResult:
      properties:
        episode_id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Episode Id
          description: Created episode ID
        belief_ids:
          items:
            type: integer
          type: array
          title: Belief Ids
          description: Created belief IDs
        new_beliefs:
          items:
            $ref: '#/components/schemas/BeliefObject'
          type: array
          title: New Beliefs
          description: Created belief objects for syncing to Clarity
        self_model_updated:
          type: boolean
          title: Self Model Updated
          description: Whether self-model was updated
          default: false
        errors:
          items:
            type: string
          type: array
          title: Errors
          description: Processing errors
      type: object
      title: ProcessingResult
      description: Result of processing an input envelope
    ProjectEngagementRequest:
      properties:
        hypotheses:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Hypotheses
          description: 'List of hypothetical engagements: [{domain_id, engagement,
            description?}]'
        horizon_days:
          type: integer
          maximum: 365.0
          minimum: 1.0
          title: Horizon Days
          description: Projection horizon in days
          default: 7
      type: object
      required:
      - hypotheses
      title: ProjectEngagementRequest
      description: Request for engagement projection.
    ProjectGoalRequest:
      properties:
        goal_engagement:
          additionalProperties: true
          type: object
          title: Goal Engagement
          description: Desired future engagement state
        horizon_days:
          type: integer
          maximum: 365.0
          minimum: 1.0
          title: Horizon Days
          default: 30
      type: object
      required:
      - goal_engagement
      title: ProjectGoalRequest
      description: Request for goal-seeking projection.
    ProjectModeTransitionRequest:
      properties:
        target_mode_id:
          type: string
          title: Target Mode Id
          description: ID of target mode
        horizon_days:
          type: integer
          maximum: 365.0
          minimum: 1.0
          title: Horizon Days
          default: 7
      type: object
      required:
      - target_mode_id
      title: ProjectModeTransitionRequest
      description: Request for mode transition projection.
    PromptCategory:
      type: string
      enum:
      - analysis
      - drill_down
      - comparison
      - recommendation
      - exploration
      title: PromptCategory
      description: Categories of agent prompt templates.
    PromptListResponse:
      properties:
        prompts:
          items:
            $ref: '#/components/schemas/PromptTemplate'
          type: array
          title: Prompts
        by_category:
          additionalProperties:
            items:
              type: string
            type: array
          propertyNames:
            $ref: '#/components/schemas/PromptCategory'
          type: object
          title: By Category
          description: Prompt IDs grouped by category
      type: object
      required:
      - prompts
      title: PromptListResponse
      description: Response for listing available prompts.
    PromptTemplate:
      properties:
        id:
          type: string
          title: Id
        name:
          type: string
          title: Name
          description: Display name for the prompt
        category:
          $ref: '#/components/schemas/PromptCategory'
        description:
          type: string
          title: Description
          description: What this prompt helps with
        template:
          type: string
          title: Template
          description: The prompt template with {placeholders}
        required_context:
          items:
            type: string
          type: array
          title: Required Context
          description: Context needed (e.g., 'from_stage', 'user_id')
        example_output:
          anyOf:
          - type: string
          - type: 'null'
          title: Example Output
          description: Example of what agent might respond
        suggested_followups:
          items:
            type: string
          type: array
          title: Suggested Followups
          description: IDs of related prompts to suggest next
      type: object
      required:
      - id
      - name
      - category
      - description
      - template
      title: PromptTemplate
      description: Template for common agent queries.
    PromptTestRequest:
      properties:
        prompt_id:
          type: string
          title: Prompt Id
        variables:
          anyOf:
          - additionalProperties:
              type: string
            type: object
          - type: 'null'
          title: Variables
        version:
          type: string
          title: Version
          default: latest
        channel:
          type: string
          title: Channel
          default: prod
      type: object
      required:
      - prompt_id
      title: PromptTestRequest
    ProposeGoalRequest:
      properties:
        new_goal_state:
          type: string
          title: New Goal State
        proposed_by:
          anyOf:
          - type: string
          - type: 'null'
          title: Proposed By
        evidence:
          anyOf:
          - type: string
          - type: 'null'
          title: Evidence
      type: object
      required:
      - new_goal_state
      title: ProposeGoalRequest
    ProvenanceEngagement:
      properties:
        lineage_ids:
          anyOf:
          - items:
              type: string
            type: array
          - type: 'null'
          title: Lineage Ids
          description: 'Active belief lineages: parental-voice, scientific-training,
            cultural-norms:US, etc.'
        invoked_concepts:
          anyOf:
          - items:
              type: string
            type: array
          - type: 'null'
          title: Invoked Concepts
          description: Conceptual frameworks actively engaged
      type: object
      title: ProvenanceEngagement
      description: 'Lineage of the belief system.


        Where did this generative model come from?'
    RankedEpisode:
      properties:
        id:
          type: integer
          title: Id
        content:
          type: string
          title: Content
          description: Truncated episode content
        relevance_score:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Relevance Score
          description: How relevant this episode is to the narrative
        user_id:
          anyOf:
          - type: string
          - type: 'null'
          title: User Id
        created_at:
          anyOf:
          - type: string
          - type: 'null'
          title: Created At
      type: object
      required:
      - id
      - content
      - relevance_score
      title: RankedEpisode
      description: An episode ranked by relevance to a narrative.
    RawContext:
      properties:
        self_model_id:
          type: integer
          title: Self Model Id
        self_model_definition:
          additionalProperties: true
          type: object
          title: Self Model Definition
          description: Complete self-model definition
        views:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Views
          description: All computed views
        beliefs:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Beliefs
          description: All fetched beliefs
        computed_at:
          type: string
          format: date-time
          title: Computed At
      type: object
      required:
      - self_model_id
      - computed_at
      title: RawContext
      description: 'Full projection data without transformation.


        Contains complete data for programmatic access and custom formatting.'
    RecentActivityVector:
      properties:
        modality_weights:
          additionalProperties:
            type: number
          type: object
          title: Modality Weights
        pillar_weights:
          additionalProperties:
            type: number
          type: object
          title: Pillar Weights
        episode_count:
          type: integer
          title: Episode Count
        belief_changes:
          type: integer
          title: Belief Changes
        time_window_days:
          type: integer
          title: Time Window Days
        data_completeness:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Data Completeness
      type: object
      required:
      - modality_weights
      - pillar_weights
      - episode_count
      - belief_changes
      - time_window_days
      - data_completeness
      title: RecentActivityVector
      description: User's actual cognitive footprint in STM window.
    Recommendation:
      properties:
        id:
          type: integer
          title: Id
        app_id:
          type: string
          title: App Id
        name:
          type: string
          title: Name
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
        ad_hook:
          anyOf:
          - type: string
          - type: 'null'
          title: Ad Hook
        ad_story:
          anyOf:
          - type: string
          - type: 'null'
          title: Ad Story
        ad_close:
          anyOf:
          - type: string
          - type: 'null'
          title: Ad Close
        traffic_source:
          anyOf:
          - type: string
          - type: 'null'
          title: Traffic Source
        creative_metadata:
          additionalProperties: true
          type: object
          title: Creative Metadata
        predicted_metric:
          type: string
          title: Predicted Metric
        predicted_value:
          type: number
          title: Predicted Value
        confidence:
          type: number
          title: Confidence
          default: 0.5
        target_stage:
          anyOf:
          - type: string
          - type: 'null'
          title: Target Stage
        target_audience:
          anyOf:
          - type: string
          - type: 'null'
          title: Target Audience
        actual_value:
          anyOf:
          - type: number
          - type: 'null'
          title: Actual Value
        accuracy_score:
          anyOf:
          - type: number
          - type: 'null'
          title: Accuracy Score
        status:
          type: string
          title: Status
          default: active
        created_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Created At
        resolved_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Resolved At
        created_by:
          anyOf:
          - type: string
          - type: 'null'
          title: Created By
        resolved_by:
          anyOf:
          - type: string
          - type: 'null'
          title: Resolved By
        resolution_notes:
          anyOf:
          - type: string
          - type: 'null'
          title: Resolution Notes
        metadata:
          additionalProperties: true
          type: object
          title: Metadata
        episode_count:
          anyOf:
          - type: integer
          - type: 'null'
          title: Episode Count
          default: 0
      type: object
      required:
      - id
      - app_id
      - name
      - predicted_metric
      - predicted_value
      title: Recommendation
      description: Full recommendation record.
    RecommendationCreate:
      properties:
        app_id:
          type: string
          title: App Id
        name:
          type: string
          title: Name
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
        ad_hook:
          anyOf:
          - type: string
          - type: 'null'
          title: Ad Hook
        ad_story:
          anyOf:
          - type: string
          - type: 'null'
          title: Ad Story
        ad_close:
          anyOf:
          - type: string
          - type: 'null'
          title: Ad Close
        traffic_source:
          anyOf:
          - type: string
          - type: 'null'
          title: Traffic Source
        creative_metadata:
          additionalProperties: true
          type: object
          title: Creative Metadata
        predicted_metric:
          type: string
          title: Predicted Metric
          description: Metric being predicted (e.g., conversion_rate)
        predicted_value:
          type: number
          title: Predicted Value
        confidence:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Confidence
          default: 0.5
        target_stage:
          anyOf:
          - type: string
          - type: 'null'
          title: Target Stage
        target_audience:
          anyOf:
          - type: string
          - type: 'null'
          title: Target Audience
        metadata:
          additionalProperties: true
          type: object
          title: Metadata
      type: object
      required:
      - app_id
      - name
      - predicted_metric
      - predicted_value
      title: RecommendationCreate
      description: Create a new recommendation (prediction).
    RecommendationOutcome:
      properties:
        recommendation:
          $ref: '#/components/schemas/Recommendation'
        linked_episodes:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Linked Episodes
        total_episodes:
          type: integer
          title: Total Episodes
      type: object
      required:
      - recommendation
      - linked_episodes
      - total_episodes
      title: RecommendationOutcome
      description: Recommendation with linked episode summaries.
    RecommendationResolve:
      properties:
        actual_value:
          type: number
          title: Actual Value
        resolution_notes:
          anyOf:
          - type: string
          - type: 'null'
          title: Resolution Notes
      type: object
      required:
      - actual_value
      title: RecommendationResolve
      description: Resolve a recommendation with actual outcome.
    RecommendationUpdate:
      properties:
        name:
          anyOf:
          - type: string
          - type: 'null'
          title: Name
        description:
          anyOf:
          - type: string
          - type: 'null'
          title: Description
        ad_hook:
          anyOf:
          - type: string
          - type: 'null'
          title: Ad Hook
        ad_story:
          anyOf:
          - type: string
          - type: 'null'
          title: Ad Story
        ad_close:
          anyOf:
          - type: string
          - type: 'null'
          title: Ad Close
        traffic_source:
          anyOf:
          - type: string
          - type: 'null'
          title: Traffic Source
        creative_metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Creative Metadata
        predicted_metric:
          anyOf:
          - type: string
          - type: 'null'
          title: Predicted Metric
        predicted_value:
          anyOf:
          - type: number
          - type: 'null'
          title: Predicted Value
        confidence:
          anyOf:
          - type: number
          - type: 'null'
          title: Confidence
        target_stage:
          anyOf:
          - type: string
          - type: 'null'
          title: Target Stage
        target_audience:
          anyOf:
          - type: string
          - type: 'null'
          title: Target Audience
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
      type: object
      title: RecommendationUpdate
      description: Update an existing recommendation.
    RecommendationsListResponse:
      properties:
        recommendations:
          items:
            $ref: '#/components/schemas/Recommendation'
          type: array
          title: Recommendations
        total:
          type: integer
          title: Total
      type: object
      required:
      - recommendations
      - total
      title: RecommendationsListResponse
      description: Paginated list of recommendations.
    RegisterEpisodeRequest:
      properties:
        episode_id:
          type: integer
          title: Episode Id
          description: Episode ID to register
      type: object
      required:
      - episode_id
      title: RegisterEpisodeRequest
      description: Request to register an episode with a session
    RejectGoalRequest:
      properties:
        rejected_by:
          anyOf:
          - type: string
          - type: 'null'
          title: Rejected By
      type: object
      title: RejectGoalRequest
    Relation:
      properties:
        fn:
          type: string
          title: Fn
          description: Functional relationship
      type: object
      required:
      - fn
      title: Relation
    ResolveResponse:
      properties:
        user_id:
          type: string
          title: User Id
        self_model_id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Self Model Id
        identities:
          items:
            $ref: '#/components/schemas/IdentityInfo'
          type: array
          title: Identities
          default: []
      type: object
      required:
      - user_id
      title: ResolveResponse
    SeedStatesRequest:
      properties:
        states:
          additionalProperties:
            type: string
          type: object
          title: States
          description: Mapping of context_id -> state_id to set as current_state
        episode_id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Episode Id
          description: Episode to record as source (optional)
      type: object
      required:
      - states
      title: SeedStatesRequest
      description: Request body for seeding initial current_state on observation contexts.
    SelfModelDefinition:
      properties:
        domains:
          items:
            $ref: '#/components/schemas/DomainDefinition'
          type: array
          minItems: 1
          title: Domains
        modes:
          items:
            $ref: '#/components/schemas/ModeDefinition'
          type: array
          title: Modes
        views:
          items:
            $ref: '#/components/schemas/ViewDefinition'
          type: array
          title: Views
      type: object
      required:
      - domains
      title: SelfModelDefinition
      description: 'Complete self-model definition with domains, modes, and views.


        This is stored in the ''definition'' JSONB column.'
    SelfModelResponse:
      properties:
        id:
          type: integer
          title: Id
        user_id:
          type: string
          title: User Id
        name:
          type: string
          title: Name
        self_model_type:
          $ref: '#/components/schemas/SelfModelType'
        app_id:
          anyOf:
          - type: string
          - type: 'null'
          title: App Id
        external_id:
          anyOf:
          - type: string
          - type: 'null'
          title: External Id
        definition:
          $ref: '#/components/schemas/SelfModelDefinition'
        version:
          type: integer
          title: Version
        created_at:
          type: string
          format: date-time
          title: Created At
        updated_at:
          type: string
          format: date-time
          title: Updated At
      type: object
      required:
      - id
      - user_id
      - name
      - self_model_type
      - definition
      - version
      - created_at
      - updated_at
      title: SelfModelResponse
      description: Full self-model response.
    SelfModelType:
      type: string
      enum:
      - primary
      - archetype
      - experimental
      - snapshot
      title: SelfModelType
      description: Type categorization for self-models.
    SelfNarrativeRequest:
      properties:
        user_id:
          type: string
          title: User Id
        modality_weights:
          additionalProperties:
            additionalProperties:
              type: number
            type: object
          type: object
          title: Modality Weights
        attention_policy:
          additionalProperties:
            additionalProperties:
              type: number
            type: object
          type: object
          title: Attention Policy
        initial_beliefs:
          anyOf:
          - items: {}
            type: array
          - type: 'null'
          title: Initial Beliefs
        residuals:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Residuals
        include_examples:
          type: boolean
          title: Include Examples
          default: false
      type: object
      required:
      - user_id
      - modality_weights
      - attention_policy
      title: SelfNarrativeRequest
      description: Request for self-narrative generation
    SelfNarrativeResponse:
      properties:
        current_self_narrative:
          type: string
          title: Current Self Narrative
        future_self_narrative:
          type: string
          title: Future Self Narrative
        transformation_path:
          type: string
          title: Transformation Path
        key_gaps:
          items:
            additionalProperties: true
            type: object
          type: array
          title: Key Gaps
        primary_focus_areas:
          items:
            type: string
          type: array
          title: Primary Focus Areas
        prompt_version:
          anyOf:
          - type: string
          - type: 'null'
          title: Prompt Version
        usage_metrics:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Usage Metrics
        generated_at:
          type: string
          title: Generated At
      type: object
      required:
      - current_self_narrative
      - future_self_narrative
      - transformation_path
      - key_gaps
      - primary_focus_areas
      - generated_at
      title: SelfNarrativeResponse
      description: Response with generated narratives
    SensoryEngagement:
      properties:
        interoception:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Interoception
          description: Internal body sensing
        proprioception:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Proprioception
          description: Body position awareness
        vision:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Vision
          description: Visual perception
        audition:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Audition
          description: Auditory perception
        social_audition:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Social Audition
          description: Social voice/conversation
        sampling_pattern:
          anyOf:
          - type: string
          - type: 'null'
          title: Sampling Pattern
          description: narrow-focused, panoramic, scanning, etc.
      type: object
      title: SensoryEngagement
      description: 'Sensory modalities and precision weights.


        Which ways can this self be perturbed by the world?'
    ShareRequest:
      properties:
        granted_to_user_id:
          type: string
          title: Granted To User Id
        role:
          type: string
          title: Role
          default: viewer
      type: object
      required:
      - granted_to_user_id
      title: ShareRequest
    ShareResponse:
      properties:
        id:
          type: integer
          title: Id
        self_model_id:
          type: integer
          title: Self Model Id
        granted_to:
          type: string
          title: Granted To
        role:
          type: string
          title: Role
        granted_by:
          type: string
          title: Granted By
      type: object
      required:
      - id
      - self_model_id
      - granted_to
      - role
      - granted_by
      title: ShareResponse
    SharedModelResponse:
      properties:
        self_model_id:
          type: integer
          title: Self Model Id
        name:
          anyOf:
          - type: string
          - type: 'null'
          title: Name
        role:
          type: string
          title: Role
        owner_user_id:
          type: string
          title: Owner User Id
      type: object
      required:
      - self_model_id
      - name
      - role
      - owner_user_id
      title: SharedModelResponse
    SolutionsConsidered:
      properties:
        summary:
          type: string
          title: Summary
        options:
          items:
            type: string
          type: array
          title: Options
        current_solution:
          anyOf:
          - type: string
          - type: 'null'
          title: Current Solution
      type: object
      required:
      - summary
      title: SolutionsConsidered
      description: Solutions the user is considering.
    StageAlignmentScore:
      properties:
        stage_id:
          type: string
          title: Stage Id
        stage_name:
          type: string
          title: Stage Name
        stage_order:
          type: integer
          title: Stage Order
        overall_score:
          type: number
          title: Overall Score
        context_scores:
          additionalProperties: true
          type: object
          title: Context Scores
        contexts_evaluated:
          type: integer
          title: Contexts Evaluated
        user_count:
          type: integer
          title: User Count
          default: 0
        method:
          type: string
          title: Method
          default: synthetic_context_delta
      type: object
      required:
      - stage_id
      - stage_name
      - stage_order
      - overall_score
      - contexts_evaluated
      title: StageAlignmentScore
      description: Alignment score for a single journey stage.
    StageMetrics:
      properties:
        name:
          type: string
          title: Name
        display_name:
          anyOf:
          - type: string
          - type: 'null'
          title: Display Name
        user_count:
          type: integer
          title: User Count
        episode_count:
          type: integer
          title: Episode Count
      type: object
      required:
      - name
      - user_count
      - episode_count
      title: StageMetrics
      description: Metrics for a single stage.
    StageTransition:
      properties:
        from_stage:
          type: string
          title: From Stage
        to_stage:
          type: string
          title: To Stage
        timestamp:
          type: string
          format: date-time
          title: Timestamp
        duration_hours:
          anyOf:
          - type: number
          - type: 'null'
          title: Duration Hours
      type: object
      required:
      - from_stage
      - to_stage
      - timestamp
      title: StageTransition
      description: Transition between JTBD stages.
    StakeholderScore:
      properties:
        self_model_id:
          type: integer
          title: Self Model Id
        label:
          type: string
          title: Label
        overall_score:
          type: number
          title: Overall Score
        context_scores:
          additionalProperties: true
          type: object
          title: Context Scores
        contexts_evaluated:
          type: integer
          title: Contexts Evaluated
        method:
          type: string
          title: Method
        error:
          anyOf:
          - type: string
          - type: 'null'
          title: Error
      type: object
      required:
      - self_model_id
      - label
      - overall_score
      - context_scores
      - contexts_evaluated
      - method
      title: StakeholderScore
      description: Alignment score for a single stakeholder.
    StakeholderTarget:
      properties:
        self_model_id:
          type: integer
          title: Self Model Id
        label:
          type: string
          title: Label
          default: ''
        role:
          type: string
          title: Role
          default: ''
      type: object
      required:
      - self_model_id
      title: StakeholderTarget
      description: A stakeholder target for batch alignment scoring.
    StatisticalEvidence:
      properties:
        p_value:
          type: number
          title: P Value
          description: P-value from z-test for two proportions
        is_significant:
          type: boolean
          title: Is Significant
          description: True if p < 0.05
        significance_label:
          type: string
          title: Significance Label
          description: e.g., 'Statistically significant'
        confidence_interval_low:
          type: number
          title: Confidence Interval Low
          description: Lower bound of 95% CI for gap
        confidence_interval_high:
          type: number
          title: Confidence Interval High
          description: Upper bound of 95% CI for gap
        confidence_level:
          type: number
          title: Confidence Level
          description: Confidence level (default 95%)
          default: 0.95
        sample_size_top:
          type: integer
          title: Sample Size Top
          description: Users in top segment
        sample_size_bottom:
          type: integer
          title: Sample Size Bottom
          description: Users in bottom segment
        sample_size_total:
          type: integer
          title: Sample Size Total
          description: Total users
        ltv_correlation:
          anyOf:
          - type: number
          - type: 'null'
          title: Ltv Correlation
          description: Pearson r correlation with LTV
        ltv_correlation_label:
          anyOf:
          - type: string
          - type: 'null'
          title: Ltv Correlation Label
          description: '''Strong'', ''Moderate'', ''Weak'', or ''None'''
        data_quality_score:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Data Quality Score
          description: Overall data quality (0-1)
        data_quality_label:
          type: string
          title: Data Quality Label
          description: '''High confidence'', ''Medium'', ''Low'''
      type: object
      required:
      - p_value
      - is_significant
      - significance_label
      - confidence_interval_low
      - confidence_interval_high
      - sample_size_top
      - sample_size_bottom
      - sample_size_total
      - data_quality_score
      - data_quality_label
      title: StatisticalEvidence
      description: Statistical analysis of cohort gap significance.
    SummaryContext:
      properties:
        self_model_name:
          type: string
          title: Self Model Name
        user_id:
          type: string
          title: User Id
        dominant_mode:
          anyOf:
          - type: string
          - type: 'null'
          title: Dominant Mode
        belief_count:
          type: integer
          title: Belief Count
          default: 0
        domain_count:
          type: integer
          title: Domain Count
          default: 0
        top_domains:
          items:
            type: string
          type: array
          title: Top Domains
          description: Top domains by episode count
        key_insight:
          type: string
          title: Key Insight
          description: Single key insight about the user
          default: Self-model is being initialized.
        computed_at:
          type: string
          format: date-time
          title: Computed At
      type: object
      required:
      - self_model_name
      - user_id
      - computed_at
      title: SummaryContext
      description: 'Condensed context overview.


        Minimal context for quick status checks and notifications.'
    TelosVector:
      properties:
        modality_delta:
          additionalProperties:
            type: number
          type: object
          title: Modality Delta
        pillar_delta:
          additionalProperties:
            type: number
          type: object
          title: Pillar Delta
        context_delta:
          additionalProperties:
            type: number
          type: object
          title: Context Delta
        magnitude:
          type: number
          minimum: 0.0
          title: Magnitude
        primary_shifts:
          items:
            type: string
          type: array
          title: Primary Shifts
      type: object
      required:
      - modality_delta
      - pillar_delta
      - magnitude
      - primary_shifts
      title: TelosVector
      description: The desired change from current to target self.
    TestDesign:
      properties:
        design:
          type: string
          title: Design
        duration:
          anyOf:
          - type: string
          - type: 'null'
          title: Duration
        adherence:
          anyOf:
          - type: string
          - type: 'null'
          title: Adherence
      type: object
      required:
      - design
      title: TestDesign
    TimeDistribution:
      properties:
        median_days:
          type: number
          title: Median Days
        p25_days:
          type: number
          title: P25 Days
        p75_days:
          type: number
          title: P75 Days
        optimal_window:
          anyOf:
          - type: string
          - type: 'null'
          title: Optimal Window
          description: e.g., '< 5 days'
      type: object
      required:
      - median_days
      - p25_days
      - p75_days
      title: TimeDistribution
      description: Time-to-complete distribution for a transition.
    TransitionConversation:
      properties:
        id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Id
        app_id:
          type: string
          title: App Id
        from_stage:
          type: string
          title: From Stage
        to_stage:
          type: string
          title: To Stage
        title:
          anyOf:
          - type: string
          - type: 'null'
          title: Title
          description: Auto-generated or user-set title
        summary:
          anyOf:
          - type: string
          - type: 'null'
          title: Summary
          description: AI-generated summary of conversation
        message_count:
          type: integer
          title: Message Count
          default: 0
        created_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Created At
        updated_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Updated At
      type: object
      required:
      - app_id
      - from_stage
      - to_stage
      title: TransitionConversation
      description: 'Conversation context for a specific journey transition.


        Scoped by app_id + from_stage + to_stage to maintain context

        when analyzing gaps between journey stages.'
    TransitionConversationWithMessages:
      properties:
        id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Id
        app_id:
          type: string
          title: App Id
        from_stage:
          type: string
          title: From Stage
        to_stage:
          type: string
          title: To Stage
        title:
          anyOf:
          - type: string
          - type: 'null'
          title: Title
          description: Auto-generated or user-set title
        summary:
          anyOf:
          - type: string
          - type: 'null'
          title: Summary
          description: AI-generated summary of conversation
        message_count:
          type: integer
          title: Message Count
          default: 0
        created_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Created At
        updated_at:
          anyOf:
          - type: string
            format: date-time
          - type: 'null'
          title: Updated At
        messages:
          items:
            $ref: '#/components/schemas/ConversationMessage'
          type: array
          title: Messages
      type: object
      required:
      - app_id
      - from_stage
      - to_stage
      title: TransitionConversationWithMessages
      description: Conversation with full message history.
    TransitionDetailResponse:
      properties:
        app_id:
          type: string
          title: App Id
        from_stage:
          type: string
          title: From Stage
        to_stage:
          type: string
          title: To Stage
        metrics:
          $ref: '#/components/schemas/TransitionMetrics'
        time_distribution:
          anyOf:
          - $ref: '#/components/schemas/TimeDistribution'
          - type: 'null'
        trend_30d:
          items:
            $ref: '#/components/schemas/TrendDataPoint'
          type: array
          title: Trend 30D
        users:
          anyOf:
          - $ref: '#/components/schemas/TransitionUsers'
          - type: 'null'
        statistical_evidence:
          anyOf:
          - $ref: '#/components/schemas/StatisticalEvidence'
          - type: 'null'
        ltv_correlation:
          anyOf:
          - type: number
          - type: 'null'
          title: Ltv Correlation
          description: Correlation with LTV
        data_quality:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Data Quality
          description: Data quality score
        computed_at:
          type: string
          format: date-time
          title: Computed At
      type: object
      required:
      - app_id
      - from_stage
      - to_stage
      - metrics
      - computed_at
      title: TransitionDetailResponse
      description: Detailed metrics for a specific transition.
    TransitionInsight:
      properties:
        id:
          anyOf:
          - type: string
          - type: 'null'
          title: Id
          description: Unique insight identifier
        app_id:
          type: string
          title: App Id
        from_stage:
          type: string
          title: From Stage
        to_stage:
          type: string
          title: To Stage
        archetype_id:
          anyOf:
          - $ref: '#/components/schemas/ArchetypeId'
          - type: 'null'
          description: Primary archetype this insight relates to
        archetype_name:
          anyOf:
          - type: string
          - type: 'null'
          title: Archetype Name
          description: Display name of the archetype
        title:
          type: string
          title: Title
          description: Short, compelling insight title
        description:
          type: string
          title: Description
          description: Detailed explanation of the insight
        causal_mechanism:
          $ref: '#/components/schemas/CausalMechanism'
        forces_summary:
          anyOf:
          - $ref: '#/components/schemas/ForcesSummary'
          - type: 'null'
          description: Inferred JTBD forces from engagement patterns
        engagement_hypothesis:
          anyOf:
          - $ref: '#/components/schemas/EngagementHypothesis'
          - type: 'null'
          description: Agent-inferred mode transition hypothesis
        cohort_comparison:
          anyOf:
          - $ref: '#/components/schemas/NarrativeCohortComparison'
          - type: 'null'
          description: Top 20% vs bottom 80% comparison
        ranked_episodes:
          items:
            $ref: '#/components/schemas/RankedEpisode'
          type: array
          title: Ranked Episodes
          description: Episodes ranked by relevance to narrative
        archetype_breakdown:
          items:
            $ref: '#/components/schemas/ArchetypeInsight'
          type: array
          title: Archetype Breakdown
          description: Per-archetype conversion metrics
        evidence:
          $ref: '#/components/schemas/InsightEvidence'
        opportunity:
          $ref: '#/components/schemas/InsightOpportunity'
        generated_at:
          type: string
          format: date-time
          title: Generated At
        data_quality_score:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Data Quality Score
      type: object
      required:
      - app_id
      - from_stage
      - to_stage
      - title
      - description
      - causal_mechanism
      - evidence
      - opportunity
      - generated_at
      - data_quality_score
      title: TransitionInsight
      description: AI-generated insight about a transition gap.
    TransitionInsightResponse:
      properties:
        app_id:
          type: string
          title: App Id
        from_stage:
          type: string
          title: From Stage
        to_stage:
          type: string
          title: To Stage
        insights:
          items:
            $ref: '#/components/schemas/TransitionInsight'
          type: array
          title: Insights
        primary_insight:
          anyOf:
          - $ref: '#/components/schemas/TransitionInsight'
          - type: 'null'
          description: The most actionable insight
        generated_at:
          type: string
          format: date-time
          title: Generated At
      type: object
      required:
      - app_id
      - from_stage
      - to_stage
      - generated_at
      title: TransitionInsightResponse
      description: Response containing insights for a transition.
    TransitionMetrics:
      properties:
        from_stage:
          type: string
          title: From Stage
        to_stage:
          type: string
          title: To Stage
        conversion_rate:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Conversion Rate
        top_20_rate:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Top 20 Rate
        bottom_80_rate:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Bottom 80 Rate
        gap_pp:
          anyOf:
          - type: integer
          - type: 'null'
          title: Gap Pp
          description: Gap in percentage points
        user_count:
          type: integer
          title: User Count
        avg_time_days:
          anyOf:
          - type: number
          - type: 'null'
          title: Avg Time Days
      type: object
      required:
      - from_stage
      - to_stage
      - conversion_rate
      - user_count
      title: TransitionMetrics
      description: Metrics for a stage transition.
    TransitionUsers:
      properties:
        converted:
          items:
            type: string
          type: array
          title: Converted
          description: User IDs who completed transition
        pending:
          items:
            type: string
          type: array
          title: Pending
          description: User IDs in from_stage, not yet converted
        dropped:
          items:
            type: string
          type: array
          title: Dropped
          description: User IDs who left without converting
      type: object
      title: TransitionUsers
      description: Users in different states of a transition.
    TrendDataPoint:
      properties:
        date:
          type: string
          title: Date
        rate:
          type: number
          title: Rate
      type: object
      required:
      - date
      - rate
      title: TrendDataPoint
      description: Single data point in a trend series.
    UpdateSelfModelRequest:
      properties:
        name:
          anyOf:
          - type: string
            maxLength: 255
            minLength: 1
          - type: 'null'
          title: Name
        description:
          anyOf:
          - type: string
            maxLength: 1000
          - type: 'null'
          title: Description
        domains:
          anyOf:
          - items:
              $ref: '#/components/schemas/DomainDefinition'
            type: array
          - type: 'null'
          title: Domains
        modes:
          anyOf:
          - items:
              $ref: '#/components/schemas/ModeDefinition'
            type: array
          - type: 'null'
          title: Modes
        views:
          anyOf:
          - items:
              $ref: '#/components/schemas/ViewDefinition'
            type: array
          - type: 'null'
          title: Views
      type: object
      title: UpdateSelfModelRequest
      description: Request to update a self-model.
    UpdateSelfModelResponse:
      properties:
        self_model_id:
          type: integer
          title: Self Model Id
        version:
          type: integer
          title: Version
        updated_at:
          type: string
          format: date-time
          title: Updated At
      type: object
      required:
      - self_model_id
      - version
      - updated_at
      title: UpdateSelfModelResponse
      description: Response after updating a self-model.
    UserAlignmentProfile:
      properties:
        user_id:
          type: string
          title: User Id
        current_alignment:
          $ref: '#/components/schemas/AlignmentMetrics'
        historical_trend:
          additionalProperties:
            type: number
          type: object
          title: Historical Trend
        current_self_snapshot:
          additionalProperties: true
          type: object
          title: Current Self Snapshot
        target_self_snapshot:
          additionalProperties: true
          type: object
          title: Target Self Snapshot
        strengths:
          items:
            type: string
          type: array
          title: Strengths
        gaps:
          items:
            type: string
          type: array
          title: Gaps
        recent_progress:
          items:
            type: string
          type: array
          title: Recent Progress
        last_calculated:
          type: string
          format: date-time
          title: Last Calculated
        data_sources:
          additionalProperties:
            type: integer
          type: object
          title: Data Sources
      type: object
      required:
      - user_id
      - current_alignment
      - historical_trend
      - current_self_snapshot
      - target_self_snapshot
      - strengths
      - gaps
      - recent_progress
      - last_calculated
      - data_sources
      title: UserAlignmentProfile
      description: Complete alignment profile for a user.
    UserArchetype:
      properties:
        user_id:
          type: string
          title: User Id
        app_id:
          type: string
          title: App Id
        archetype_id:
          $ref: '#/components/schemas/ArchetypeId'
        archetype_name:
          type: string
          title: Archetype Name
        confidence:
          type: number
          maximum: 1.0
          minimum: 0.0
          title: Confidence
          description: Classification confidence
        matching_criteria:
          items:
            type: string
          type: array
          title: Matching Criteria
          description: Which criteria matched
        computed_at:
          type: string
          format: date-time
          title: Computed At
      type: object
      required:
      - user_id
      - app_id
      - archetype_id
      - archetype_name
      - confidence
      - computed_at
      title: UserArchetype
      description: Archetype classification for a user.
    UserJTBDPhases:
      properties:
        user_id:
          type: string
          title: User Id
        app_id:
          type: string
          title: App Id
        current_phase:
          anyOf:
          - $ref: '#/components/schemas/JTBDPhase'
          - type: 'null'
        phases:
          items:
            $ref: '#/components/schemas/JTBDPhaseSummary'
          type: array
          title: Phases
        computed_at:
          type: string
          format: date-time
          title: Computed At
      type: object
      required:
      - user_id
      - app_id
      - phases
      - computed_at
      title: UserJTBDPhases
      description: All JTBD phases for a user.
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
            - type: string
            - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
        input:
          title: Input
        ctx:
          type: object
          title: Context
      type: object
      required:
      - loc
      - msg
      - type
      title: ValidationError
    Variable:
      properties:
        name:
          type: string
          title: Name
        unit:
          anyOf:
          - type: string
          - type: 'null'
          title: Unit
      type: object
      required:
      - name
      title: Variable
    ViewDefinition:
      properties:
        id:
          type: string
          title: Id
          description: Unique view identifier
        role:
          $ref: '#/components/schemas/ViewRole'
          description: 'Temporal role: being, becoming, telos, archetype'
        label:
          type: string
          title: Label
          description: Human-readable label
        horizon_days:
          anyOf:
          - type: integer
            minimum: 0.0
          - type: 'null'
          title: Horizon Days
          description: Future horizon in days (for becoming)
        attention:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Attention
          description: Attention weights for this view (domain_weights, mode_weights)
      type: object
      required:
      - id
      - role
      - label
      title: ViewDefinition
      description: 'A view within a self-model (temporal perspective).


        Views are different temporal perspectives on the self.'
    ViewRole:
      type: string
      enum:
      - being
      - becoming
      - telos
      - archetype
      title: ViewRole
      description: Role of a self-model view (temporal perspective).
    WhaleIndexEntry:
      properties:
        value:
          anyOf:
          - type: string
          - type: 'null'
          title: Value
        whale_index:
          anyOf:
          - type: number
          - type: 'null'
          title: Whale Index
        top_count:
          type: integer
          title: Top Count
        top_pct:
          type: number
          title: Top Pct
        bottom_count:
          type: integer
          title: Bottom Count
        bottom_pct:
          type: number
          title: Bottom Pct
      type: object
      required:
      - value
      - top_count
      - top_pct
      - bottom_count
      - bottom_pct
      title: WhaleIndexEntry
      description: Single value in the whale index ranking.
    WorkingMemoryContext:
      properties:
        header:
          type: string
          title: Header
          default: ''
        plan:
          type: string
          title: Plan
          default: ''
        bridge:
          items:
            $ref: '#/components/schemas/Hypothesis'
          type: array
          title: Bridge
        objective_pack:
          items:
            $ref: '#/components/schemas/Concept'
          type: array
          title: Objective Pack
        subjective_pack:
          items:
            $ref: '#/components/schemas/Episode'
          type: array
          title: Subjective Pack
        mini_history:
          items:
            type: string
          type: array
          title: Mini History
        pins:
          items:
            type: string
          type: array
          title: Pins
        total_tokens:
          type: integer
          title: Total Tokens
          default: 0
        budget_tokens:
          type: integer
          title: Budget Tokens
          default: 3000
      type: object
      title: WorkingMemoryContext
      description: Assembled working memory context under token budget
    src__api__routes__external__CreateSessionRequest:
      properties:
        user_id:
          type: string
          title: User Id
          description: User ID (from onboarding)
        session_type:
          type: string
          enum:
          - onboarding
          - reflection
          - journal
          - chat
          - retake
          title: Session Type
          description: Session type
        expected_episode_count:
          type: integer
          exclusiveMinimum: 0.0
          title: Expected Episode Count
          description: Number of episodes expected
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
          description: Session metadata
          default: {}
        causation_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Causation Id
          description: What triggered this session
        correlation_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Correlation Id
          description: Group related sessions
      type: object
      required:
      - user_id
      - session_type
      - expected_episode_count
      title: CreateSessionRequest
      description: Request to create a session
    src__api__routes__external__InputEnvelope:
      properties:
        envelope_id:
          type: string
          title: Envelope Id
          description: Unique envelope identifier (UUID)
        user_id:
          type: string
          title: User Id
          description: User identifier
        input_type:
          type: string
          title: Input Type
          description: 'Type of input: likert|reflection|narrative|slider|ranking|experiential|backcasting'
        schema_version:
          type: string
          title: Schema Version
          description: Schema version
          default: '1.0'
        timestamp:
          type: string
          title: Timestamp
          description: ISO 8601 timestamp
        data:
          additionalProperties: true
          type: object
          title: Data
          description: Type-specific input data
        session_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Session Id
          description: Optional session ID for session coordination
        customer_journey_stage:
          anyOf:
          - type: string
          - type: 'null'
          title: Customer Journey Stage
          description: 'Customer journey stage (JTBD Timeline): first_thought|passive_looking|active_looking|deciding|consuming|satisfaction'
      type: object
      required:
      - envelope_id
      - user_id
      - input_type
      - timestamp
      - data
      title: InputEnvelope
      description: Input envelope for processing
    src__api__routes__external__SessionResponse:
      properties:
        session_id:
          type: string
          title: Session Id
        user_id:
          type: string
          title: User Id
        session_type:
          type: string
          title: Session Type
        expected_episode_count:
          type: integer
          title: Expected Episode Count
        processed_episode_count:
          type: integer
          title: Processed Episode Count
        status:
          type: string
          title: Status
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
        self_model_snapshot:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Self Model Snapshot
        self_model_delta:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Self Model Delta
      type: object
      required:
      - session_id
      - user_id
      - session_type
      - expected_episode_count
      - processed_episode_count
      - status
      title: SessionResponse
      description: Session details response
    src__api__routes__inputs__InputEnvelope:
      properties:
        envelope_id:
          type: string
          title: Envelope Id
          description: Unique envelope identifier (UUID)
        user_id:
          type: string
          title: User Id
          description: User identifier
        input_type:
          type: string
          title: Input Type
          description: 'Type of input: likert|reflection|narrative|slider|ranking|experiential|backcasting'
        schema_version:
          type: string
          title: Schema Version
          description: Schema version (e.g., '1.0')
        timestamp:
          type: string
          title: Timestamp
          description: ISO 8601 timestamp
        data:
          additionalProperties: true
          type: object
          title: Data
          description: Type-specific input data
        session_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Session Id
          description: Optional session ID for session coordination
      type: object
      required:
      - envelope_id
      - user_id
      - input_type
      - schema_version
      - timestamp
      - data
      title: InputEnvelope
      description: Input envelope from Clarity
    src__api__routes__sessions__CreateSessionRequest:
      properties:
        user_id:
          type: string
          title: User Id
          description: User ID
        session_type:
          type: string
          title: Session Type
          description: 'Session type: onboarding, reflection, journal, chat, retake'
        expected_episode_count:
          type: integer
          exclusiveMinimum: 0.0
          title: Expected Episode Count
          description: Number of episodes expected in this session
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
          description: Session-specific metadata
          default: {}
        causation_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Causation Id
          description: What triggered this session
        correlation_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Correlation Id
          description: Group related sessions
      type: object
      required:
      - user_id
      - session_type
      - expected_episode_count
      title: CreateSessionRequest
      description: Request to create a new self-model update session
    src__api__routes__sessions__SessionResponse:
      properties:
        session_id:
          type: string
          title: Session Id
        user_id:
          type: string
          title: User Id
        session_type:
          type: string
          title: Session Type
        expected_episode_count:
          type: integer
          title: Expected Episode Count
        processed_episode_count:
          type: integer
          title: Processed Episode Count
        status:
          type: string
          title: Status
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
        self_model_snapshot:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Self Model Snapshot
        self_model_delta:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Self Model Delta
      type: object
      required:
      - session_id
      - user_id
      - session_type
      - expected_episode_count
      - processed_episode_count
      - status
      title: SessionResponse
      description: Session data response
    src__api__routes__v1_episodes__CreateEpisodeRequest:
      properties:
        user_id:
          type: string
          maxLength: 100
          title: User Id
          description: Clarity internal user ID
        context:
          type: string
          maxLength: 500
          title: Context
          description: Episode context (e.g., 'email_engagement', 'page_view')
        action:
          type: string
          maxLength: 500
          title: Action
          description: Action taken (e.g., 'clicked', 'opened', 'subscribed')
        domain:
          type: string
          maxLength: 100
          title: Domain
          description: Domain (e.g., 'email', 'web', 'calendar')
          default: external
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
        timestamp:
          anyOf:
          - type: string
          - type: 'null'
          title: Timestamp
          description: ISO 8601 timestamp, defaults to now
        app_id:
          anyOf:
          - type: string
            maxLength: 100
          - type: 'null'
          title: App Id
          description: Application ID for multi-client scoping
      type: object
      required:
      - user_id
      - context
      - action
      title: CreateEpisodeRequest
    src__api__routes__v1_episodes__CreateEpisodeResponse:
      properties:
        episode_id:
          anyOf:
          - type: integer
          - type: 'null'
          title: Episode Id
        deduplicated:
          type: boolean
          title: Deduplicated
          default: false
      type: object
      title: CreateEpisodeResponse
    src__models__analytics__JourneyEpisode:
      properties:
        id:
          type: integer
          title: Id
        created_at:
          type: string
          format: date-time
          title: Created At
        customer_journey_stage:
          anyOf:
          - type: string
          - type: 'null'
          title: Customer Journey Stage
        event_type:
          anyOf:
          - type: string
          - type: 'null'
          title: Event Type
        metadata:
          additionalProperties:
            anyOf:
            - type: string
            - type: 'null'
          type: object
          title: Metadata
        raw_input:
          anyOf:
          - type: string
          - type: 'null'
          title: Raw Input
        response:
          anyOf:
          - type: string
          - type: 'null'
          title: Response
      type: object
      required:
      - id
      - created_at
      title: JourneyEpisode
      description: Episode in a user's journey timeline.
    src__models__journey__ForceType__1:
      type: string
      enum:
      - push
      - pull
      - habit
      - anxiety
      title: ForceType
      description: Types of forces in JTBD framework.
    src__models__journey__ForceType__2:
      type: string
      enum:
      - push
      - pull
      - habit
      - anxiety
      title: ForceType
      description: JTBD forces that block or enable transitions.
    src__models__journey__JourneyEpisode:
      properties:
        id:
          type: integer
          title: Id
        user_id:
          type: string
          title: User Id
        app_id:
          type: string
          title: App Id
        customer_journey_stage:
          anyOf:
          - type: string
          - type: 'null'
          title: Customer Journey Stage
        raw_input:
          anyOf:
          - type: string
          - type: 'null'
          title: Raw Input
        response:
          anyOf:
          - type: string
          - type: 'null'
          title: Response
        created_at:
          type: string
          format: date-time
          title: Created At
        archetype_id:
          anyOf:
          - $ref: '#/components/schemas/ArchetypeId'
          - type: 'null'
        sentiment_score:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: -1.0
          - type: 'null'
          title: Sentiment Score
        key_themes:
          items:
            type: string
          type: array
          title: Key Themes
      type: object
      required:
      - id
      - user_id
      - app_id
      - created_at
      title: JourneyEpisode
      description: Episode data for journey dashboard viewing.
    src__models__self_model__CreateEpisodeRequest:
      properties:
        domain_id:
          type: string
          title: Domain Id
          description: Primary domain for this episode
        engagement:
          anyOf:
          - $ref: '#/components/schemas/EngagementState'
          - type: 'null'
          description: 6-quality engagement substrate
        notes:
          anyOf:
          - type: string
          - type: 'null'
          title: Notes
          description: Free-form episode notes
        content:
          anyOf:
          - type: string
          - type: 'null'
          title: Content
          description: Episode content (alternative to notes)
        customer_journey_stage:
          anyOf:
          - type: string
          - type: 'null'
          title: Customer Journey Stage
          description: Journey stage (e.g., active_looking)
        observation_context_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Observation Context Id
          description: Observation context identifier
        metadata:
          anyOf:
          - additionalProperties: true
            type: object
          - type: 'null'
          title: Metadata
          description: Additional metadata
      type: object
      required:
      - domain_id
      title: CreateEpisodeRequest
      description: Request to create an episode with engagement state.
    src__models__self_model__CreateEpisodeResponse:
      properties:
        episode_id:
          type: integer
          title: Episode Id
        domain_id:
          type: string
          title: Domain Id
        inferred_mode_id:
          anyOf:
          - type: string
          - type: 'null'
          title: Inferred Mode Id
          description: Mode inferred from engagement
        mode_confidence:
          anyOf:
          - type: number
            maximum: 1.0
            minimum: 0.0
          - type: 'null'
          title: Mode Confidence
          description: Confidence in mode inference
        created_at:
          type: string
          format: date-time
          title: Created At
      type: object
      required:
      - episode_id
      - domain_id
      - created_at
      title: CreateEpisodeResponse
      description: Response after creating an episode with mode inference.
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
servers:
- url: https://clarity-self-learning-agent.onrender.com
  description: Production server (Render)
- url: http://localhost:8000
  description: Development server
security:
- ApiKeyAuth: []
tags:
- name: health
  description: Health checks and readiness probes
- name: onboarding
  description: User registration and lookup
- name: sessions
  description: Session lifecycle management
- name: input
  description: Submit inputs for belief extraction
- name: self-models
  description: Self-model CRUD operations
- name: episodes
  description: Episode management with engagement state
- name: beliefs
  description: Belief extraction and evidence chains
- name: context
  description: Context assembly for AI/LLM consumption
- name: views
  description: 'Temporal views: being, becoming, telos'
- name: analytics
  description: Funnel, archetype, and evidence analytics
- name: external
  description: External-facing API surface
- name: admin
  description: Administrative and backfill operations
- name: monitoring
  description: Performance monitoring and metrics
- name: memory
  description: Memory management and consolidation
- name: embeddings
  description: Embedding generation and vector search
- name: recommendations
  description: Content and action recommendations
