Spaces:
Paused

miracle / docs /BACKEND_DIAGRAMS.md
dushyantsingh0
backend stabilization
ea4e72d
|
Raw History Blame Contribute Delete
47.2 kB

Nexus Backend — Complete Architecture & Flow Diagrams

All diagrams use Mermaid. Render in GitHub, VS Code (Markdown Preview Mermaid Support), or mermaid.live.


Table of Contents

  1. Overall System Architecture
  2. Component Architecture
  3. API Route Map
  4. Database Entity Relationship
  5. Auth & Session Flow
  6. WebSocket & SSE Real-time Architecture
  7. Ticket Lifecycle
  8. Ticket Creation & AI Triage Flow
  9. Ticket SLA & Escalation Flow
  10. Knowledge Base Article Workflow
  11. Hybrid Search System
  12. Worker & Background Job System
  13. Nexus Master Agent Architecture
  14. Nexus SSE Streaming Flow
  15. Redis Keys & Channels Map
  16. Notification Flow
  17. File Attachment Flow
  18. KB Insights Workflow

1. Overall System Architecture

High-level view of every process, storage layer, and external dependency.

graph TB
    subgraph Clients
        CU[Customer Browser]
        SU[Staff Browser]
    end

    subgraph "FastAPI Process (Gunicorn x4 workers)"
        API[REST API\napi/v1/*]
        WS[WebSocket Manager\ncore/websockets.py]
        SSE[SSE Streaming\nnexus_stream.py]
        AUTH[Auth / JWT\ncore/security.py]
        RATE[Rate Limiter\ncore/rate_limiter.py]
    end

    subgraph "ARQ Worker Pool"
        W1[Worker 1]
        W2[Worker 2]
        W3[Worker 3]
        CRON[Cron Scheduler]
    end

    subgraph "Agent Layer"
        NMG[Nexus Master Agent\nLangGraph Graph]
        NCA[Nexus Customer Agent]
        TOOLS[Tool Registry\nagents/tools/]
    end

    subgraph "Storage"
        PG[(PostgreSQL\n+ pgvector\n+ TSVector)]
        RLA[(Redis Local\nlocalhost:6379\npub/sub + cache)]
        RLA2[(Redis ARQ\nUpstash Cloud\njob queue)]
        FS[File Storage\nlocal / S3]
    end

    subgraph "External"
        ANT[Anthropic API\nClaude Sonnet/Opus/Haiku]
        OLL[Ollama\nself-hosted fallback]
        SMTP[SMTP / Email]
        OTEL[OpenTelemetry\ntracing]
    end

    CU -- HTTPS/WSS --> API
    SU -- HTTPS/WSS --> API

    API --> AUTH
    API --> RATE
    API --> WS
    API --> SSE
    API --> PG
    API --> RLA

    SSE -- enqueue job --> RLA2
    SSE -- XREAD stream --> RLA

    W1 & W2 & W3 -- dequeue --> RLA2
    W1 & W2 & W3 --> NMG
    W1 & W2 & W3 --> PG
    W1 & W2 & W3 --> RLA
    CRON --> RLA2

    NMG --> TOOLS
    NMG --> NCA
    TOOLS --> PG
    TOOLS --> RLA

    W1 & W2 & W3 -- XADD stream --> RLA
    WS -- pub/sub --> RLA

    W1 & W2 & W3 --> ANT
    NMG --> ANT
    ANT -. fallback .-> OLL

    W1 & W2 & W3 --> SMTP
    W1 & W2 & W3 --> FS
    API --> FS

    API --> OTEL
    W1 & W2 & W3 --> OTEL

2. Component Architecture

Internal component breakdown within each major layer.

graph LR
    subgraph "API Layer (api/v1/)"
        A1[auth.py\nregister / login / refresh\npassword reset]
        A2[tickets.py\nCRUD + search + paginate]
        A3[messages.py\nthread messaging]
        A4[websockets.py\nWS endpoints]
        A5[kb.py\narticle CRUD + search]
        A6[kb_insights.py\ninsight approve]
        A7[nexus.py\nagent HTTP query]
        A8[nexus_stream.py\nSSE streaming]
        A9[escalations.py\nSLA rules + audit]
        A10[reports.py\nanalytics]
        A11[notifications.py]
        A12[attachments.py\nupload / download]
        A13[feedback.py\nCSAT]
        A14[dashboard.py\nhydration]
        A15[projects.py]
        A16[workspace.py]
        A17[system.py\nhealth]
        A18[worker.py\njob monitoring]
        A19[ai.py\ntrace]
    end

    subgraph "Core Infrastructure (core/)"
        C1[database.py\nSQLAlchemy + pool]
        C2[security.py\nJWT + bcrypt]
        C3[permissions.py\nRBAC + BOLA]
        C4[cache.py\nL1 LRU + L2 Redis]
        C5[websockets.py\nConnectionManager]
        C6[rate_limiter.py\nwindow-based]
        C7[llm.py\nLLM factory]
        C8[search.py\nchunking utilities]
        C9[storage.py\nfile abstraction]
        C10[vision.py\nimage captions]
        C11[audit.py\naction logging]
        C12[token_blocklist.py\nJWT revocation]
        C13[email.py]
        C14[observability.py\nOpenTelemetry]
        C15[sync.py\nimage sync]
    end

    subgraph "Agent Layer (agents/)"
        AG1[nexus_master.py\nLangGraph graph]
        AG2[nexus_customer.py\ncustomer graph]
        AG3[state.py\nAgentState schema]
        AG4[routing.py\nassignment node]
        AG5[remediation.py\nremediation node]
        AG6[duplication.py\nduplicate detector]
        AG7[analytics.py\nanalytics node]
        AG8[kb_node.py\nKB search node]
        AG9[suggestion.py\nsuggestion node]
        AG10[staff_profiler.py\nskill inference]
        AG11[nexus_checkpoint.py\nLangGraph persist]
        AG12[ingestion.py\ncontent ingestion]
        AG13[tools/nexus_tools.py\n15 callable tools]
        AG14[tools/tool_registry.py\nRBAC enforcement]
    end

    subgraph "Services (services/)"
        SV1[ticket_service.py\nbusiness logic]
    end

    subgraph "Tasks (tasks/)"
        T1[ai.py\nembed + index]
        T2[nexus_ai.py\nmaster agent stream]
        T3[system.py\nSLA + heartbeat]
        T4[notifications.py\nalert sending]
        T5[analytics.py\nanalytics jobs]
        T6[remediation.py\nauto-remediation]
    end

    A2 --> SV1
    A7 --> AG1
    A8 --> T2
    SV1 --> C1
    AG1 --> AG13
    AG13 --> AG14
    T1 --> C7
    T2 --> AG1
    C5 --> C4
    A2 --> C4
    A5 --> C4

3. API Route Map

Complete endpoint inventory grouped by domain.

mindmap
  root((API v1))
    Auth
      POST /auth/register
      POST /auth/login
      POST /auth/token/refresh
      POST /auth/password/change
      POST /auth/password/forgot
      POST /auth/password/reset
    Tickets
      GET /tickets/statuses
      GET /tickets/priorities
      GET /tickets/search
      GET /tickets/paginated
      POST /tickets
      GET /tickets/:id
      PATCH /tickets/:id
      DELETE /tickets/:id
      POST /tickets/:id/messages
      GET /tickets/:id/messages
      PATCH /tickets/:id/messages/:msg_id
      DELETE /tickets/:id/messages/:msg_id
      POST /tickets/:id/attachments
      GET /tickets/:id/attachments
      GET /tickets/attachments/:id
      POST /tickets/upload
      POST /tickets/:id/feedback
    Knowledge Base
      POST /kb
      GET /kb
      GET /kb/search
      PATCH /kb/:id
      DELETE /kb/:id
      POST /kb/bulk-sync
      GET /kb/insights
      POST /kb/insights/:id/approve
    Nexus Agent
      POST /nexus/query
      POST /nexus/stream
      GET /nexus/thread/:id
      GET /nexus/history
    Escalations
      POST /escalations/rules
      GET /escalations/rules
      PATCH /escalations/rules/:id
      GET /escalations/breaches
      GET /escalations/audit
    Reports
      GET /reports/volume
      GET /reports/csat
      GET /reports/sla-compliance
      GET /reports/summary
    Dashboard
      GET /dashboard/hydration
    Workspace
      GET /workspace
      PATCH /workspace/:id
      POST /workspace/:id/invite
    Projects
      POST /projects
      GET /projects
      PATCH /projects/:id
      DELETE /projects/:id
    Notifications
      GET /notifications
      PATCH /notifications/mark-read
      DELETE /notifications/:id
    AI Trace
      GET /ai/trace/:ticket_id
    Workers
      GET /worker/stats
      GET /worker/history
    System
      GET /health
      GET /system/infra
    WebSocket
      WS /ws/:workspace_id
      WS /ws/tickets/:ticket_id

4. Database Entity Relationship

Core model relationships across all domains.

erDiagram
    WORKSPACES {
        uuid id PK
        string name
        timestamp created_at
        timestamp deleted_at
    }

    USERS {
        uuid id PK
        string email
        string hashed_password
        string full_name
        string global_role
        bool is_active
        timestamp created_at
    }

    USER_WORKSPACES {
        uuid user_id FK
        uuid workspace_id FK
        string role
        bool is_primary
    }

    PROJECTS {
        uuid id PK
        uuid workspace_id FK
        string name
        string description
        timestamp created_at
        timestamp deleted_at
    }

    TICKETS {
        uuid id PK
        uuid workspace_id FK
        uuid created_by FK
        uuid assigned_to FK
        uuid project_id FK
        uuid duplicate_of_id FK
        string title
        text description
        string category
        string priority
        string status
        vector embedding
        tsvector search_vector
        text ai_metadata
        text resolution_text
        string content_hash
        timestamp sla_deadline
        timestamp resolved_at
        uuid resolved_by FK
        timestamp created_at
        timestamp deleted_at
    }

    MESSAGES {
        uuid id PK
        uuid ticket_id FK
        uuid workspace_id FK
        uuid sender_id FK
        text content
        bool is_internal
        jsonb mentions
        timestamp created_at
        timestamp deleted_at
    }

    ATTACHMENTS {
        uuid id PK
        uuid workspace_id FK
        uuid uploader_id FK
        uuid ticket_id FK
        uuid article_id FK
        string filename
        string storage_path
        string storage_backend
        string content_type
        int file_size
        text ai_caption
        timestamp created_at
        timestamp deleted_at
    }

    KB_ARTICLES {
        uuid id PK
        uuid workspace_id FK
        uuid author_id FK
        uuid project_id FK
        uuid duplicate_of_id FK
        string title
        text content
        string category
        bool is_published
        text summary
        vector embedding
        tsvector search_vector
        int version
        int view_count
        int citation_count
        string content_hash
        timestamp created_at
        timestamp deleted_at
    }

    KB_ARTICLE_CHUNKS {
        uuid id PK
        uuid article_id FK
        int chunk_index
        text content
        vector embedding
        timestamp created_at
    }

    KB_ARTICLE_VERSIONS {
        uuid id PK
        uuid article_id FK
        int version_number
        uuid author_id FK
        string title
        text content
        string category
        timestamp created_at
    }

    ESCALATION_RULES {
        uuid id PK
        uuid workspace_id FK
        string name
        string priority_level
        int threshold_minutes
        string action
        bool is_active
        timestamp created_at
    }

    ESCALATION_AUDIT_LOG {
        uuid id PK
        uuid workspace_id FK
        uuid ticket_id FK
        uuid rule_id FK
        string action_taken
        timestamp created_at
    }

    FEEDBACK {
        uuid id PK
        uuid ticket_id FK
        uuid workspace_id FK
        uuid user_id FK
        int rating
        text comment
        timestamp created_at
    }

    NOTIFICATIONS {
        uuid id PK
        uuid workspace_id FK
        uuid user_id FK
        string type
        string title
        text content
        bool is_read
        timestamp created_at
        timestamp deleted_at
    }

    NEXUS_THREADS {
        uuid id PK
        uuid workspace_id FK
        uuid user_id FK
        string title
        bool is_hidden
        uuid ticket_id FK
        text gist
        jsonb metadata_json
        timestamp created_at
    }

    NEXUS_INTERACTIONS {
        uuid id PK
        uuid workspace_id FK
        uuid user_id FK
        uuid thread_id FK
        uuid ticket_id FK
        text input_query
        text ai_answer
        jsonb tool_trace
        jsonb extracted_params
        text thread_summary
        string status
        jsonb metadata_json
        timestamp created_at
    }

    NEXUS_MEMORY {
        uuid id PK
        uuid workspace_id FK
        uuid user_id FK
        string topic
        text context
        vector embedding
        timestamp created_at
    }

    NEXUS_CHECKPOINTS {
        string thread_id PK
        string checkpoint_id PK
        string channel
        int version
        string type
        bytea data
        timestamp created_at
    }

    AI_INTERACTIONS {
        uuid id PK
        uuid ticket_id FK
        uuid workspace_id FK
        string interaction_type
        string ai_model
        int duration_ms
        jsonb tool_calls
        jsonb ai_metadata
        string status
        timestamp created_at
    }

    AI_WORKFLOWS {
        uuid id PK
        uuid ticket_id FK
        uuid workspace_id FK
        string status
        jsonb steps_executed
        jsonb output
        timestamp created_at
    }

    REMEDIATIONS {
        uuid id PK
        uuid ticket_id FK
        uuid workspace_id FK
        string title
        text description
        string status
        timestamp created_at
    }

    KNOWLEDGE_INSIGHTS {
        uuid id PK
        uuid workspace_id FK
        string topic
        text context
        string suggested_title
        text suggested_content
        float confidence
        timestamp created_at
    }

    AUDIT_LOGS {
        uuid id PK
        uuid workspace_id FK
        uuid user_id FK
        string action
        string resource_type
        uuid resource_id
        jsonb changes
        string ip_address
        timestamp created_at
    }

    WORKER_JOBS {
        uuid id PK
        string task_name
        string status
        jsonb args
        jsonb kwargs
        jsonb metadata_json
        timestamp started_at
        timestamp completed_at
        int duration_ms
        text error_message
        timestamp created_at
    }

    WORKSPACES ||--o{ USER_WORKSPACES : "has members"
    USERS ||--o{ USER_WORKSPACES : "belongs to"
    WORKSPACES ||--o{ TICKETS : "contains"
    WORKSPACES ||--o{ KB_ARTICLES : "contains"
    WORKSPACES ||--o{ PROJECTS : "contains"
    WORKSPACES ||--o{ ESCALATION_RULES : "has"
    WORKSPACES ||--o{ NOTIFICATIONS : "has"
    WORKSPACES ||--o{ NEXUS_THREADS : "has"
    WORKSPACES ||--o{ KNOWLEDGE_INSIGHTS : "has"
    USERS ||--o{ TICKETS : "created_by"
    USERS ||--o{ TICKETS : "assigned_to"
    USERS ||--o{ MESSAGES : "sends"
    USERS ||--o{ NEXUS_THREADS : "owns"
    USERS ||--o{ NEXUS_INTERACTIONS : "makes"
    PROJECTS ||--o{ TICKETS : "groups"
    PROJECTS ||--o{ KB_ARTICLES : "groups"
    TICKETS ||--o{ MESSAGES : "has thread"
    TICKETS ||--o{ ATTACHMENTS : "has files"
    TICKETS ||--o{ FEEDBACK : "receives"
    TICKETS ||--o{ AI_INTERACTIONS : "traced by"
    TICKETS ||--o{ AI_WORKFLOWS : "processed by"
    TICKETS ||--o{ REMEDIATIONS : "has"
    TICKETS ||--o{ ESCALATION_AUDIT_LOG : "triggers"
    ESCALATION_RULES ||--o{ ESCALATION_AUDIT_LOG : "generates"
    KB_ARTICLES ||--o{ KB_ARTICLE_CHUNKS : "chunked into"
    KB_ARTICLES ||--o{ KB_ARTICLE_VERSIONS : "versioned as"
    KB_ARTICLES ||--o{ ATTACHMENTS : "has images"
    NEXUS_THREADS ||--o{ NEXUS_INTERACTIONS : "contains"
    NEXUS_THREADS ||--o{ NEXUS_CHECKPOINTS : "checkpointed as"

5. Auth & Session Flow

5a. Login & Token Issuance

sequenceDiagram
    participant C as Client
    participant API as FastAPI Auth
    participant DB as PostgreSQL
    participant Redis as Redis Local

    C->>API: POST /auth/login email + password
    API->>DB: SELECT user WHERE email=?
    DB-->>API: User record
    API->>API: bcrypt.verify(plain, hashed)
    alt Invalid credentials
        API-->>C: 401 Unauthorized
    end
    API->>DB: SELECT user_workspace WHERE user_id=?
    DB-->>API: workspace + role
    API->>API: create_access_token(sub, workspace_id, role, jti)
    API->>API: create_refresh_token(sub, jti)
    API-->>C: access_token + refresh_token + expires_in

5b. Request Authorization

flowchart TD
    REQ[Incoming Request] --> EXTRACT[Extract Bearer token\nfrom Authorization header]
    EXTRACT --> DECODE[jwt.decode HS256]
    DECODE --> VALID{Valid signature\n& not expired?}
    VALID -- No --> R401[401 Unauthorized]
    VALID -- Yes --> BLOCKLIST{Token JTI\nin Redis blocklist?}
    BLOCKLIST -- Yes --> R401
    BLOCKLIST -- No --> TYPE{Token type\n== access?}
    TYPE -- No --> R401
    TYPE -- Yes --> LOAD[Load User from DB]
    LOAD --> ACTIVE{user.is_active?}
    ACTIVE -- No --> R403[403 Forbidden]
    ACTIVE -- Yes --> ROLES[Resolve workspace role\nvia user_workspaces]
    ROLES --> RBAC{Required role\nsatisfied?}
    RBAC -- No --> R403
    RBAC -- Yes --> HANDLER[Route Handler]

5c. Token Refresh & Logout

sequenceDiagram
    participant C as Client
    participant API as FastAPI Auth
    participant Redis as Redis Local

    Note over C,Redis: Token Refresh
    C->>API: POST /auth/token/refresh with refresh_token
    API->>API: decode refresh_token, verify type==refresh
    API->>Redis: GET token:blocklist:JTI
    Redis-->>API: nil (not revoked)
    API->>API: issue new access_token
    API-->>C: new access_token

    Note over C,Redis: Logout / Password Change
    C->>API: POST /auth/password/change or logout
    API->>Redis: SET token:blocklist:JTI 1 EX TTL_SECS
    API-->>C: 200 OK
    Note right of Redis: Token revoked for remaining TTL

5d. WebSocket Authentication

sequenceDiagram
    participant B as Browser
    participant WS as WebSocket Endpoint
    participant Redis as Redis Local

    B->>WS: WSS /ws/WORKSPACE_ID?token=ACCESS_TOKEN
    WS->>WS: decode_access_token(token)
    WS->>Redis: GET token:blocklist:JTI
    Redis-->>WS: nil
    alt Token invalid / expired / revoked
        WS-->>B: Close 1008 Policy Violation
    end
    WS->>WS: Verify workspace_id matches token claim
    WS->>WS: Register connection in ConnectionManager
    WS->>Redis: SUBSCRIBE nexus:ws:workspace:WORKSPACE_ID
    loop Keep-alive
        WS-->>B: Events from pub/sub
        B-->>WS: ping
    end
    B->>WS: Disconnect
    WS->>WS: Unregister connection

6. WebSocket & SSE Real-time Architecture

6a. Distributed WebSocket Pub/Sub

graph TD
    subgraph "HTTP Worker 1"
        W1C[Client A\nConnection]
        W1M[ConnectionManager\nlocal registry]
        W1S[Redis Subscriber\nbackground task]
    end

    subgraph "HTTP Worker 2"
        W2C[Client B\nConnection]
        W2M[ConnectionManager\nlocal registry]
        W2S[Redis Subscriber\nbackground task]
    end

    subgraph "HTTP Worker 3"
        W3C[Client C\nConnection]
        W3M[ConnectionManager\nlocal registry]
        W3S[Redis Subscriber\nbackground task]
    end

    subgraph "Redis Local"
        CH1[nexus:ws:workspace:uuid]
        CH2[nexus:ws:user:uuid]
        CH3[nexus:ws:role:ws:role]
        CH4[nexus:ws:ticket:uuid]
    end

    TRIGGER[Event Source\ne.g. ARQ worker\nor API handler] -- PUBLISH --> CH1
    TRIGGER -- PUBLISH --> CH2
    TRIGGER -- PUBLISH --> CH3
    TRIGGER -- PUBLISH --> CH4

    CH1 --> W1S & W2S & W3S
    W1S --> W1M --> W1C
    W2S --> W2M --> W2C
    W3S --> W3M --> W3C

6b. Channel Selection Logic

flowchart TD
    EVENT[Broadcast Event] --> WHO{Who should receive?}

    WHO -- All users in workspace --> PUB1[PUBLISH\nnexus:ws:workspace:uuid]
    WHO -- Specific user only --> PUB2[PUBLISH\nnexus:ws:user:uuid]
    WHO -- All staff in role --> PUB3[PUBLISH\nnexus:ws:role:ws_uuid:role]
    WHO -- Ticket thread participants --> PUB4[PUBLISH\nnexus:ws:ticket:uuid]

    PUB1 & PUB2 & PUB3 & PUB4 --> REDIS[Redis Pub/Sub\nfan-out to all workers]
    REDIS --> WS[WebSocket frames\ndelivered to browsers]

6c. Nexus SSE Streaming Architecture

sequenceDiagram
    participant B as Browser
    participant HTTP as HTTP Worker (FastAPI)
    participant ARQ as ARQ Job Queue (Redis Cloud)
    participant W as ARQ Worker
    participant LG as LangGraph Agent
    participant RS as Redis Stream

    B->>HTTP: POST /nexus/stream query + workspace_id + thread_id
    HTTP->>HTTP: Auth + rate limit check
    HTTP->>ARQ: enqueue nexus_stream_task(job_id, query, ...)
    HTTP-->>B: StreamingResponse SSE headers 200 OK

    Note over HTTP,RS: HTTP worker reads Redis Stream while streaming to browser

    W->>ARQ: dequeue nexus_stream_task
    W->>LG: invoke LangGraph with stream=True
    loop LangGraph execution
        LG-->>W: event tool_called or tool_result or response_chunk
        W->>RS: XADD nexus:stream:JOB_ID event_data
        HTTP->>RS: XREAD BLOCK 3000ms
        RS-->>HTTP: event data
        HTTP-->>B: SSE data frame
    end
    LG-->>W: complete
    W->>RS: XADD nexus:stream:JOB_ID type=complete
    HTTP->>RS: XREAD complete event
    HTTP-->>B: SSE complete event
    HTTP-->>B: close stream

7. Ticket Lifecycle

7a. Status State Machine

stateDiagram-v2
    [*] --> OPEN : POST /tickets (customer creates)

    OPEN --> ACKNOWLEDGED : Staff claims ticket

    ACKNOWLEDGED --> IN_PROGRESS : Staff begins work

    IN_PROGRESS --> RESOLVED : Staff provides solution

    RESOLVED --> CLOSED : Customer confirms

    OPEN --> IN_PROGRESS : Direct escalation (admin bypass)

    CLOSED --> [*] : Terminal state

    note right of OPEN
        SLA clock starts
        AI triage runs
    end note

    note right of ACKNOWLEDGED
        Assignment confirmed
        Customer notified
    end note

    note right of IN_PROGRESS
        SLA breach monitored
        every 5 minutes
    end note

    note right of RESOLVED
        resolution_text saved
        CSAT survey sent
    end note

7b. Priority Levels

graph LR
    P0[P0 - Critical\nImmediate response\nSLA: 1h] --> P1
    P1[P1 - High\nUrgent\nSLA: 4h] --> P2
    P2[P2 - Medium\nStandard\nSLA: 24h] --> P3
    P3[P3 - Low\nBest effort\nSLA: 72h]

    style P0 fill:#ff4444,color:#fff
    style P1 fill:#ff8800,color:#fff
    style P2 fill:#ffcc00,color:#000
    style P3 fill:#44aa44,color:#fff

8. Ticket Creation & AI Triage Flow

8a. Creation Request Flow

sequenceDiagram
    participant C as Customer
    participant API as POST /tickets
    participant DB as PostgreSQL
    participant SVC as ticket_service.py
    participant ARQ as ARQ Queue
    participant WS as WebSocket Broadcast

    C->>API: POST /tickets title + description + category + priority
    API->>API: Validate auth + RBAC
    API->>SVC: create_ticket(payload, user, workspace)
    SVC->>DB: INSERT ticket (status=OPEN, priority, workspace_id)
    SVC->>DB: INSERT ai_workflow (status=QUEUED)
    DB-->>SVC: ticket_id
    SVC->>ARQ: enqueue run_ai_workflow(ticket_id)
    SVC->>ARQ: enqueue auto_summarize_ticket(ticket_id)
    SVC->>ARQ: enqueue generate_ticket_embedding(ticket_id)
    SVC->>WS: broadcast_to_workspace(workspace_id, ticket_created_event)
    SVC-->>API: TicketResponse
    API-->>C: 201 ticket_id + status OPEN

8b. AI Triage LangGraph Pipeline

flowchart TD
    START([ARQ: run_ai_workflow\nticket_id]) --> FETCH

    FETCH[Fetch ticket from DB\ntitle + description + attachments] --> INGEST

    INGEST[Ingestion Node\nagents/ingestion.py\nExtract: category, keywords,\nattachment types] --> VISION

    VISION{Has image\nattachments?}
    VISION -- Yes --> CAPTION[Vision Node\ncore/vision.py\nGenerate image captions\nvia Claude Vision API]
    VISION -- No --> EMBED
    CAPTION --> EMBED

    EMBED[Embedding Node\nGenerate 768-dim vector\nvia nomic-embed-text-1.5\nUpdate ticket.embedding] --> DEDUP

    DEDUP[Duplication Node\nagents/duplication.py\nCompare embedding + content_hash\nagainst existing tickets] --> DUPCHECK

    DUPCHECK{Duplicate\ndetected?}
    DUPCHECK -- Yes --> MARKDUP[Set ticket.duplicate_of_id\nLink to original ticket\nStatus: ACKNOWLEDGED]
    DUPCHECK -- No --> KBSEARCH

    KBSEARCH[KB Search Node\nagents/kb_node.py\nHybrid search KB\nfor matching articles] --> KBHIT

    KBHIT{KB article\nfound with\nhigh confidence?}
    KBHIT -- Yes --> SUGGEST[Suggestion Node\nagents/suggestion.py\nAttach KB reference\nto ticket.ai_metadata]
    KBHIT -- No --> ROUTE

    SUGGEST --> ROUTE

    ROUTE[Routing Node\nagents/routing.py\nResolve target staff:\n1. Specialists\n2. Team generalists\n3. Load-balanced] --> ASSIGN

    ASSIGN[Update ticket.assigned_to\nSet status=ACKNOWLEDGED\nBroadcast assignment event] --> REMEDIATE

    REMEDIATE[Remediation Node\nagents/remediation.py\nGenerate auto-resolution\nif confidence > threshold] --> REMCHECK

    REMCHECK{Auto-resolve\nconfidence > 85%?}
    REMCHECK -- Yes --> AUTORESOLVE[Create Remediation record\nSet resolution_text\nTransition to RESOLVED]
    REMCHECK -- No --> LOGWF

    AUTORESOLVE --> LOGWF
    MARKDUP --> LOGWF

    LOGWF[Update ai_workflow.status=SUCCESS\nLog AI interactions to ai_interactions\nUpdate WorkerJob record] --> NOTIFY

    NOTIFY[send_triple_notification\nassigned staff + customer] --> END([Done])

9. Ticket SLA & Escalation Flow

9a. Cron Monitor

flowchart TD
    CRON([Cron: every 5 min\nmonitor_sla_thresholds]) --> RULES

    RULES[Fetch all active EscalationRules\nfor all workspaces] --> LOOP

    LOOP[For each rule] --> FETCH

    FETCH[Fetch tickets WHERE\nstatus NOT IN RESOLVED, CLOSED\nAND priority == rule.priority_level] --> CHECK

    CHECK{time_in_status\n> rule.threshold_minutes?} -- No --> NEXTTICKET[Next ticket]
    NEXTTICKET --> LOOP

    CHECK -- Yes --> ACTION{rule.action}

    ACTION -- NOTIFY_LEAD --> NOTIF[Find SC_LEAD users\nin workspace\nSend notification + email]
    ACTION -- REASSIGN --> DO_REASSIGN[Find available agent\nUpdate ticket.assigned_to\nBroadcast reassignment]
    ACTION -- AUTO_RESOLVE --> AUTORES[Set ticket status=RESOLVED\nAdd system message]

    NOTIF & DO_REASSIGN & AUTORES --> AUDIT

    AUDIT[INSERT escalation_audit_log\nticket_id + rule_id + action_taken] --> BROADCAST

    BROADCAST[broadcast_to_workspace\nescalation_triggered event] --> NEXTTICKET

9b. SLA Breach Timeline

gantt
    title SLA Breach Timeline Example (P1 Ticket - 4h SLA)
    dateFormat HH:mm
    axisFormat %H:%M

    section Ticket Lifecycle
    Created OPEN            :milestone, m1, 00:00, 1m
    AI Triage completes     :active, 00:00, 5m
    Assigned ACKNOWLEDGED   :milestone, m2, 00:05, 1m
    SLA deadline            :crit, milestone, m3, 04:00, 1m

    section SLA Monitoring
    Monitor run 1           :active, 00:05, 1m
    Monitor run 2           :active, 00:10, 1m
    Monitor run at 3h mark  :active, 03:00, 1m
    NOTIFY_LEAD at 3h 30m   :crit, 03:30, 1m
    REASSIGN at 4h          :crit, 04:00, 1m

10. Knowledge Base Article Workflow

10a. Article Creation & Indexing

sequenceDiagram
    participant A as Author (Staff)
    participant API as POST /kb
    participant DB as PostgreSQL
    participant ARQ as ARQ Queue
    participant W as ARQ Worker
    participant EMB as Embedding Model
    participant Cache as Redis Cache

    A->>API: POST /kb title + content + category + project_id
    API->>DB: INSERT kb_articles (version=1)
    API->>DB: INSERT kb_article_versions (version_number=1)
    DB-->>API: article_id
    API->>ARQ: enqueue index_kb_article(article_id)
    API->>Cache: DEL kb:list:WORKSPACE_ID:*
    API->>Cache: DEL kb:categories:WORKSPACE_ID
    API->>Cache: DEL cache:search:kb:WORKSPACE_ID:*
    API-->>A: 201 KBArticleResponse

    W->>ARQ: dequeue index_kb_article
    W->>DB: SELECT kb_article WHERE id=article_id
    W->>W: chunk_content(content, size=1200, overlap=200)
    loop For each chunk
        W->>EMB: embed(chunk_text) returns 768-dim vector
        W->>DB: UPSERT kb_article_chunks (chunk_index, content, embedding)
    end
    W->>W: compute centroid embedding (avg of all chunks)
    W->>DB: UPDATE kb_articles SET embedding=centroid, version+=1
    W->>DB: UPDATE kb_articles SET search_vector=to_tsvector(title+content)
    W->>W: sync_images_to_storage(article_id)
    W->>DB: UPDATE worker_jobs SET status=SUCCESS

10b. Article Update & Version Control

flowchart TD
    UPDATE[PATCH /kb/:id\ntitle? + content? + category?] --> FETCH[Fetch current article]
    FETCH --> NEWVER[INSERT kb_article_versions\nversion_number = current + 1]
    NEWVER --> UPDARTICLE[UPDATE kb_articles\ncontent, title, category\nincrement version]
    UPDARTICLE --> REINDEX[Enqueue index_kb_article\nre-embed all chunks]
    REINDEX --> INVAL[Invalidate Redis caches:\nkb:list:*, kb:categories:*\ncache:search:kb:*]
    INVAL --> BROADCAST[WebSocket: article_updated event]
    BROADCAST --> DONE([200 Updated])

    subgraph "Version History"
        V1[Version 1\nOriginal]
        V2[Version 2\nFirst edit]
        V3[Version 3\nLatest]
        V1 --> V2 --> V3
    end

10c. Article Deletion

flowchart TD
    DEL[DELETE /kb/:id] --> SOFT[Soft delete:\nUPDATE deleted_at=now]
    SOFT --> CHUNKS[Mark kb_article_chunks orphaned]
    CHUNKS --> DUPREFS[Find articles WHERE duplicate_of_id=deleted_id\nMark as stale]
    DUPREFS --> CACHES[Invalidate all workspace caches]
    CACHES --> DONE([204 No Content])

11. Hybrid Search System

11a. 3-Branch Search Architecture

flowchart TD
    QUERY[Search Query\nGET /kb/search?q=...] --> CACHE{Redis cache hit?\ncache:search:kb:ws:hash}

    CACHE -- Hit --> RETURN_CACHE[Return cached results\nTTL: 300s]

    CACHE -- Miss --> PARALLEL

    PARALLEL[Execute 3 branches in parallel]

    PARALLEL --> B1 & B2 & B3

    subgraph "Branch 1: Keyword Search"
        B1[PostgreSQL TSVector\nGIN index: idx_kb_search_vector\nQuery: search_vector @@ plainto_tsquery\nReturns: rank + article_id]
    end

    subgraph "Branch 2: Semantic Search"
        B2[Generate query embedding\nnomic-embed-text-1.5\n768-dim vector\nHNSW index: idx_kb_embedding_hnsw\nQuery: embedding cosine distance\nReturns: distance + article_id]
    end

    subgraph "Branch 3: Multimodal Search"
        B3[Extract image captions\nfrom article attachments\nMatch via text similarity\nReturns: caption_score + article_id]
    end

    B1 & B2 & B3 --> MERGE[Merge results by article_id]

    MERGE --> SCORE[Score each article:\ntext_score = ts_rank x 0.40\nsemantic_score = 1 - distance/2 x 0.60\nimage_bonus = caption_score x 0.10\nfinal = text + semantic + image]

    SCORE --> SORT[Sort by final score DESC\nDedup by article_id\nLimit: top N results]

    SORT --> STORE_CACHE[SETEX cache:search:kb:ws:hash\nTTL: 300s]

    STORE_CACHE --> RESPONSE[Return articles + scores + match_types]

11b. Ticket Search Flow

flowchart TD
    Q[GET /tickets/search?q=...] --> TCACHE{Cache hit?\ncache:search:ticket:ws:hash}
    TCACHE -- Yes --> CACHED[Return cached]
    TCACHE -- No --> HYBRID

    HYBRID[Hybrid search on tickets table] --> T1 & T2

    subgraph "Text Search"
        T1[TSVector GIN index\nidx_ticket_search_vector\nQuery: title + description]
    end

    subgraph "Semantic Search"
        T2[pgvector HNSW\nidx_ticket_embedding_hnsw\nCosine similarity on\nticket.embedding]
    end

    T1 & T2 --> MERGE2[Merge + score + sort]
    MERGE2 --> CACHE2[Cache 300s]
    CACHE2 --> RESP2[TicketSearchResponse]

11c. RAG Chunk Retrieval (Agent KB Search)

flowchart TD
    AGENT[Agent: kb_search_tool\nquery + workspace_id] --> SEMCACHE{Semantic cache hit?\nnexus:semantic_cache:ws:hash}
    SEMCACHE -- Yes --> CACHED[Return cached answer\nTTL: 3600s]
    SEMCACHE -- No --> EMBED[Generate query embedding]
    EMBED --> CHUNKS[Query kb_article_chunks:\nSELECT ordered by\nembedding cosine distance\nLIMIT 5]
    CHUNKS --> CONTEXT[Build RAG context:\nchunk_1 + chunk_2 + ... + chunk_5]
    CONTEXT --> LLM[Claude: synthesize answer\nusing chunks as context]
    LLM --> STORECACHE[Store in semantic cache\nnexus:semantic_cache:ws:hash\nTTL: 3600s]
    STORECACHE --> RETURN[Return answer + sources + chunks]

12. Worker & Background Job System

12a. ARQ Worker Architecture

graph TD
    subgraph "ARQ Queue (Redis Cloud - Upstash)"
        Q[arq:regular\njob queue]
        CRON_Q[cron schedule\nstored in Redis]
    end

    subgraph "Worker Pool"
        W1[Worker Process 1]
        W2[Worker Process 2]
        W3[Worker Process 3]
        CRON[Cron Dispatcher]
    end

    subgraph "Job Lifecycle"
        JOB_START[on_job_start:\nINSERT worker_jobs\nstatus=RUNNING]
        JOB_END[on_job_end:\nUPDATE worker_jobs\nstatus=SUCCESS/FAILED\nduration_ms]
    end

    subgraph "DB"
        WJTABLE[(worker_jobs table)]
    end

    API[FastAPI Handler] -- enqueue --> Q
    AGENT[Agent Tool] -- enqueue --> Q

    W1 & W2 & W3 --> Q
    CRON --> CRON_Q
    CRON_Q --> W1 & W2 & W3

    W1 & W2 & W3 --> JOB_START --> JOB_END --> WJTABLE

12b. Cron Job Schedule

gantt
    title Cron Job Schedule (24-hour view)
    dateFormat HH:mm
    axisFormat %H:%M

    section System
    record_system_heartbeat every 1 min    :active, 00:00, 1440m
    monitor_sla_thresholds every 5 min     :active, 00:00, 1440m
    nexus_pulse_check every 5 min          :active, 00:00, 1440m

    section Cache
    purge_stale_semantic_cache run 1       :00:00, 60m
    purge_stale_semantic_cache run 2       :01:00, 60m
    purge_stale_semantic_cache run 3       :02:00, 60m

    section Insights
    refresh_workspace_insights run 1       :00:00, 30m
    refresh_workspace_insights run 2       :00:30, 30m
    refresh_workspace_insights run 3       :01:00, 30m

    section Analytics
    generate_nightly_analytics 2am daily   :crit, 02:00, 30m

12c. On-Demand Task Catalog

graph LR
    subgraph "Triggered by API"
        OD1[index_kb_article\narticle created/updated]
        OD2[generate_ticket_embedding\nticket created]
        OD3[auto_summarize_ticket\nticket created]
        OD4[process_kb_import_task\nbulk-sync endpoint]
    end

    subgraph "Triggered by Agent/Tools"
        OD5[nexus_stream_task\nnexus/stream endpoint]
        OD6[vectorize_nexus_interaction\nagent query complete]
        OD7[execute_remediation_hook\nremediation approved]
        OD8[harvest_expertise_task\nstaff profiler]
    end

    subgraph "Triggered by Cron"
        OD9[generate_global_insight\nworkspace nightly]
        OD10[crystallize_memory\nold interactions to memory]
        OD11[generate_workspace_insights\ndashboard refresh]
        OD12[ai_dynamic_nudge_pulse\nproactive suggestions]
    end

    subgraph "Triggered by Events"
        OD13[send_triple_notification\nticket events]
        OD14[notify_mentions\nmessage @mentions]
        OD15[record_workflow_step_task\nworkflow telemetry]
        OD16[recover_nexus_history\nthread restore]
    end

    OD1 & OD2 & OD3 & OD4 --> ARQ[ARQ Worker Pool]
    OD5 & OD6 & OD7 & OD8 --> ARQ
    OD9 & OD10 & OD11 & OD12 --> ARQ
    OD13 & OD14 & OD15 & OD16 --> ARQ

13. Nexus Master Agent Architecture

13a. LangGraph Graph Structure

flowchart TD
    INPUT([User Query\nworkspace + role + thread_id]) --> FASTTRACK

    FASTTRACK{Fast-track regex\npattern match?}
    FASTTRACK -- create/raise ticket --> CT_INTENT[intent: CREATE_TICKET]
    FASTTRACK -- kb/knowledge/docs --> KB_INTENT[intent: KB_SEARCH]
    FASTTRACK -- analytic/trend/metric --> AN_INTENT[intent: GET_ANALYTICS]
    FASTTRACK -- assign...to --> AS_INTENT[intent: ASSIGN_TICKET]
    FASTTRACK -- No match --> LLM_CLASSIFY

    LLM_CLASSIFY[intent_classifier node\nClaude classifies intent\nfrom message history] --> INTENT

    CT_INTENT & KB_INTENT & AN_INTENT & AS_INTENT --> INTENT

    INTENT[Resolved intent] --> SEMCACHE

    SEMCACHE{Semantic cache hit?} -- Hit --> RETURN_CACHED[Return cached answer]

    SEMCACHE -- Miss --> TOOL_SELECT[tool_selector node\nMap intent to tool function]

    TOOL_SELECT --> TOOL_EXEC[execute_tool node\nRun selected tool\nfrom tool registry]

    TOOL_EXEC --> VERIFY

    VERIFY{Risky action?\ncreate_ticket\nchange_status} -- Yes + not approved --> APPROVAL[Request human approval\naction_approved: false]

    VERIFY -- No risk or approved --> RESPOND

    APPROVAL --> INPUT

    RESPOND[respond node\nFormat answer + sources\nUpdate NexusThread\nSave NexusInteraction] --> OUTPUT

    OUTPUT([Response:\nanswer + sources\nthread_id + tool_trace])

13b. Tool Registry (15 Tools)

mindmap
  root((Nexus Tools))
    Knowledge Base
      kb_search_tool
      recall_knowledge
    Tickets
      create_ticket_tool
      search_tickets_tool
      get_ticket_details_tool
      add_ticket_comment_tool
      change_ticket_status_tool
      assign_ticket_tool
      update_ticket_attributes_tool
      similar_incident_finder
    Analytics
      nexus_analytics_tool
      sla_audit_tool
      summarize_workspace_tool
      sentiment_pulse_tool
    Projects
      project_pulse_tool

13c. RBAC Tool Enforcement

flowchart TD
    CALL[Agent calls tool] --> REGISTRY[tool_registry.py\ncheck_tool_permission]

    REGISTRY --> ROLE{User role}

    ROLE -- CUSTOMER_USER --> CU_TOOLS[Allowed:\nkb_search_tool\ncreate_ticket_tool\nrecall_knowledge\nget_ticket_details own only]

    ROLE -- SC_AGENT --> AG_TOOLS[Allowed: all above +\nadd_ticket_comment_tool\nchange_ticket_status_tool\nassign_ticket_tool\nsentiment_pulse_tool\nsimilar_incident_finder]

    ROLE -- SC_LEAD / SC_ADMIN --> LEAD_TOOLS[Allowed: all above +\nsla_audit_tool\nnexus_analytics_tool\nsummarize_workspace_tool\nupdate_ticket_attributes_tool\nproject_pulse_tool]

    ROLE -- SUPERADMIN --> ALL[All tools + no rate limits]

    CU_TOOLS & AG_TOOLS & LEAD_TOOLS & ALL --> EXEC[Execute tool]
    EXEC --> RESULT[Return result to graph]

13d. Memory & Checkpoint System

flowchart LR
    subgraph "Short-term (Thread)"
        THREAD[NexusThread\nconversation session]
        INTER[NexusInteraction\nper-turn query+answer+tool_trace]
        CHECK[NexusCheckpoints\nLangGraph state snapshots]
        THREAD --> INTER
        THREAD --> CHECK
    end

    subgraph "Long-term (Memory)"
        MEM[NexusMemory\ncrystallized facts\nper workspace+user\n768-dim embedding]
    end

    subgraph "Semantic Cache"
        SCACHE[nexus_semantic_cache\nDB + Redis\nworkspace:hash to answer\nTTL: 1h]
    end

    INTER -- crystallize_memory\ncron task --> MEM
    INTER -- vectorize_nexus_interaction\ntask --> SCACHE

    MEM -- recall_knowledge\ntool --> AGENT[Agent response]
    SCACHE -- cache hit\nskips LangGraph --> AGENT
    CHECK -- recover_nexus_history\ntask --> THREAD

14. Nexus SSE Streaming Flow

Detailed sequence showing each SSE event type emitted during agent execution.

sequenceDiagram
    participant B as Browser (EventSource)
    participant API as FastAPI HTTP Worker
    participant Q as ARQ Queue (Redis Cloud)
    participant W as ARQ Worker
    participant G as LangGraph
    participant T as Tool e.g. kb_search
    participant RS as Redis Stream

    B->>API: POST /nexus/stream query + workspace_id + thread_id
    API->>API: Generate job_id = uuid4()
    API->>Q: LPUSH arq:regular nexus_stream_task(job_id, ...)
    API-->>B: HTTP 200 + SSE headers Content-Type: text/event-stream

    par HTTP worker reads stream
        loop until complete
            API->>RS: XREAD BLOCK 3000ms STREAMS nexus:stream:JOB_ID
            RS-->>API: events if any
            API-->>B: SSE data frames
        end
    and ARQ worker executes agent
        W->>Q: BRPOP arq:regular
        Q-->>W: nexus_stream_task job
        W->>G: compile_graph().stream(state)
        G->>RS: XADD type=thinking content=Classifying intent
        G->>G: fast-track / classify intent
        G->>RS: XADD type=tool_called tool=kb_search_tool
        G->>T: execute kb_search_tool(query)
        T-->>G: articles + chunks + answer
        G->>RS: XADD type=tool_result tool=kb_search_tool
        G->>G: respond node stream Claude response
        loop Response tokens
            G->>RS: XADD type=response_chunk content=token
        end
        G->>RS: XADD type=complete thread_id=ID interaction_id=ID
        W->>W: save NexusInteraction to DB
        W->>W: enqueue vectorize_nexus_interaction
    end

SSE event format:

data: {"type":"thinking","content":"Classifying intent..."}

data: {"type":"tool_called","tool":"kb_search_tool","args":{"query":"..."}}

data: {"type":"tool_result","tool":"kb_search_tool","result":{"articles":[...]}}

data: {"type":"response_chunk","content":"Based on our KB, "}

data: {"type":"complete","thread_id":"...","interaction_id":"..."}

15. Redis Keys & Channels Map

mindmap
  root((Redis Local\nlocalhost:6379))
    Pub/Sub Channels
      nexus:ws:workspace:uuid
      nexus:ws:user:uuid
      nexus:ws:role:ws_uuid:role
      nexus:ws:ticket:uuid
    Streams
      nexus:stream:job_id
    Cache Keys
      kb:list:ws_id:filter_hash
      kb:categories:ws_id
      cache:search:kb:ws_id:query_hash
      cache:search:ticket:ws_id:query_hash
      dashboard:insights:ws_id:date
      nexus:semantic_cache:ws:hash
    Rate Limiting
      rl:user:user_id
    Token Blocklist
      token:blocklist:jti
    Distributed Locks
      nexus:latch:cron:job_name
      nexus:latch:job:job_id

16. Notification Flow

16a. Triple Notification (In-app + Email + Webhook)

flowchart TD
    EVENT[Triggering Event\ne.g. ticket assigned,\nSLA breached,\nstatus changed] --> ENQUEUE

    ENQUEUE[ARQ: enqueue\nsend_triple_notification\nuser_id + type + payload] --> W

    W[ARQ Worker\ntasks/notifications.py] --> N1 & N2 & N3

    subgraph "In-App Notification"
        N1[INSERT notifications\nworkspace_id + user_id + type\ntitle + content + is_read=false]
        N1 --> WS_NOTIF[PUBLISH\nnexus:ws:user:USER_ID\ntype=notification]
    end

    subgraph "Email Notification"
        N2[core/email.py\nSMTP / SendGrid\nHTML template rendered]
    end

    subgraph "Webhook"
        N3{Workspace has\nwebhook URL?}
        N3 -- Yes --> WEBHOOK[HTTP POST to webhook URL\nevent_type + payload + workspace_id]
        N3 -- No --> SKIP[Skip]
    end

    WS_NOTIF & N2 & WEBHOOK & SKIP --> DONE([Done])

16b. @Mention Notification

sequenceDiagram
    participant U as Staff User
    participant API as POST /messages
    participant DB as PostgreSQL
    participant ARQ as ARQ Queue
    participant W as Worker
    participant WS as WebSocket

    U->>API: POST /tickets/:id/messages content with @alice mention
    API->>DB: INSERT message content + mentions list
    API->>ARQ: enqueue notify_mentions(message_id, user_ids)
    API-->>U: 201 MessageResponse

    W->>ARQ: dequeue notify_mentions
    W->>DB: SELECT users WHERE id IN mentions
    loop For each mentioned user
        W->>DB: INSERT notification type=MENTION
        W->>WS: PUBLISH nexus:ws:user:MENTIONED_USER_ID type=mention + ticket_id
    end

17. File Attachment Flow

17a. Upload

sequenceDiagram
    participant U as User
    participant API as POST /tickets/:id/attachments
    participant VIS as core/vision.py
    participant FS as File Storage
    participant DB as PostgreSQL
    participant ARQ as ARQ Queue

    U->>API: POST multipart/form-data file + ticket_id
    API->>API: Validate size + content_type whitelist
    API->>FS: store(file_bytes, path=workspace/ticket/filename)
    FS-->>API: storage_path + storage_backend
    API->>DB: INSERT attachments\nticket_id + filename + storage_path\ncontent_type + file_size
    DB-->>API: attachment_id

    alt Image attachment (image/*)
        API->>ARQ: enqueue generate_image_caption(attachment_id)
        Note right of ARQ: Worker calls Claude Vision API\nUpdates attachment.ai_caption\nUsed in multimodal search
    end

    API-->>U: 201 AttachmentResponse id + filename + url

17b. Download

flowchart TD
    GET[GET /tickets/attachments/:id] --> AUTH[Verify user belongs\nto attachment workspace]
    AUTH --> FETCH[SELECT attachment by id\nWHERE deleted_at IS NULL]
    FETCH --> BACKEND{storage_backend}
    BACKEND -- local --> READ[Read file from disk\nstream response]
    BACKEND -- s3 --> PRESIGN[Generate presigned URL\nredirect 302]
    READ & PRESIGN --> RESPONSE[FileResponse / redirect]

18. KB Insights Workflow

AI-driven discovery of knowledge gaps from recurring ticket patterns.

flowchart TD
    CRON([Cron: every 30 min\nrefresh_active_workspace_insights]) --> FETCH

    FETCH[Fetch all active workspaces] --> LOOP[For each workspace]

    LOOP --> ARQ_ENQUEUE[Enqueue\ngenerate_global_insight\nworkspace_id]

    ARQ_ENQUEUE --> WORKER

    subgraph "ARQ Worker: generate_global_insight"
        WORKER[Fetch tickets\ncreated in last 7 days\nstatus != CLOSED] --> CLUSTER

        CLUSTER[Group tickets by\ntopic / category / keywords\nUsing LLM clustering] --> GAPS

        GAPS[Identify recurring topics\nnot covered by existing KB articles\nCompare via semantic search] --> INSIGHTS

        INSIGHTS[For each gap:\nGenerate suggested_title\nGenerate draft suggested_content\nAssign confidence score 0-1] --> STORE

        STORE[UPSERT knowledge_insights\nlink to source tickets\nvia knowledge_insight_tickets] --> CACHE

        CACHE[Cache insights:\ndashboard:insights:ws_id:date\nTTL: 3600s]
    end

    CACHE --> UI[Staff sees suggestions\nGET /kb/insights]

    UI --> APPROVE{Staff action}

    APPROVE -- Approve --> CREATE[POST /kb/insights/:id/approve\nINSERT kb_articles from insight\nEnqueue index_kb_article\nMark insight as approved]

    APPROVE -- Dismiss --> DISMISS[DELETE insight record]

    CREATE --> INDEX[Article indexed\nAvailable in search]

Summary: Data Flow Reference

flowchart LR
    subgraph "Ingress"
        HTTP[REST API\nHTTPS]
        WSS[WebSocket\nWSS]
        SSE_IN[SSE\nHTTPS streaming]
    end

    subgraph "Processing"
        SYNC[Sync handlers\nFastAPI routes]
        ASYNC[Async workers\nARQ tasks]
        AGENT_PROC[Agent execution\nLangGraph]
    end

    subgraph "Storage"
        PG_S[(PostgreSQL\nfacts + vectors)]
        REDIS_S[(Redis Local\npub/sub + cache + streams)]
        REDIS_Q[(Redis Cloud ARQ\njob queue)]
        FILES[(File Storage)]
    end

    subgraph "Egress"
        WS_OUT[WebSocket push\nto browsers]
        SSE_OUT[SSE events\nto browser]
        EMAIL_OUT[Email notifications]
        WEBHOOK_OUT[Webhook callbacks]
    end

    HTTP --> SYNC
    WSS --> SYNC
    SSE_IN --> SYNC

    SYNC --> PG_S
    SYNC --> REDIS_S
    SYNC --> REDIS_Q

    REDIS_Q --> ASYNC
    ASYNC --> AGENT_PROC
    ASYNC --> PG_S
    ASYNC --> REDIS_S
    ASYNC --> FILES

    AGENT_PROC --> REDIS_S

    REDIS_S --> WS_OUT
    REDIS_S --> SSE_OUT
    ASYNC --> EMAIL_OUT
    ASYNC --> WEBHOOK_OUT