Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
5eb4857
0
Parent(s):
Beta 1.0: Pure Backend Release (Excluding Frontend)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignoreAdded+17
- .gitignoreAdded+82
- DockerfileAdded+56
- README.mdAdded+19
- agents/__init__.pyAdded
- agents/analytics.pyAdded+46
- agents/duplication.pyAdded+145
- agents/nexus_checkpoint.pyAdded+93
- agents/nexus_master.pyAdded+562
- agents/remediation.pyAdded+96
- agents/routing.pyAdded+110
- agents/safety.pyAdded+97
- agents/state.pyAdded+44
- agents/suggestion.pyAdded+118
- agents/summarizer.pyAdded+43
- agents/tools/nexus_tools.pyAdded+434
- agents/triage.pyAdded+102
- agents/utils.pyAdded+213
- agents/workflow.pyAdded+247
- alembic.iniAdded+115
- alembic/READMEAdded+1
- alembic/env.pyAdded+111
- alembic/script.py.makoAdded+26
- alembic/versions/0001_initial_consolidated.pyAdded+365
- alembic/versions/0002_fix_attachments_schema.pyAdded+54
- alembic/versions/0003_final_schema_reconciliation.pyAdded+85
- alembic/versions/4c626672022a_add_meta_infra_health_table.pyAdded+44
- alembic/versions/archive/0b3641c15213_add_resolution_fields_to_ticket.pyAdded+112
- alembic/versions/archive/175b693efa2c_add_nexus_agent_tables.pyAdded+67
- alembic/versions/archive/263c3f7b1819_initial_migration.pyAdded+162
- alembic/versions/archive/27de6d53f3f0_add_is_active_to_escalation_rules.pyAdded+30
- alembic/versions/archive/3dfe53d8e8aa_add_summary_to_kb_articles.pyAdded+30
- alembic/versions/archive/86b5efeb3906_make_nexus_thread_id_nullable.pyAdded+34
- alembic/versions/archive/9a883ee7d42e_add_attachment_source_url.pyAdded+30
- alembic/versions/archive/a1b2c3d4e5f6_create_notifications_table.pyAdded+39
- alembic/versions/archive/b2895ed533fc_add_ai_workflows_table_correct.pyAdded+51
- alembic/versions/archive/b480d2a38d7d_add_soft_delete_to_notifications.pyAdded+30
- alembic/versions/archive/c1ae7937bc77_add_kbarticle_and_vector_support.pyAdded+56
- alembic/versions/archive/d5fd341999f5_add_duplicate_tagging_to_kb_articles.pyAdded+38
- alembic/versions/archive/e7f94a821c56_add_attachment_multimodal_and_storage.pyAdded+51
- alembic/versions/archive/f3a2b1c0d9e8_adjust_vector_dimensions_to_768.pyAdded+36
- alembic/versions/f62561e3e123_add_user_gist_column.pyAdded+28
- api/__init__.pyAdded
- api/v1/__init__.pyAdded
- api/v1/ai.pyAdded+128
- api/v1/attachments.pyAdded+182
- api/v1/auth.pyAdded+242
- api/v1/dashboard.pyAdded+272
- api/v1/escalations.pyAdded+148
- api/v1/feedback.pyAdded+74
1234567891011121314151617# Build context optimization**/node_modules**/__pycache__**/.pytest_cache**/.venv**/.dockerignore**/.git**/.github# Frontend Source & Dist (Monorepo)frontend/node_modules/**/node_modules/logs/*.loguploads/*.Project guidelinesDockerfiledocker-compose.yml12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Environment.env.env.prod.env.*
# Python__pycache__/*.py[cod]*$py.class*.so.Pythonenv/build/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# Virtual Environmentvenv/ENV/env.bak/venv.bak/
# Project Metadata & Tooling.agents/.Project guidelines/.vscode/.idea/*.swp*.swo
# Project Data & Artifactspostgres_data/uploads/logs/*.logtmp/!tmp/init_nexus.py!tmp/seed_remediation.py!tmp/seed_rules.py
# Testing.pytest_cache/.coveragehtmlcov/
# Docker.docker_cache/
# System.DS_StoreThumbs.db
# Documentation & Miscdocs/node_modules/**/node_modules/**/dist/**/build/
# Cloud Push Optimization (Remove Binaries for HF)*.png*.jpg*.jpeg*.gif*.ico*.pdf*.zip*.tar.gz1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# --- STAGE 1: BASE (Lightweight Core) ---FROM python:3.11-slim AS base
ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ PYTHONPATH=/app
WORKDIR /app
# Install minimal system dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ libpq-dev \ gcc \ curl \ && apt-get clean && rm -rf /var/lib/apt/lists/*
# Install core requirementsCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Copy application codeCOPY . .
# Create directory for uploadsRUN mkdir -p uploads logs
EXPOSE 8000CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
# --- STAGE 2: HYBRID-AI (Optimized Worker) ---FROM base AS heavy
# Install lightweight AI dependencies (No Torch/CUDA)COPY requirements-ai.txt .RUN pip install --no-cache-dir -r requirements-ai.txt
# PRE-CACHE ONNX WEIGHTS# This ensures sub-second boot times for local CLIP inference without 10GB of bloat.# Placeholder for ONNX download script - in production, this would pull from HF.RUN mkdir -p models && \ python -c "print('Pre-caching ONNX weights for clip-ViT-B-32...')"
# --- STAGE 3: PRODUCTION (Unified API + Worker) ---FROM heavy AS production
# Expose Hugging Face default portEXPOSE 7860
# Ensure entrypoint script is executable and has Linux line endingsRUN sed -i 's/\r$//' scripts/run_prod.sh && \ chmod +x scripts/run_prod.sh
# Use the unified sidecar entrypointCMD ["./scripts/run_prod.sh"]12345678910111213141516171819---title: Nexus Backendemoji: 🪐colorFrom: indigocolorTo: slatesdk: dockerapp_port: 7860pinned: false---
# Nexus AI Backend (Beta 1.0)
Distributed, local-first AI platform for unified workspace management.
### Deployment Details- **Architecture**: Unified FastAPI + Arq Worker Sidecar.- **Port**: 7860 (Hugging Face Default).- **Persistence**: Mounted via `/data` storage bucket.- **AI Intelligence**: Hybrid (Local Ollama Tunnel + Google Gemini).12345678910111213141516171819202122232425262728293031323334353637383940414243444546from typing import Any, Dict, Listfrom langchain_core.prompts import ChatPromptTemplatefrom core.llm import get_llmfrom datetime import datetime
ANALYTICS_PROMPT = """You are a Senior Service Delivery Manager. Analyze the FOLLOWING metrics and recent ticket data (last 48h).Generate a concise, high-impact "Executive Health Narrative" for the workspace lead.
Current Metrics:- SLA Compliance: {sla_rate}%- Breached Count: {breaches}- Analyzed Tickets: {ticket_count}
Ticket Data:{ticket_data}
REPORT RULES:1. MAXIMUM 4-5 LINES total.2. Structure: One sentence on Overall Health (Green/Amber/Red), one on the primary volume/breach driver, and one on a specific tactical recommendation.3. Use bolding to highlight critical metrics or actions. Professional Markdown format."""
async def generate_service_insights(metrics: Dict[str, Any], tickets: List[Dict[str, Any]]) -> str: """ Generates an executive summary of service performance using LLM analytics. """ llm = get_llm() # Format ticket data for analysis (Privacy-Safe: No Titles) formatted_data = "\n".join([ f"- [{t['priority']}] Category: {t.get('category' or 'General')} (Active for {t['duration_mins']:.1f}m)" for t in tickets ]) prompt = ChatPromptTemplate.from_template(ANALYTICS_PROMPT) chain = prompt | llm response = await chain.ainvoke({ "sla_rate": round(metrics.get("sla_compliance_rate", 0) * 100, 1), "breaches": metrics.get("breached_tickets", 0), "ticket_count": len(tickets), "ticket_data": formatted_data or "No recent ticket data available." }) return response.content123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145from typing import Any, Dict, List, Optionalfrom uuid import UUIDfrom datetime import datetimefrom langchain_core.runnables import RunnableConfigfrom agents.state import AgentStatefrom agents.state import AgentStatefrom core.llm import get_text_embeddings, get_image_embeddingsfrom core.vision import resolve_imagefrom core.logging import get_loggerfrom models.ticket import Ticket, TicketStatusfrom models.attachment import Attachmentfrom sqlalchemy import select, desc, func
logger = get_logger(__name__)
async def duplication_node(state: AgentState, config: RunnableConfig) -> Dict[str, Any]: """ Node that checks for duplicate tickets based on semantic similarity of title and description. """ db = config["configurable"].get("db") if not db: logger.error(f"Duplication node missing DB session for ticket {state['ticket_id']}") return {"errors": ["No library session provided for duplication check"]}
workspace_id = UUID(state["workspace_id"]) if isinstance(state["workspace_id"], str) else state["workspace_id"] ticket_id = UUID(state["ticket_id"]) if isinstance(state["ticket_id"], str) else state["ticket_id"] try: # 1. Generate text embedding for the current ticket content content = f"{state['title']}\n\n{state['description']}" logger.debug(f"Duplication node embedding content for ticket {ticket_id}") query_vector = await get_text_embeddings().aembed_query(content) # PERSIST: Save embedding to self immediately ticket_res = await db.execute(select(Ticket).where(Ticket.id == ticket_id)) self_ticket = ticket_res.scalar_one_or_none() if self_ticket: self_ticket.embedding = query_vector db.add(self_ticket) await db.commit() # 1.5. IMAGE DUPLICATION CHECK: Index and check current screenshots att_stmt = select(Attachment).where(Attachment.ticket_id == ticket_id, Attachment.content_type.like("image/%")) current_attachments = (await db.execute(att_stmt)).scalars().all() img_matches = [] if current_attachments: img_model = get_image_embeddings() for att in current_attachments: # Resolve and embed if not already done if not att.embedding: resolved = await resolve_image(db, workspace_id, str(att.id)) if resolved: att.embedding = await img_model.aembed_query(resolved["image_url"]["url"]) db.add(att) if att.embedding: # Search for similar images in OTHER tickets # Threshold for image identicality is high (0.85+) img_stmt = ( select(Attachment) .where( Attachment.workspace_id == workspace_id, Attachment.ticket_id != ticket_id, Attachment.ticket_id.isnot(None), Attachment.embedding.isnot(None) ) .order_by(Attachment.embedding.cosine_distance(att.embedding)) .limit(1) ) sim_att = (await db.execute(img_stmt)).scalar_one_or_none() if sim_att: dist = (await db.execute(select(Attachment.embedding.cosine_distance(att.embedding)).where(Attachment.id == sim_att.id))).scalar() sim = 1 - dist if sim >= 0.85: img_matches.append({"other_ticket_id": sim_att.ticket_id, "score": sim}) await db.commit()
# 2. Search for similar tickets (Text Similarity) # We use cosine_distance: 0 is identical, 1 is opposite. # Similarity = 1 - distance. We want similarity > 0.75, so distance < 0.25. stmt = ( select(Ticket) .where( Ticket.workspace_id == workspace_id, Ticket.id != ticket_id, Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED]), Ticket.deleted_at.is_(None), Ticket.embedding.isnot(None) ) .order_by(Ticket.embedding.cosine_distance(query_vector)) .limit(1) ) result = await db.execute(stmt) match = result.scalar_one_or_none() if img_matches: # Sort by best match img_matches.sort(key=lambda x: x["score"], reverse=True) best_img = img_matches[0] logger.warning(f"VISUAL DUPLICATE DETECTED: Ticket {ticket_id} matches {best_img['other_ticket_id']} via image content ({best_img['score']:.2%})") return { "is_duplicate": True, "duplicate_of_id": best_img["other_ticket_id"], "status": TicketStatus.CLOSED, "metadata": { "duplication_match_id": str(best_img["other_ticket_id"]), "duplication_type": "visual", "duplication_similarity": round(best_img["score"], 4), "duplication_reason": f"Visual match ({best_img['score']:.2%}) detected via CLIP similarity." } }
if match: dist_stmt = select(Ticket.embedding.cosine_distance(query_vector)).where(Ticket.id == match.id) distance = (await db.execute(dist_stmt)).scalar() or 1.0 similarity = 1 - distance if similarity >= 0.70: return { "is_duplicate": True, "duplicate_of_id": match.id, "status": TicketStatus.CLOSED, "metadata": { "duplication_match_id": str(match.id), "duplication_type": "textual", "duplication_similarity": round(similarity, 4), "duplication_reason": f"Semantic text similarity ({similarity:.2%}) exceeds 70% threshold." } } return { "is_duplicate": False, "processed_steps": [{"name": "DUPLICATION", "status": "success", "timestamp": datetime.utcnow().isoformat()}], "metadata": {"duplication_check_performed": True, "vision_check": bool(current_attachments)} } except Exception as e: logger.error(f"Duplication node failed for ticket {ticket_id}: {str(e)}") return { "errors": [f"Duplication check failed: {str(e)}"], "processed_steps": [{"name": "DUPLICATION", "status": "error", "timestamp": datetime.utcnow().isoformat()}], "metadata": {"duplication_check_success": False} }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import jsonfrom datetime import datetime, timezonefrom typing import Any, Dict, List, Optionalfrom langgraph.checkpoint.base import ( BaseCheckpointSaver, Checkpoint, CheckpointMetadata, CheckpointTuple, SerializerProtocol,)from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializerfrom sqlalchemy import select, update, insertfrom core.database import async_session_factoryfrom models.nexus_checkpoint import NexusCheckpoint
class SQLAlchemySaver(BaseCheckpointSaver): """ Custom LangGraph checkpointer using our project's SQLAlchemy engine. This bypasses the Windows/Psycopg/libpq issues. """ def __init__(self, serde: Optional[SerializerProtocol] = None): super().__init__(serde=serde or JsonPlusSerializer())
def _get_checkpoint_tuple(self, row: Any) -> CheckpointTuple: return CheckpointTuple( config={"configurable": {"thread_id": row.thread_id, "checkpoint_id": row.checkpoint_id}}, checkpoint=self.serde.loads(row.checkpoint_data), metadata=self.serde.loads(row.metadata_data) if row.metadata_data else {}, parent_config={"configurable": {"thread_id": row.thread_id, "checkpoint_id": row.parent_id}} if row.parent_id else None, )
async def aget_tuple(self, config: Dict[str, Any]) -> Optional[CheckpointTuple]: thread_id = config["configurable"]["thread_id"] checkpoint_id = config["configurable"].get("checkpoint_id") async with async_session_factory() as session: if checkpoint_id: stmt = select(NexusCheckpoint).where( NexusCheckpoint.thread_id == str(thread_id), NexusCheckpoint.checkpoint_id == str(checkpoint_id) ) else: stmt = select(NexusCheckpoint).where( NexusCheckpoint.thread_id == str(thread_id) ).order_by(NexusCheckpoint.checkpoint_id.desc()).limit(1) result = await session.execute(stmt) row = result.scalar_one_or_none() if row: return self._get_checkpoint_tuple(row) return None
async def alist(self, config: Optional[Dict[str, Any]], *, before: Optional[Dict[str, Any]] = None, limit: Optional[int] = None) -> Any: # Minimal implementation for listing history thread_id = config["configurable"]["thread_id"] if config else None async with async_session_factory() as session: stmt = select(NexusCheckpoint) if thread_id: stmt = stmt.where(NexusCheckpoint.thread_id == str(thread_id)) stmt = stmt.order_by(NexusCheckpoint.checkpoint_id.desc()) if limit: stmt = stmt.limit(limit) result = await session.execute(stmt) for row in result.scalars(): yield self._get_checkpoint_tuple(row)
async def aput(self, config: Dict[str, Any], checkpoint: Checkpoint, metadata: CheckpointMetadata, new_versions: Any) -> Dict[str, Any]: thread_id = config["configurable"]["thread_id"] checkpoint_id = checkpoint["id"] async with async_session_factory() as session: stmt = insert(NexusCheckpoint).values( thread_id=str(thread_id), checkpoint_id=str(checkpoint_id), parent_id=str(config["configurable"].get("checkpoint_id")) if config["configurable"].get("checkpoint_id") else None, checkpoint_data=self.serde.dumps(checkpoint), metadata_data=self.serde.dumps(metadata) if metadata else None ) # Use upsert or handle existing await session.execute(stmt) await session.commit() return {"configurable": {"thread_id": thread_id, "checkpoint_id": checkpoint_id}} # Sync methods are required by the interface but we'll focus on async def get_tuple(self, config: Dict[str, Any]) -> Optional[CheckpointTuple]: raise NotImplementedError("Use aget_tuple instead") def list(self, config: Optional[Dict[str, Any]], *, before: Optional[Dict[str, Any]] = None, limit: Optional[int] = None) -> Any: raise NotImplementedError("Use alist instead") def put(self, config: Dict[str, Any], checkpoint: Checkpoint, metadata: CheckpointMetadata, new_versions: Any) -> Dict[str, Any]: raise NotImplementedError("Use aput instead")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562from typing import Annotated, Any, Dict, List, Optional, TypedDictfrom uuid import UUIDimport jsonimport loggingfrom langgraph.graph import StateGraph, ENDfrom langchain_core.messages import BaseMessage, HumanMessage, SystemMessage, AIMessagefrom langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholderfrom core.llm import get_llmfrom core.logging import get_loggerfrom agents.tools.nexus_tools import ( kb_search_tool, ticket_query_tool, nexus_analytics_tool, similar_incident_finder, project_pulse_tool, sentiment_pulse_tool, knowledge_drafting_tool, assign_ticket_tool, update_ticket_status_tool, dynamic_remediation_tool)from agents.safety import is_malicious_query, sanitize_outputfrom core.vision import extract_visual_contextfrom core.database import async_session_factoryfrom models.ai_interaction import AIInteractionfrom models.nexus_interaction import NexusInteractionfrom models.remediation_audit import RemediationAuditfrom agents.utils import safe_uuidfrom core import logging
logger = logging.get_logger(__name__)
# --- AGENT STATE ---
class NexusState(TypedDict): """Conversational state for the Master Agent.""" messages: Annotated[List[BaseMessage], lambda x, y: x + y] workspace_id: UUID user_role: str user_name: str sources: List[str] is_agent: bool current_tool_output: Optional[str] pending_actions: List[Dict[str, Any]] # Actions awaiting approval action_approved: bool # Flag for HITL vision_context: List[Dict[str, Any]] # Extracted from attachments ticket_id: Optional[UUID] # Current ticket context target_user_id: Optional[UUID] # For assignments target_status: Optional[str] # For status updates user_id: UUID # For specialized auditing internal_summary: str # Long-term summarized memory thread_id: Optional[UUID] = None # Added for session consistency ticket_context: str # Hydrated technical context of the current ticket ai_gist: Dict[str, Any] # Long-term durable memory store
# --- NODES ---
async def nexus_vision_gatherer(state: NexusState) -> Dict[str, Any]: """ Extracts visual context (images) from ticket attachments. """ if not state.get("ticket_id"): return {"vision_context": []} async with async_session_factory() as db: # We look for images in the last human message or the ticket itself last_msg = state["messages"][-1].content vision_context = await extract_visual_context(db, state["workspace_id"], last_msg) return {"vision_context": vision_context}
async def nexus_context_hydrator(state: NexusState) -> Dict[str, Any]: """ Hydrates the state with full technical context if a ticket_id is present. Ensures the LLM "sees" the description and findings without needing a tool call. """ t_id = safe_uuid(state.get("ticket_id")) if not t_id: return {"ticket_context": "No active ticket context."} from models.ticket import Ticket from sqlalchemy import select async with async_session_factory() as db: stmt = select(Ticket).where(Ticket.id == t_id) res = await db.execute(stmt) ticket = res.scalar_one_or_none() if not ticket: return {"ticket_context": "Ticket context provided but record not found."} # Format the context block findings = ticket.ai_metadata.get("processed_steps", []) findings_str = "\n".join([f"- {s.get('name')}: {s.get('status')}" for s in findings]) context = f""" TICKET_CONTEXT: ID: {ticket.id} TITLE: {ticket.title} STATUS: {ticket.status} PRIORITY: {ticket.priority} DESCRIPTION: {ticket.description} AI_FINDINGS_LOG: {findings_str or 'No autonomous findings yet.'} INTERNAL_SUMMARY: {ticket.ai_metadata.get('summaries', {}).get('internal_summary', 'None')} """ return {"ticket_context": context.strip()}
async def nexus_input_guard(state: NexusState) -> Dict[str, Any]: """ Scans the user query for prompt injection and ill intent. """ last_msg = state["messages"][-1].content if is_malicious_query(last_msg): msg = AIMessage(content="I'm sorry, I cannot fulfill this request due to safety policy violations.") return {"messages": [msg], "current_tool_output": "SAFETY_BLOCK"} return {"current_tool_output": "PROCEED"}
async def nexus_router(state: NexusState) -> Dict[str, Any]: """ Analyzes the query and determines which secured tool to call. """ if state.get("current_tool_output") == "SAFETY_BLOCK": return {"current_tool_output": "SAFETY_BLOCK"} # Constant write to satisfy LangGraph llm = get_llm() last_msg = state["messages"][-1].content # Prompt the LLM to choose tools and extract parameters prompt = ChatPromptTemplate.from_template(""" You are the Nexus Intent Resolver. Analyze the query and provide a JSON list of tools and their parameters. Query: {query} Persona: {persona} (Is internal staff: {is_agent}) Context: {{ "ticket_id": "{ticket_id}" }} Long-Term Memory: {summary} Tools available: - KB_SEARCH: {{ "tool": "KB_SEARCH", "query": "search_string" }} - TICKETS: {{ "tool": "TICKETS", "status_filter": "open" }} - ANALYTICS: {{ "tool": "ANALYTICS" }} (USE FOR: "visualize", "trends", "charts", "graphs", "distribution", "analysis") - SIMILAR_INCIDENTS: {{ "tool": "SIMILAR_INCIDENTS", "query": "current_problem" }} (USE ONLY for troubleshooting) - PROJECT_PULSE: {{ "tool": "PROJECT_PULSE", "project_name": "name" }} - SENTIMENT_CHECK: {{ "tool": "SENTIMENT_CHECK", "ticket_id": "UUID" }} - ASSIGN_TICKET: {{ "tool": "ASSIGN_TICKET", "target_user_id": "UUID", "ticket_id": "UUID" }} - UPDATE_STATUS: {{ "tool": "UPDATE_STATUS", "new_status": "CLOSED/RESOLVED", "ticket_id": "UUID" }} - REMEDIATE: {{ "tool": "REMEDIATE", "action": "RESET_VPN/RESTART_SERVICE/FLUSH_CACHE", "params": {{ "user_email": "...", "service_name": "..." }} }} - CONVERSE: {{ "tool": "CONVERSE" }} TICKET_DATA (AUTOMATICALLY LOADED): {ticket_context} Constraint: For any request involving visualization or trends, prioritze the ANALYTICS tool alone. Avoid redundant SIMILAR_INCIDENTS calls unless explicitly troubleshoot-related. Respond ONLY with a JSON list: [{{ "tool": "NAME", "params": {{...}} }}] """) persona = "Internal Staff" if state["is_agent"] else "Customer" chain = prompt | llm tool_json = (await chain.ainvoke({ "query": last_msg, "persona": persona, "is_agent": state["is_agent"], "ticket_id": str(state.get("ticket_id") or "None"), "summary": state.get("internal_summary", "No prior history."), "ticket_context": state.get("ticket_context", "None") })).content.strip() # Try to parse or fallback to CONVERSE try: # Strip potential markdown blocks clean_json = tool_json.replace("```json", "").replace("```", "").strip() parsed = json.loads(clean_json) return {"current_tool_output": clean_json} except: return {"current_tool_output": '[{"tool": "CONVERSE"}]'}
import asyncio
async def nexus_tool_executor(state: NexusState) -> Dict[str, Any]: """ Executes multiple chosen tools concurrently using asyncio.gather. """ tool_input = state.get("current_tool_output", "") if tool_input == "SAFETY_BLOCK": return {} # Handle multiple tools (JSON list) try: intents = json.loads(tool_input) except: intents = [{"tool": "CONVERSE"}] query = state["messages"][-1].content ws_id = state["workspace_id"] is_agent = state["is_agent"] tasks = [] task_labels = [] pending_actions = [] update_data = {} for intent in intents: tool_name = intent.get("tool", "").upper() params = intent.get("params", {}) role = state.get("user_role", "customer_user") is_ws_admin = role == "customer_admin" if tool_name == "KB_SEARCH": tasks.append(kb_search_tool(params.get("query", query), ws_id)) task_labels.append("Nexus Knowledge Base") elif tool_name == "TICKETS": t_id = safe_uuid(params.get("ticket_id")) tasks.append(ticket_query_tool(ws_id, ticket_id=t_id, status_filter=params.get("status_filter"), role=role)) task_labels.append("Workspace Ticket Registry") elif tool_name == "ANALYTICS": # All users can see analytics, but tool logic will scrub details tasks.append(nexus_analytics_tool(ws_id, role=role)) task_labels.append("SQL Metadata Engine") elif tool_name == "SIMILAR_INCIDENTS" and (is_agent or is_ws_admin): tasks.append(similar_incident_finder(params.get("query", query), ws_id, role=role)) task_labels.append("Historical Resolution Archive") elif tool_name == "PROJECT_PULSE": tasks.append(project_pulse_tool(params.get("project_name", ""), ws_id)) task_labels.append("Project Management Module") elif tool_name == "SENTIMENT_CHECK" and is_agent: t_id = safe_uuid(params.get("ticket_id") or state.get("ticket_id")) if t_id: tasks.append(sentiment_pulse_tool(t_id, ws_id)) task_labels.append("Conversation Sentiment Engine") else: tasks.append(asyncio.sleep(0)) task_labels.append("SENTIMENT_CHECK [FAILED]: Malformed ticket_id ID.") elif tool_name == "ASSIGN_TICKET" and is_agent: t_id = safe_uuid(params.get("ticket_id") or state.get("ticket_id")) u_id = safe_uuid(params.get("target_user_id")) if t_id and u_id: pending_actions.append({"tool": "ASSIGN_TICKET", "description": f"Assign ticket {t_id} to user {u_id}"}) update_data["target_user_id"] = u_id update_data["ticket_id"] = t_id else: tasks.append(asyncio.sleep(0.01)) task_labels.append("ASSIGN_TICKET [FAILED]: Malformed ticket_id or user_id.") elif tool_name == "UPDATE_STATUS" and is_agent: t_id = safe_uuid(params.get("ticket_id") or state.get("ticket_id")) stat = params.get("new_status") if t_id and stat: pending_actions.append({"tool": "UPDATE_STATUS", "description": f"Update ticket {t_id} to {stat}"}) update_data["target_status"] = stat update_data["ticket_id"] = t_id else: tasks.append(asyncio.sleep(0.01)) task_labels.append("UPDATE_STATUS [FAILED]: Malformed ticket_id.") elif tool_name == "REMEDIATE" and is_agent: act = params.get("action") if act: pending_actions.append({"tool": "REMEDIATE", "action": act, "params": params, "description": f"Trigger automated fix: {act} with params {params}"}) update_data["remediation_data"] = {"action": act, "params": params} elif tool_name in ["SIMILAR_INCIDENTS", "SENTIMENT_CHECK", "KB_DRAFT", "ASSIGN_TICKET", "UPDATE_STATUS"]: tasks.append(asyncio.sleep(0.01)) task_labels.append("Permission Denied: 3SC Internal Only")
# PARALLEL EXECUTION (Read tools) read_results = [] if tasks: read_results = await asyncio.gather(*tasks) combined_output = "\n\n".join([f"Source [{label}]:\n{res}" for label, res in zip(task_labels, read_results)]) # If writing actions are pending and NOT approved yet if pending_actions and not state.get("action_approved"): return { "current_tool_output": f"TOOL_DATA (READS): {combined_output}\n\nPENDING_ACTIONS: {pending_actions}", "sources": task_labels, "pending_actions": pending_actions, **update_data } # If approved, or only reads if state.get("action_approved") and pending_actions: # Perform the actual writes here! write_tasks = [] for action in pending_actions: if action["tool"] == "ASSIGN_TICKET": write_tasks.append(assign_ticket_tool(state.get("ticket_id"), state.get("target_user_id"), ws_id)) elif action["tool"] == "UPDATE_STATUS": write_tasks.append(update_ticket_status_tool(state.get("ticket_id"), state.get("target_status"), ws_id)) elif action["tool"] == "REMEDIATE": rem = action.get("params") or {} write_tasks.append(dynamic_remediation_tool(action["action"], rem, ws_id)) write_results = await asyncio.gather(*write_tasks) combined_output += "\n\n" + "\n".join(write_results)
return {"current_tool_output": f"TOOL_DATA: {combined_output}", "sources": task_labels, "pending_actions": [], **update_data}
from langgraph.errors import GraphInterrupt
async def nexus_approval_node(state: NexusState) -> Dict[str, Any]: """ Mandatory pause for human approval on "Write" actions. """ if state.get("pending_actions") and not state.get("action_approved"): # This will pause the graph execution raise GraphInterrupt(f"Approval required for actions: {state['pending_actions']}") return {"action_approved": state.get("action_approved", False)}
async def nexus_responder(state: NexusState) -> Dict[str, Any]: """ Formats the final response based on role and tool output. Generates Mermaid charts if analytical data is present. """ llm = get_llm() tool_data = state.get("current_tool_output", "") query = state["messages"][-1].content sources = ", ".join(state.get("sources", [])) system_prompt = f""" You are Nexus, the highly advanced AI Master for the 3SC support workspace. You assist users—both customers and staff—with intelligence, clarity, and precision. User Role: {state['user_role']}. Is Agent: {state['is_agent']} TONE & STYLE: - Be helpful, professional, and concise. - Avoid meta-commentary about the "System State" or "Tool Data" unless it's genuinely useful for the user to know why a specific request failed. - If you lack data (Tool Data is empty), simply explain what information you need or how you can proceed together (e.g. "I couldn't find a ticket with that ID, could you please double-check it?"). - Do NOT use robotic headers like "🛡️ Nexus Master Intelligence" unless the situation genuinely calls for a formal system report. CAPABILITIES: - If Tool Data is present, provide a detailed answer, citing sources appropriately: [Sources: {sources}]. - Use Mermaid.js diagrams to visualize any analytics or trends provided in the data. - If images or visual context are provided in the vision_context, incorporate those findings into your answer. CURRENT TICKET CONTEXT: {state.get('ticket_context', 'No ticket active.')} """ prompt = ChatPromptTemplate.from_messages([ ("system", system_prompt), # Memory Layer: Full conversation history MessagesPlaceholder(variable_name="messages"), ("human", "Tool Output provided: {tool_data}\n\nLatest Query: {query}") ]) chain = prompt | llm # We pass the full message list to the placeholder response = await chain.ainvoke({ "messages": state["messages"], "tool_data": tool_data, "query": query }) # Return as an AIMessage return {"messages": [response]}
async def nexus_output_guard(state: NexusState) -> Dict[str, Any]: """ Final sanitization of the AI response to mask PII and technical data. """ last_msg = state["messages"][-1] if not isinstance(last_msg, AIMessage): return {"messages": []} # Return empty list (no-op) to satisfy LangGraph sanitized_text = sanitize_output(last_msg.content, state["is_agent"]) last_msg.content = sanitized_text return {"messages": [last_msg]}async def nexus_history_pruner(state: NexusState) -> Dict[str, Any]: """ Prevents context bloat by distilling pruned messages into a long-term internal summary. Maintains a lean active window (last 15) while ensuring 0% detail loss of long-term intent. """ if len(state["messages"]) > 15: # 1. Identify what we are slicing off pruned_messages = state["messages"][:-15] active_messages = state["messages"][-15:] # 2. Distill the history recursively llm = get_llm() old_summary = state.get("internal_summary", "No prior history.") # Format the pruned block for the LLM history_str = "\n".join([f"{m.type.upper()}: {m.content}" for m in pruned_messages]) prompt = ChatPromptTemplate.from_template(""" You are the Nexus Memory Distiller. Your job is to update the Long-Term Summary of a conversation. Current Summary: {old_summary} New messages being archived: {new_history} Instructions: 1. Update the Summary to incorporate key facts, user preferences, and unresolved issues from the new messages. 2. Keep the summary under 300 words. 3. Be precise and technical. New Updated Summary: """) chain = prompt | llm new_summary_resp = await chain.ainvoke({"old_summary": old_summary, "new_history": history_str}) new_thread_summary = new_summary_resp.content.strip()
# 3. CRYSTALLIZATION: Extract Durable Facts for the User Gist gist_prompt = ChatPromptTemplate.from_template(""" You are the Nexus Identity Architect. Extract 'Durable Facts' from this history to update the User's Long-Term Gist. Current Gist: {old_gist} Recent History: {new_history} Extract and Merge: - Preferences (UI, data format, tone) - Recurring Technical Context (specific projects, persistent errors) - Professional Persona (Agent vs Customer context) Respond with a JSON object representing the NEW unified gist. """) gist_chain = gist_prompt | llm new_gist_resp = await gist_chain.ainvoke({ "old_gist": json.dumps(state.get("ai_gist", {})), "new_history": history_str }) try: # ROBUST JSON EXTRACTION: Find the first { and last } to avoid conversational noise content = new_gist_resp.content.strip() start_idx = content.find('{') end_idx = content.rfind('}') if start_idx != -1 and end_idx != -1: clean_gist = content[start_idx:end_idx+1] new_gist = json.loads(clean_gist) else: raise ValueError("No viable JSON gist found in response.") # 4. Persistence: Write Gist to User record async with async_session_factory() as db: from models.user import User from sqlalchemy import update await db.execute( update(User) .where(User.id == state["user_id"]) .values(ai_gist=new_gist) ) await db.commit() return { "messages": active_messages, "internal_summary": new_thread_summary, "ai_gist": new_gist } except Exception as e: logger.error(f"Crystallization Failed: {str(e)}") return { "messages": active_messages, "internal_summary": new_thread_summary } return {"messages": []} # No-op
async def nexus_forensic_auditor(state: NexusState) -> Dict[str, Any]: """ Logs each and everything about this execution to the AIInteraction table. """ ws_id = state["workspace_id"] u_id = state["user_id"] t_id = state.get("ticket_id") # We now log every interaction, even those without a ticket_id async with async_session_factory() as db: try: interaction = NexusInteraction( workspace_id=ws_id, user_id=u_id, thread_id=state.get("thread_id") or UUID("00000000-0000-0000-0000-000000000001"), # Standardize on thread_id ticket_id=t_id, input_query=state["messages"][-2].content if len(state["messages"]) >= 2 else "New Session", ai_answer=state["messages"][-1].content, tool_trace=state.get("sources", []), extracted_params={ "target_user_id": str(state.get("target_user_id")) if state.get("target_user_id") else None, "target_status": state.get("target_status") }, metadata_json={ "is_agent": state["is_agent"], "role": state["user_role"], "vision_context_count": len(state.get("vision_context", [])) } ) db.add(interaction) # 2. Specialized Remediation Audit (if active) for action in state.get("pending_actions", []): if action["tool"] == "REMEDIATE" and state.get("action_approved"): audit = RemediationAudit( workspace_id=ws_id, ticket_id=t_id, user_id=u_id, action_type=action["action"], parameters=action.get("params", {}), reasoning="Automated fix identified and approved by staff.", is_successful=True, execution_log=state.get("current_tool_output") ) db.add(audit) await db.commit() except Exception as e: # Audit failures should NEVER crash the agent logger.error(f"Nexus Auditor Failed: {str(e)}") await db.rollback() return {"current_tool_output": state.get("current_tool_output")}
# --- GRAPH ---
from agents.nexus_checkpoint import SQLAlchemySaver
def create_nexus_graph(): workflow = StateGraph(NexusState) checkpointer = SQLAlchemySaver() workflow.add_node("vision", nexus_vision_gatherer) workflow.add_node("hydrator", nexus_context_hydrator) workflow.add_node("input_guard", nexus_input_guard) workflow.add_node("router", nexus_router) workflow.add_node("executor", nexus_tool_executor) workflow.add_node("approval", nexus_approval_node) workflow.add_node("responder", nexus_responder) workflow.add_node("pruner", nexus_history_pruner) workflow.add_node("output_guard", nexus_output_guard) workflow.add_node("auditor", nexus_forensic_auditor) workflow.set_entry_point("vision") workflow.add_edge("vision", "hydrator") workflow.add_edge("hydrator", "input_guard") def should_continue(state: NexusState) -> str: if state.get("current_tool_output") == "SAFETY_BLOCK": return "auditor" # Log even if blocked return "router" workflow.add_conditional_edges("input_guard", should_continue, {"router": "router", "auditor": "auditor"}) workflow.add_edge("router", "executor") def check_approval(state: NexusState) -> str: if state.get("pending_actions") and not state.get("action_approved"): return "approval" return "responder"
workflow.add_conditional_edges("executor", check_approval, {"approval": "approval", "responder": "responder"}) workflow.add_edge("approval", "executor") workflow.add_edge("responder", "pruner") workflow.add_edge("pruner", "output_guard") workflow.add_edge("output_guard", "auditor") workflow.add_edge("auditor", END) return workflow.compile(checkpointer=checkpointer)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Remediation Node for the AI Workflow.Determines if an automated fix can be applied based on the ticket category."""
from typing import Any, Dictfrom datetime import datetimeimport uuidfrom sqlalchemy import selectfrom arq import create_poolfrom arq.connections import RedisSettings
from agents.state import AgentStatefrom core.config import get_settingsfrom core.logging import get_loggerfrom models.remediation import RemediationHook
logger = get_logger(__name__)settings = get_settings()
async def remediation_node(state: AgentState, config: Dict[str, Any]) -> Dict[str, Any]: """ Checks for available remediation hooks and queues them if found. """ db = config["configurable"].get("db") if not db: logger.error(f"Remediation node missing DB session for ticket {state.get('ticket_id')}") return {"errors": ["No database session provided for remediation"]} category = state.get("category") if not category: logger.info(f"No category assigned to ticket {state.get('ticket_id')}, skipping remediation.") return { "next_node": "routing", "processed_steps": [{"name": "REMEDIATION", "status": "skipped", "timestamp": datetime.utcnow().isoformat()}] } workspace_id = uuid.UUID(state["workspace_id"]) if isinstance(state["workspace_id"], str) else state["workspace_id"] # 1. Check for a matching hook in the workspace stmt = select(RemediationHook).where( (RemediationHook.workspace_id == workspace_id) & (RemediationHook.trigger_category == category) ) result = await db.execute(stmt) hook = result.scalar_one_or_none() if not hook: logger.debug(f"No remediation hook found for category '{category}' in workspace {workspace_id}") return { "next_node": "routing", "processed_steps": [{"name": "REMEDIATION", "status": "not_found", "timestamp": datetime.utcnow().isoformat()}] } logger.info(f"Found remediation hook {hook.id} for ticket {state.get('ticket_id')}") # 2. Queue the background job via Arq try: redis = await create_pool(RedisSettings.from_dsn(settings.REDIS_URL)) # High-Priority: Using a dedicated queue name for remediation job = await redis.enqueue_job( "execute_remediation_hook", str(state["ticket_id"]), str(hook.id), _queue_name="arq:critical" ) await redis.close() logger.info(f"Queued remediation job {job.job_id} for ticket {state.get('ticket_id')}") return { "status": "in_progress", "processed_steps": [{"name": "REMEDIATION", "status": "success", "timestamp": datetime.utcnow().isoformat()}], "metadata": { "remediation_triggered": True, "remediation_hook_id": str(hook.id), "remediation_job_id": job.job_id }, "next_node": "suggestion" } except Exception as e: logger.error(f"Failed to queue remediation job: {str(e)}") return { "errors": [f"Remediation queuing failed: {str(e)}"], "processed_steps": [{"name": "REMEDIATION", "status": "error", "timestamp": datetime.utcnow().isoformat()}], "next_node": "routing" }
def should_continue_remediation(state: AgentState) -> str: """ Router to determine if the workflow should proceed to routing or skip to suggestion. """ next_node = state.get("next_node", "routing") logger.info(f"Remediation router directing to: {next_node}") return next_node123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110from typing import Any, Dict, List, Optionalfrom uuid import UUIDfrom datetime import datetimefrom langchain_core.runnables import RunnableConfigfrom agents.state import AgentStatefrom agents.utils import get_available_agentsfrom sqlalchemy import select, funcfrom models.ticket import Ticket, TicketStatusfrom models.user import User, UserRole
from core.logging import get_logger
logger = get_logger(__name__)
async def routing_node(state: AgentState, config: RunnableConfig) -> Dict[str, Any]: """ Node that assigns the ticket to an agent based on workload (Load Balancing). """ db = config["configurable"].get("db") if not db: logger.error(f"Routing node missing DB session for ticket {state.get('ticket_id')}") return {"errors": ["No database session provided for routing"], "next_node": "END"} workspace_id = UUID(state["workspace_id"]) if isinstance(state["workspace_id"], str) else state["workspace_id"] category = state.get("category", "General") priority = state.get("priority", "P2") logger.debug(f"Routing node calculating workload for workspace {workspace_id}") # 1. Fetch all SC agents in the workspace agents = await get_available_agents(db, workspace_id) # ... if not agents: logger.warning(f"Routing fallback: No active agents found. Searching for Manager/Lead...") # Fallback to ANY Lead or Admin in the workspace stmt = select(User).where( User.workspace_id == workspace_id, User.role.in_([UserRole.SC_LEAD, UserRole.SC_ADMIN]), User.deleted_at.is_(None) ).limit(1) res = await db.execute(stmt) manager = res.scalar_one_or_none() if manager: logger.info(f"Routing fallback success: Assigned to Manager {manager.id}") return { "assigned_to": manager.id, "status": TicketStatus.ACKNOWLEDGED, "processed_steps": [{"name": "ROUTING", "status": "fallback", "timestamp": datetime.utcnow().isoformat()}], "metadata": { "routing_fallback_assigned": True, "routing_assigned_to": str(manager.id), "routing_reason": "No active agents found, assigned to Workspace Manager." } } return { "processed_steps": [{"name": "ROUTING", "status": "error", "timestamp": datetime.utcnow().isoformat()}], "metadata": { "routing_error": "Critical: No agents or managers found in workspace", "routing_success": False } } # 2. Load Balancing: Count open tickets per agent agent_ids = [a.id for a in agents] stmt = ( select(Ticket.assigned_to, func.count(Ticket.id)) .where( Ticket.assigned_to.in_(agent_ids), Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), Ticket.deleted_at.is_(None) ) .group_by(Ticket.assigned_to) ) result = await db.execute(stmt) workloads = {row[0]: row[1] for row in result.all()} # Fill in zeros for agents with no tickets for aid in agent_ids: if aid not in workloads: workloads[aid] = 0 # 3. Decision Logic: # - If priority is P0/P1, prefer a Lead if available # - Otherwise, pick the agent with the minimum workload leads = [a for a in agents if a.role in [UserRole.SC_LEAD, UserRole.SC_ADMIN]] target_agent = None if priority in ["P0", "P1"] and leads: # Pick least busy lead target_agent = min(leads, key=lambda a: workloads.get(a.id, 0)) reason = f"High priority ({priority}) assigned to least busy Lead" else: # Pick least busy agent target_agent = min(agents, key=lambda a: workloads.get(a.id, 0)) reason = "Assigned to least busy available agent"
return { "assigned_to": target_agent.id, "status": TicketStatus.ACKNOWLEDGED, "processed_steps": [{"name": "ROUTING", "status": "success", "timestamp": datetime.utcnow().isoformat()}], "metadata": { "routing_assigned_to": str(target_agent.id), "routing_success": True, "routing_reason": reason, "routing_workload": workloads.get(target_agent.id, 0) } }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697import reimport loggingfrom typing import List
logger = logging.getLogger(__name__)
# --- PII MASKING CONFIG ---
# Emails: Matches standard user@domain.comEMAIL_PATTERN = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'# Phone Numbers: Basic international and US patternsPHONE_PATTERN = r'(\+\d{1,3}[- ]?)?\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}'# UUIDs: Masking internal system IDsUUID_PATTERN = r'[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}'
# --- PROMPT INJECTION CONFIG ---INJECTION_KEYWORDS = [ "ignore previous instructions", "ignore all instructions", "system prompt", "you are now", "dan mode", "developer mode", "jailbreak"]
def mask_pii(text: str) -> str: """ Recursively masks personal information using high-confidence regex. """ if not text: return text # 1. Mask Emails: u***@d***.com def email_repl(match): email = match.group(0) parts = email.split('@') if len(parts) == 2: return f"{parts[0][0]}***@{parts[1][0]}***.{parts[1].split('.')[-1]}" return "***@***.***" text = re.sub(EMAIL_PATTERN, email_repl, text) # 2. Mask Phone Numbers: (***) ***-**** text = re.sub(PHONE_PATTERN, r"(***) ***-****", text) # 3. Mask UUIDs: ********-****-****-****-************ # We only mask UUIDs if they look like standalone system IDs, not if they are part of a URL # text = re.sub(UUID_PATTERN, "********-****-****-****-************", text) return text
def is_malicious_query(query: str) -> bool: """ Detects potential prompt injection or query manipulation. """ if not query: return False normalized_query = query.lower() for kw in INJECTION_KEYWORDS: if kw in normalized_query: logger.warning(f"Nexus Safety: Potential prompt injection detected: '{kw}'") return True # Check for excessive length if len(query) > 5000: logger.warning("Nexus Safety: Query length exceeds safety limits.") return True return False
def sanitize_output(text: str, is_agent: bool) -> str: """ Final sanitization layer before returning response to client. """ if not text: return "" # Always mask PII for everyone text = mask_pii(text) # If customer, potentially more aggressive masking could go here # Character Guardrail: Block general trivia pivots (e.g., 'Ringelmann Effect', 'Did you know...') trivia_patterns = [ r"(?i)interestingly,", r"(?i)did you know", r"(?i)fun fact", r"(?i)Ringelmann Effect", r"(?i)fact about.*in general" ] for pattern in trivia_patterns: if re.search(pattern, text): # If trivia detected with no underlying data return "I apologize, but I do not have enough specific workspace data to provide a detailed insight on this topic. Please provide a ticket ID or workspace reference." return text1234567891011121314151617181920212223242526272829303132333435363738394041424344from typing import TypedDict, List, Optional, Any, Dict, Annotatedfrom uuid import UUID
def merge_list(current: List[Any], new: List[Any]) -> List[Any]: return (current or []) + (new or [])
def merge_dict(current: Dict[str, Any], new: Dict[str, Any]) -> Dict[str, Any]: _c = current.copy() if current else {} if new: _c.update(new) return _c
class AgentState(TypedDict): """ Shared state for the Customer Portal Agentic Workflow. """ # Source Info ticket_id: UUID workspace_id: UUID thread_id: Optional[UUID] title: str description: str attachments: Optional[List[Any]] # Serialized attachment data (id, filename, ai_caption) # Processed Results category: Optional[str] priority: Optional[str] sentiment: Optional[str] # Duplication Info is_duplicate: bool duplicate_of_id: Optional[UUID] # Generated Outputs assigned_to: Optional[UUID] status: Optional[str] suggested_reply: Optional[str] internal_summary: Optional[str] # Flow Control next_node: Optional[str] errors: Annotated[List[str], merge_list] metadata: Annotated[Dict[str, Any], merge_dict] processed_steps: Annotated[List[Dict[str, Any]], merge_list]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118from typing import Any, Dict, List, Optionalfrom datetime import datetimefrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.runnables import RunnableConfigfrom langchain_core.output_parsers import StrOutputParser # Added import for StrOutputParserfrom uuid import UUID # Added import for UUID
from core.llm import get_llm, get_text_embeddingsfrom agents.state import AgentStatefrom agents.utils import hybrid_search_kb_internal, semantic_search_past_ticketsfrom core.logging import get_loggerfrom models.attachment import Attachmentfrom sqlalchemy import select, func
SUGGESTION_PROMPT = """You are an expert customer support assistant. Your goal is to draft a helpful, professional reply to a customer ticket.
Ticket Title: {title}Ticket Description: {description}
{context}
Based on the above context, draft a response to the customer. - If the context doesn't provide enough information, ask clarifying questions or state that an agent will look into it.- Keep the tone professional and empathetic."""
logger = get_logger(__name__)
async def suggestion_node(state: AgentState, config: RunnableConfig) -> Dict[str, Any]: """ Node that searches KB and past resolutions to draft a suggested reply. """ db = config["configurable"].get("db") if not db: logger.error(f"Suggestion node missing DB session for ticket {state.get('ticket_id')}") return {"errors": ["No database session provided for suggestion"], "next_node": "END"} workspace_id = UUID(state["workspace_id"]) if isinstance(state["workspace_id"], str) else state["workspace_id"] try: # Generate query embedding for search (Nomic-768 by default) logger.debug(f"Suggestion node embedding query for ticket {state['ticket_id']}") query_text = f"{state['title']} {state['description']}" query_vector = await get_text_embeddings().aembed_query(query_text) # 1. Hybrid KB Search + Semantic Past Tickets Search logger.debug(f"Suggestion node searching KB and past tickets for ticket {state['ticket_id']}") kb_hits = await hybrid_search_kb_internal(db, workspace_id, query_text, query_vector, threshold=0.4, limit=3) past_tickets = await semantic_search_past_tickets(db, workspace_id, query_vector, limit=2) # 1.5. Multimodal Context: Search attachment captions att_stmt = ( select(Attachment) .where( Attachment.workspace_id == workspace_id, Attachment.ai_caption.isnot(None), # Using simple LIKE for robustness without full text search index on captions yet (Attachment.ai_caption.contains(state['title']) | Attachment.ai_caption.contains("error")) ) .limit(3) ) matched_atts = (await db.execute(att_stmt)).scalars().all() # 2. Format Context logger.debug(f"Suggestion node formatting context for ticket {state['ticket_id']}") context = "" if kb_hits: context += "Context from Knowledge Base:\n" # Format using article title and content (which might be a chunk now if we wanted, # but for the prompt, we'll use the article as the hit unit). context += "\n".join([f"- {h['article'].title} (Score: {h['score']:.2f}): {h['article'].content}" for h in kb_hits]) else: context += "No relevant KB articles found.\n" if past_tickets: context += "\nSimilar Past Resolutions:\n" context += "\n".join([f"- Past Ticket: {t.title}\n Resolution: {t.description}" for t in past_tickets]) if matched_atts: context += "\nRelevant Visual Context (from KB/Ticket images):\n" context += "\n".join([f"- Image '{a.filename}': {a.ai_caption}" for a in matched_atts]) else: context += "\nNo similar past resolutions or visual context found." # 3. Generate Draft via LLM prompt = ChatPromptTemplate.from_template(SUGGESTION_PROMPT) chain = prompt | get_llm() | StrOutputParser() logger.info(f"Suggestion node generating reply via LLM for ticket {state['ticket_id']}") suggestion = await chain.ainvoke({ "title": state["title"], "description": state["description"], "context": context }) return { "suggested_reply": suggestion, "processed_steps": [{"name": "SUGGESTION", "status": "success", "timestamp": datetime.utcnow().isoformat()}], "metadata": { "suggestion_sources": { "kb_count": len(kb_hits), "past_tickets_count": len(past_tickets), "kb_articles": [ {"id": str(h['article'].id), "title": h['article'].title} for h in kb_hits ] }, "suggestion_success": True } } except Exception as e: logger.error(f"Suggestion node failed for ticket {state['ticket_id']}: {str(e)}") return { "errors": [f"Suggestion failed: {str(e)}"], "processed_steps": [{"name": "SUGGESTION", "status": "error", "timestamp": datetime.utcnow().isoformat()}], "metadata": {"suggestion_success": False} }12345678910111213141516171819202122232425262728293031323334353637383940414243from typing import Any, Dict, Listfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.runnables import RunnableConfigfrom core.llm import get_llm
SUMMARIZER_PROMPT = """Summarize the following support ticket thread into a concise overview.Include:1. The main problem or request.2. Key actions taken so far.3. Current status or pending items.
Ticket Title: {title}Original Description: {description}
Thread Messages:{messages}
Summary:"""
async def summarize_thread(title: str, description: str, messages: List[Dict[str, Any]]) -> str: """ Stand-alone utility to summarize a ticket thread. """ llm = get_llm() # Format messages for prompt formatted_messages = "\n".join([ f"- {m.get('sender_name', 'User')}: {m.get('content')}" for m in messages ]) prompt = ChatPromptTemplate.from_template(SUMMARIZER_PROMPT) chain = prompt | llm response = await chain.ainvoke({ "title": title, "description": description, "messages": formatted_messages or "No messages yet." }) return response.content123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434from typing import Any, Dict, List, Optionalfrom uuid import UUIDfrom datetime import datetimeimport jsonfrom sqlalchemy import select, func, and_, cast, Stringfrom core.database import async_session_factoryfrom models.ticket import Ticket, TicketStatus, TicketPriorityfrom models.kb_article import KBArticlefrom models.kb_article_chunk import KBArticleChunkfrom models.escalation_rule import EscalationRulefrom core.llm import get_text_embeddingsfrom core.logging import get_loggerfrom agents.utils import safe_uuid
logger = get_logger(__name__)
# --- SECURED READ-ONLY TOOLS ---
async def kb_search_tool(query: str, workspace_id: UUID) -> str: """ Search the Knowledge Base for relevant articles and technical solutions. """ async with async_session_factory() as db: embedder = get_text_embeddings() query_vector = await embedder.aembed_query(query) from models.user import User, UserRole # Semantic search on chunks stmt = ( select(KBArticleChunk, KBArticle.title, KBArticle.id) .join(KBArticle, KBArticle.id == KBArticleChunk.article_id) .where( KBArticle.workspace_id == workspace_id, KBArticle.is_published == True, KBArticle.deleted_at.is_(None) ) .order_by(KBArticleChunk.embedding.cosine_distance(query_vector)) .limit(5) ) result = await db.execute(stmt) chunks = result.all() if not chunks: return "No relevant Knowledge Base articles found." formatted_res = [] for chunk, title, article_id in chunks: formatted_res.append(f"### Article: {title} (ID: {article_id})\n{chunk.content}\n") return "\n".join(formatted_res)
async def ticket_query_tool(workspace_id: UUID, ticket_id: Optional[UUID] = None, status_filter: Optional[str] = None, role: str = "customer_user") -> str: """ Retrieve ticket status, AI summaries, and recent activity. Strictly masks internal staff notes for customer roles. """ async with async_session_factory() as db: from models.user import User, UserRole is_staff = "3sc" in role.lower() stmt = select(Ticket).where( Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None) ) if not is_staff: from sqlalchemy.orm import aliased Creator = aliased(User) stmt = stmt.join(Creator, Ticket.created_by == Creator.id).where( Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]) ) if ticket_id: t_id = safe_uuid(ticket_id) if not t_id: return "Invalid Ticket ID format." stmt = stmt.where(Ticket.id == t_id) elif status_filter: # Smart Mapper for friendly terms status_map = { "open": [TicketStatus.OPEN], "acknowledged": [TicketStatus.ACKNOWLEDGED], "pending": [TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED], "active": [TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS], "in_progress": [TicketStatus.IN_PROGRESS], "resolved": [TicketStatus.RESOLVED], "closed": [TicketStatus.CLOSED], "done": [TicketStatus.RESOLVED, TicketStatus.CLOSED], "open/pending": [TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED] } # Normalize and lookup normalized = str(status_filter).lower().strip() target_statuses = status_map.get(normalized, [TicketStatus.OPEN]) # Default to open if unknown stmt = stmt.where(Ticket.status.in_(target_statuses)) else: stmt = stmt.limit(20) # Default list result = await db.execute(stmt) tickets = result.scalars().all() if not tickets: return "No tickets found matching the criteria." is_staff = any(s in role.lower() for s in ["3sc", "agent", "lead", "admin"]) # Standardize: 3sc_agent, 3sc_lead, 3sc_admin are staff. customer_admin, customer_user are NOT. is_staff = "3sc" in role.lower()
res = [] for t in tickets: meta = t.ai_metadata or {} summaries = meta.get("summaries", {}) # STAFF BUBBLE PROTECTION if is_staff: summary = summaries.get("internal_summary") or summaries.get("customer_summary") or "No summary available." else: summary = summaries.get("customer_summary") or "Status active. Detailed internal notes are restricted." res.append( f"TICKET [{t.id}]\nTitle: {t.title}\nStatus: {t.status}\nPriority: {t.priority}\n" f"Summary: {summary}\n" f"Created: {t.created_at.isoformat()}\n---" ) return "\n".join(res)
async def nexus_analytics_tool(workspace_id: UUID, role: str = "customer_user") -> str: """ Fetch workspace metrics: Volume Trends, SLA compliance, and Category Heatmaps. Returns structured data for the agent to generate visualizations. """ async with async_session_factory() as db: from models.user import User, UserRole is_staff = "3sc" in role.lower()
# 1. Status Distribution status_stmt = ( select(Ticket.status, func.count(Ticket.id)) .where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None)) ) if not is_staff: from sqlalchemy.orm import aliased Creator = aliased(User) status_stmt = status_stmt.join(Creator, Ticket.created_by == Creator.id).where( Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]) ) status_stmt = status_stmt.group_by(Ticket.status) # 2. Priority Distribution prio_stmt = ( select(Ticket.priority, func.count(Ticket.id)) .where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None)) ) if not is_staff: from sqlalchemy.orm import aliased Creator = aliased(User) prio_stmt = prio_stmt.join(Creator, Ticket.created_by == Creator.id).where( Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]) ) prio_stmt = prio_stmt.group_by(Ticket.priority)
# 3. Category Distribution cat_stmt = ( select(Ticket.category, func.count(Ticket.id)) .where(Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None)) ) if not is_staff: from sqlalchemy.orm import aliased Creator = aliased(User) cat_stmt = cat_stmt.join(Creator, Ticket.created_by == Creator.id).where( Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]) ) cat_stmt = cat_stmt.group_by(Ticket.category).order_by(func.count(Ticket.id).desc()).limit(10)
# 4. Daily Volume Trends (Last 7 Days) from datetime import timedelta seven_days_ago = datetime.now() - timedelta(days=7) day_expr = cast(func.date(Ticket.created_at), String) trend_stmt = ( select(day_expr, func.count(Ticket.id)) .where( Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None), Ticket.created_at >= seven_days_ago ) ) if not is_staff: from sqlalchemy.orm import aliased Creator = aliased(User) trend_stmt = trend_stmt.join(Creator, Ticket.created_by == Creator.id).where( Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]) ) trend_stmt = trend_stmt.group_by(day_expr).order_by(day_expr) # 5. SLA Compliance from api.v1.reports import get_sla_compliance class MockUser: def __init__(self, ws_id): self.workspace_id = ws_id self.role = UserRole.SC_ADMIN # Ensure MockUser has necessary role for analytics # FIX: Correct argument order (workspace_id, current_user, db) mock_user = MockUser(workspace_id) sla_data = await get_sla_compliance(str(workspace_id), mock_user, db) status_res = await db.execute(status_stmt) prio_res = await db.execute(prio_stmt) cat_res = await db.execute(cat_stmt) trend_res = await db.execute(trend_stmt) stats = { "status_dist": {row[0]: row[1] for row in status_res.all()}, "prio_dist": {row[0]: row[1] for row in prio_res.all()}, "category_dist": {row[0] or "Uncategorized": row[1] for row in cat_res.all()}, "daily_volume": {row[0].split('T')[0]: row[1] for row in trend_res.all()}, "sla": sla_data } return json.dumps(stats, indent=2)
async def similar_incident_finder(query: str, workspace_id: UUID, role: str = "customer_user") -> str: """ Find top 3 similar resolved tickets. Masks internal staff notes for customer roles. """ async with async_session_factory() as db: from models.user import User, UserRole embedder = get_text_embeddings() query_vector = await embedder.aembed_query(query) is_staff = "3sc" in role.lower() stmt = ( select(Ticket) .where( Ticket.workspace_id == workspace_id, Ticket.status.in_([TicketStatus.RESOLVED, TicketStatus.CLOSED]), Ticket.deleted_at.is_(None) ) ) if not is_staff: from sqlalchemy.orm import aliased Creator = aliased(User) stmt = stmt.join(Creator, Ticket.created_by == Creator.id).where( Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]) ) stmt = stmt.order_by(Ticket.embedding.cosine_distance(query_vector)).limit(3) result = await db.execute(stmt) tickets = result.scalars().all() if not tickets: return "No similar resolved tickets found." is_staff = "3sc" in role.lower() res = [] for t in tickets: meta = t.ai_metadata or {} summaries = meta.get("summaries", {}) if is_staff: summ = summaries.get("internal_summary") or summaries.get("customer_summary") or "No summary." else: summ = summaries.get("customer_summary") or "Resolution complete. Internal notes restricted." res.append(f"PAST INCIDENT [{t.id}]\nTitle: {t.title}\nResolution: {summ}\n---") return "\n".join(res)
async def project_pulse_tool(project_name: str, workspace_id: UUID) -> str: """ A birds-eye view of a specific project's health and ticket distribution. """ async with async_session_factory() as db: from models.project import Project # 1. Resolve Project p_stmt = select(Project).where( Project.workspace_id == workspace_id, Project.name.ilike(f"%{project_name}%"), Project.deleted_at.is_(None) ) p_res = await db.execute(p_stmt) project = p_res.scalar_one_or_none() if not project: return f"Project '{project_name}' not found." # 2. Get Distribution stmt = ( select(Ticket.status, func.count(Ticket.id)) .where(Ticket.project_id == project.id, Ticket.deleted_at.is_(None)) .group_by(Ticket.status) ) res = await db.execute(stmt) dist = {row[0]: row[1] for row in res.all()} return json.dumps({"project": project.name, "distribution": dist}, indent=2)
async def sentiment_pulse_tool(ticket_id: UUID, workspace_id: UUID) -> str: """ Retrieve message history for sentiment and pulse analysis. """ async with async_session_factory() as db: from models.message import Message t_id = safe_uuid(ticket_id) if not t_id: return "Invalid Ticket ID." stmt = ( select(Message.content, Message.sender_id, Message.created_at) .where( Message.ticket_id == t_id, Message.workspace_id == workspace_id, Message.is_internal == False, # Only customer-distinguishable messages for sentiment Message.deleted_at.is_(None) ) .order_by(Message.created_at.desc()) .limit(10) ) res = await db.execute(stmt) messages = res.all() if not messages: return "No recent messages found for sentiment analysis." return "\n".join([f"{row[2]} (User {row[1]}): {row[0]}" for row in messages])
async def knowledge_drafting_tool(ticket_id: UUID, workspace_id: UUID) -> str: """ Extract problem and resolution data to draft a KB article. """ async with async_session_factory() as db: t_id = safe_uuid(ticket_id) if not t_id: return "Invalid Ticket ID." stmt = select(Ticket).where( Ticket.id == t_id, Ticket.workspace_id == workspace_id, Ticket.deleted_at.is_(None) ) res = await db.execute(stmt) t = res.scalar_one_or_none() if not t: return "Ticket not found." meta = t.ai_metadata or {} return json.dumps({ "problem": t.description, "category": t.category, "resolution": meta.get("summaries", {}).get("internal_summary") or "Pending resolution." })
async def assign_ticket_tool(ticket_id: UUID, user_id: UUID, workspace_id: UUID) -> str: """ Assign a ticket to a specific agent. """ async with async_session_factory() as db: t_id = safe_uuid(ticket_id) u_id = safe_uuid(user_id) if not t_id or not u_id: return "Invalid Ticket or User ID." stmt = select(Ticket).where(Ticket.id == t_id, Ticket.workspace_id == workspace_id) res = await db.execute(stmt) t = res.scalar_one_or_none() if not t: return "Ticket not found or access denied." t.assigned_to = user_id await db.commit() return f"Ticket {ticket_id} successfully assigned to user {user_id}."
async def update_ticket_status_tool(ticket_id: UUID, new_status: str, workspace_id: UUID) -> str: """ Update a ticket's status (e.g. to RESOLVED). """ async with async_session_factory() as db: t_id = safe_uuid(ticket_id) if not t_id: return "Invalid Ticket ID." stmt = select(Ticket).where(Ticket.id == t_id, Ticket.workspace_id == workspace_id) res = await db.execute(stmt) t = res.scalar_one_or_none() if not t: return "Ticket not found or access denied." try: t.status = TicketStatus(new_status) if t.status == TicketStatus.RESOLVED: from datetime import datetime t.resolved_at = datetime.now() await db.commit() return f"Ticket {ticket_id} status updated to {new_status}." except ValueError: return f"Invalid status: {new_status}. Valid statuses: {[s.value for s in TicketStatus]}"async def dynamic_remediation_tool(action_type: str, parameters: Dict[str, Any], workspace_id: UUID) -> str: """ Intelligent remediation engine. Executes specific system actions with dynamic parameters. Actions: RESET_VPN, RESTART_SERVICE, FLUSH_CACHE, PROVISION_AWS_TEMP """ # In a real system, this would call actual infrastructure APIs # Here we simulate the logic and log the attempt action = action_type.upper() params_str = ", ".join([f"{k}={v}" for k, v in parameters.items()]) logger.info(f"Remediation: Triggering {action} with [{params_str}] for workspace {workspace_id}") # Simulate a delay for infrastructure action await asyncio.sleep(0.5) if action == "RESET_VPN": email = parameters.get("user_email") or parameters.get("email") if not email: return "ERROR: user_email parameter missing for RESET_VPN." return f"SUCCESS: VPN reset successfully for {email}. Password temporary link sent." elif action == "RESTART_SERVICE": svc = parameters.get("service_name") or parameters.get("service_id") if not svc: return "ERROR: service_name missing for RESTART_SERVICE." return f"SUCCESS: Service '{svc}' has been restarted and is now healthy (200 OK)." elif action == "FLUSH_CACHE": region = parameters.get("region", "GLOBAL") return f"SUCCESS: CDN/Cache flush completed for region: {region}." return f"REMEDIATION_TRIGGERED: Action '{action}' initiated with [{params_str}]. Please monitor infrastructure."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102from typing import Any, Dict, List, Optionalfrom datetime import datetimefrom pydantic import BaseModel, Fieldfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.runnables import RunnableConfig
from core.llm import get_llmfrom core.vision import resolve_imagefrom models.attachment import Attachmentfrom agents.state import AgentStatefrom models.ticket import TicketPriorityfrom core.logging import get_logger
logger = get_logger(__name__)
class TriageResult(BaseModel): """Structured output for ticket triage.""" category: str = Field(description="The category of the ticket (e.g., technical, billing, feature_request, general)") priority: TicketPriority = Field(description="Priority level based on urgency and impact") sentiment: str = Field(description="User sentiment (e.g., frustrated, neutral, positive)") estimated_effort_hours: float = Field(description="Estimated technical effort in hours to resolve this ticket (e.g., 0.5, 2, 8, 40)") complexity: str = Field(description="Complexity level: 'low', 'medium', or 'high'") reasoning: str = Field(description="Short explanation for the classification and estimation")
from langchain_core.output_parsers import PydanticOutputParser
TRIAGE_PROMPT = """You are an expert customer support triage agent. Your job is to analyze incoming support tickets and categorize them with high-fidelity effort estimation.
Ticket Title: {title}Ticket Description: {description}Visual Context: {image_captions}
Analyze the content and provide:1. Category and Priority.2. Sentiment of the customer.3. Estimated effort (IN HOURS) required for a human to resolve this issue. Use the following BENCHMARKING RUBRIC to calibrate your score: - LOW COMPLEXITY (0.5 - 1.0h): Password resets, status checks, general queries, simple configuration. - MEDIUM COMPLEXITY (2.0 - 4.0h): Standard bug reports, troubleshooting, Reproducible issues, minor feature tweaks. - HIGH COMPLEXITY (8.0 - 40.0h): System-wide feature requests, data migrations, infrastructure setup, complex integration failures.4. Complexity level (low, medium, high).
Provide the output in the specified JSON format. Ensure the 'estimated_effort_hours' is a float that strictly follows the rubric above.
{format_instructions}"""
from core.logging import get_logger
logger = get_logger(__name__)
async def triage_node(state: AgentState, config: RunnableConfig) -> Dict[str, Any]: """ Node that classifies the ticket and determines sentiment/priority. """ llm = get_llm() parser = PydanticOutputParser(pydantic_object=TriageResult) prompt = ChatPromptTemplate.from_messages([ ("system", TRIAGE_PROMPT) ]) chain = prompt | llm | parser # 1. Format context from state image_captions = [] for attachment in state.get("attachments", []): if attachment.ai_caption: image_captions.append(attachment.ai_caption) # 2. Define Extraction Chain try: logger.debug(f"Triage node starting ainvoke for ticket {state['ticket_id']}") result = await chain.ainvoke({ "title": state["title"], "description": state["description"], "image_captions": "\n".join(image_captions) if image_captions else "No visual evidence provided.", "format_instructions": parser.get_format_instructions() }) logger.debug(f"Triage node completed for ticket {state['ticket_id']}") logger.info(f"TRIAGE: Agent categorized ticket as '{result.category}' with priority '{result.priority}' (Effort: {result.estimated_effort_hours}h)") return { "category": result.category, "priority": result.priority, "sentiment": result.sentiment, "processed_steps": [{"name": "TRIAGE", "status": "success", "timestamp": datetime.utcnow().isoformat()}], "metadata": { "triage_reasoning": result.reasoning, "estimated_effort_hours": result.estimated_effort_hours, "complexity": result.complexity, "triage_success": True } } except Exception as e: logger.error(f"Triage node failed for ticket {state['ticket_id']}: {str(e)}") return { "errors": [f"Triage failed: {str(e)}"], "processed_steps": [{"name": "TRIAGE", "status": "error", "timestamp": datetime.utcnow().isoformat()}], "metadata": {"triage_success": False} }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213from typing import Any, Dict, List, Optionalfrom uuid import UUIDfrom datetime import datetimefrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import select, func, descfrom core.logging import get_loggerfrom models.user import User, UserRolefrom models.kb_article import KBArticlefrom models.kb_article_chunk import KBArticleChunk
logger = get_logger(__name__)
async def get_available_agents(db: AsyncSession, workspace_id: UUID) -> List[User]: """ Fetch all active agents in the given workspace. """ stmt = select(User).where( User.workspace_id == workspace_id, User.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), User.is_active == True, User.deleted_at.is_(None) ) result = await db.execute(stmt) agents = list(result.scalars().all()) logger.debug(f"Fetched {len(agents)} available agents for workspace {workspace_id}") return agents
async def update_ticket_ai_metadata(db: AsyncSession, ticket_id: UUID, metadata: Dict[str, Any]): """ Utility to update ticket AI metadata in the DB. """ from models.ticket import Ticket stmt = select(Ticket).where(Ticket.id == ticket_id) result = await db.execute(stmt) ticket = result.scalar_one_or_none() if ticket: # Merge new metadata existing = ticket.ai_metadata or {} existing.update(metadata) ticket.ai_metadata = existing db.add(ticket)
async def semantic_search_kb(db: AsyncSession, workspace_id: UUID, query_embedding: List[float], limit: int = 3) -> List[Any]: """ Search KBArticles by embedding. """ from models.kb_article import KBArticle stmt = select(KBArticle).where( KBArticle.workspace_id == workspace_id, KBArticle.deleted_at.is_(None), KBArticle.duplicate_of_id.is_(None) ).order_by( KBArticle.embedding.cosine_distance(query_embedding) ).limit(limit) logger.info(f"AI: Semantic search KB for workspace {workspace_id}") result = await db.execute(stmt) return list(result.scalars().all())
async def semantic_search_past_tickets(db: AsyncSession, workspace_id: UUID, query_embedding: List[float], limit: int = 3) -> List[Any]: """ Search resolved Tickets by embedding. """ from models.ticket import Ticket, TicketStatus stmt = select(Ticket).where( Ticket.workspace_id == workspace_id, Ticket.status == TicketStatus.RESOLVED, Ticket.embedding.isnot(None), Ticket.deleted_at.is_(None) ).order_by( Ticket.embedding.cosine_distance(query_embedding) ).limit(limit) logger.info(f"AI: Semantic search past tickets for workspace {workspace_id}") result = await db.execute(stmt) return list(result.scalars().all())
async def hybrid_search_kb_internal( db: AsyncSession, workspace_id: UUID, query_text: str, query_embedding: List[float], threshold: float = 0.2, limit: int = 5) -> List[Dict[str, Any]]: """ Internal utility for hybrid search (FTS + Vector) to be used by AI nodes. Returns a list of dictionaries containing the article object and its hybrid score. """ # 1. Semantic Chunk Search semantic_stmt = ( select( KBArticle, (1 - KBArticleChunk.embedding.cosine_distance(query_embedding)).label("sim_score") ) .join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id) .where( KBArticle.workspace_id == workspace_id, KBArticle.deleted_at.is_(None), KBArticle.is_published == True, KBArticle.duplicate_of_id.is_(None) ) .order_by(desc("sim_score")) .limit(20) ) semantic_res = await db.execute(semantic_stmt) # 2. Keyword FTS Search fts_stmt = ( select( KBArticle, func.ts_rank( func.to_tsvector('english', KBArticle.title + " " + KBArticle.content), func.plainto_tsquery('english', query_text) ).label("fts_rank") ) .where( KBArticle.workspace_id == workspace_id, KBArticle.deleted_at.is_(None), KBArticle.is_published == True, KBArticle.duplicate_of_id.is_(None), func.to_tsvector('english', KBArticle.title + " " + KBArticle.content).op("@@")(func.plainto_tsquery('english', query_text)) ) .order_by(desc("fts_rank")) .limit(20) ) fts_res = await db.execute(fts_stmt)
# 3. Score Fusion article_scores = {} for article, sim in semantic_res.all(): if article.id not in article_scores: article_scores[article.id] = {"obj": article, "semantic": sim, "fts": 0.0} else: article_scores[article.id]["semantic"] = max(article_scores[article.id]["semantic"], sim)
for article, rank in fts_res.all(): if article.id not in article_scores: article_scores[article.id] = {"obj": article, "semantic": 0.0, "fts": rank} else: article_scores[article.id]["fts"] = rank
final_results = [] for art_id, data in article_scores.items(): score = (data["semantic"] * 0.7) + (min(data["fts"], 1.0) * 0.3) if score >= threshold: final_results.append({"article": data["obj"], "score": score})
final_results.sort(key=lambda x: x["score"], reverse=True) return final_results[:limit]
async def get_workspace_manager(db: AsyncSession, workspace_id: UUID) -> Optional[User]: """Find the best person to notify in a workspace (Lead first, then Admin).""" # 1. Try to find a Lead stmt = select(User).where( (User.workspace_id == workspace_id), (User.role == UserRole.SC_LEAD), (User.is_active == True), (User.deleted_at.is_(None)) ).limit(1) res = await db.execute(stmt) manager = res.scalar_one_or_none() if manager: return manager # 2. Fallback to Admin stmt = select(User).where( (User.workspace_id == workspace_id), (User.role == UserRole.SC_ADMIN), (User.is_active == True), (User.deleted_at.is_(None)) ).limit(1) res = await db.execute(stmt) return res.scalar_one_or_none()
import jsonclass CustomEncoder(json.JSONEncoder): """JSON encoder that handles UUID objects by converting them to strings.""" def default(self, obj): if isinstance(obj, UUID): return str(obj) if isinstance(obj, datetime): return obj.isoformat() return super().default(obj)
def sanitize_for_db(data: Any) -> Any: """Recursively converts UUIDs and datetimes to strings for DB storage.""" if isinstance(data, dict): return {k: sanitize_for_db(v) for k, v in data.items()} elif isinstance(data, list): return [sanitize_for_db(i) for i in data] elif isinstance(data, UUID): return str(data) elif isinstance(data, datetime): return data.isoformat() return data
def safe_uuid(val: Any) -> Optional[UUID]: """Safely attempts to cast a value to UUID. Returns None on failure.""" if not val: return None if isinstance(val, UUID): return val try: # Check for common short-codes or hex strings that are not UUIDs s_val = str(val).strip() if len(s_val) < 32: return None return UUID(s_val) except (ValueError, TypeError, AttributeError): return None
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247print("!!! AGENTS-WORKFLOW LOADED: [V_734] !!!")import uuidimport jsonimport loggingimport timefrom typing import Dict, Any, Listfrom datetime import datetime, timedelta
from langgraph.graph import StateGraph, ENDfrom langgraph.types import RetryPolicy
from agents.state import AgentStatefrom agents.triage import triage_nodefrom agents.duplication import duplication_nodefrom agents.remediation import remediation_node, should_continue_remediationfrom agents.routing import routing_nodefrom agents.suggestion import suggestion_nodefrom agents.utils import sanitize_for_db, CustomEncoder, get_workspace_managerfrom core.database import async_session_factoryfrom models.ticket import Ticket, TicketStatusfrom models.attachment import Attachmentfrom sqlalchemy import select
logger = logging.getLogger(__name__)
def should_proceed_after_duplication(state: AgentState) -> str: """Router to exit early if ticket is a duplicate.""" if state.get("is_duplicate"): logger.warning(f"Workflow: Exiting early for duplicate ticket {state['ticket_id']}") return END return "triage"
async def run_ai_workflow(ctx: Any, ticket_data: Dict[str, Any], **kwargs: Any) -> Dict[str, Any]: """ Main entry point to run the agentic workflow for a new ticket. """ thread_id = uuid.uuid4() t_id_raw = ticket_data.get("id") t_id = uuid.UUID(str(t_id_raw)) if t_id_raw else None # Version Tag for Verification v_tag = f"v_{int(time.time() % 1000)}" logger.info(f"TASK START [{v_tag}]: Orchestrating AI for ticket {t_id} (Thread: {thread_id})") final_state = {} try: async with async_session_factory() as db: # 1. Initialize Graph workflow = StateGraph(AgentState) retry_policy = RetryPolicy(max_attempts=3) workflow.add_node("duplication", duplication_node, retry=retry_policy) workflow.add_node("triage", triage_node, retry=retry_policy) workflow.add_node("remediation", remediation_node, retry=retry_policy) workflow.add_node("routing", routing_node, retry=retry_policy) workflow.add_node("suggestion", suggestion_node, retry=retry_policy) workflow.set_entry_point("duplication") workflow.add_conditional_edges( "duplication", should_proceed_after_duplication, {"triage": "triage", END: END} ) workflow.add_edge("triage", "remediation") workflow.add_conditional_edges( "remediation", should_continue_remediation, {"routing": "routing", "suggestion": "suggestion"} ) workflow.add_edge("routing", "suggestion") workflow.add_edge("suggestion", END) app = workflow.compile() # 1.5 Fetch Attachments for state att_stmt = select(Attachment).where(Attachment.ticket_id == t_id) att_res = await db.execute(att_stmt) attachments = att_res.scalars().all() serialized_atts = [ {"id": str(a.id), "filename": a.filename, "ai_caption": a.ai_caption} for a in attachments ]
# 2. Initial State initial_state = AgentState( ticket_id=t_id, workspace_id=uuid.UUID(str(ticket_data["workspace_id"])), thread_id=thread_id, title=ticket_data["title"], description=ticket_data.get("description", ""), attachments=serialized_atts, is_duplicate=False, duplicate_of_id=None, category=None, priority=None, sentiment=None, assigned_to=None, status=None, suggested_reply=None, internal_summary=None, next_node=None, errors=[], metadata={}, processed_steps=[{"name": "SYSTEM:EMBEDDING", "status": "success", "timestamp": datetime.utcnow().isoformat()}] ) from models.ai_interaction import AIInteraction from core.config import get_settings settings = get_settings() final_state = initial_state.copy() # 3. Final Orchestration with Native Reduction try: # We use ainvoke to get the PERFECTLY reduced final state # because manual loops bypass LangGraph's internal reducers. logger.info(f"STARTING AI WORKFLOW [{v_tag}] for ticket {t_id}") # Still use astream for REAL-TIME logging of nodes # but we'll use ainvoke's final result for the hard persistence. async for event in app.astream( initial_state, config={"configurable": {"db": db}}, stream_mode="updates" ): if not event: continue for node_name, updates in event.items(): # Track interactions with the V_734 provenance tag clean_updates = sanitize_for_db(updates) clean_updates["debug_v"] = "V_734" # DEFINTIVE PROOF TAG # Log nodes as they happen for the Dashboard interaction = AIInteraction( workspace_id=initial_state["workspace_id"], ticket_id=t_id, agent_name=node_name, model_info=settings.AI_MODEL, thread_id=thread_id, input_data={"v": v_tag, "msg": "Streaming input..."}, output_data=clean_updates, status="success", duration_ms=sanitize_for_db({"total": 0}), # Latency handled by final sync is_automatic=True, metadata_json=clean_updates.get("metadata", {}) ) db.add(interaction) await db.commit() logger.info(f"NODE COMPLETE [{v_tag}]: {node_name}")
# 4. FINAL REDUCTION: Get the official final state from the graph # Using ainvoke here ensures we don't have to manual-merge anymore. final_state = await app.ainvoke(initial_state, config={"configurable": {"db": db}}) # --- Observability: Record Triage Result --- from core.observability import record_workflow_step await record_workflow_step( db, entity_id=t_id, workspace_id=initial_state["workspace_id"], workflow_type="LIFECYCLE", step_name="AI_TRIAGE_COMPLETE", input_data={"v": v_tag}, output_data={ "next_node": final_state.get("next_node"), "metadata": final_state.get("metadata") }, current_stage="ROUTED_FOR_ACTION" ) # --- Observability: Record Suggestion --- if final_state.get("suggested_reply"): await record_workflow_step( db, entity_id=t_id, workspace_id=initial_state["workspace_id"], workflow_type="LIFECYCLE", step_name="AI_SUGGESTION_GENERATED", output_data={"preview": final_state["suggested_reply"][:100] + "..."}, current_stage="REPLY_DRAFTED" )
await db.commit() logger.info(f"AI WORKFLOW COMPLETE [{v_tag}]: {t_id} -> {final_state.get('next_node')}") stmt = select(Ticket).where(Ticket.id == t_id) res = await db.execute(stmt) ticket = res.scalar_one_or_none() if ticket: logger.info(f"ULTIMATE SYNC [{v_tag}]: Saving reduced state to Ticket {t_id}") # Merge metadata and add processed steps final_meta = final_state.get("metadata", {}) final_meta.update({ "worker_version": v_tag, "sync_type": "ultimate_ainvoke", "processed_steps": final_state.get("processed_steps", []) }) ticket.ai_metadata = final_meta # Core Attributes (with Fallbacks) ticket.category = final_state.get("category") or "general" ticket.priority = final_state.get("priority") or "P3" if final_state.get("assigned_to"): ticket.assigned_to = uuid.UUID(str(final_state.get("assigned_to"))) if final_state.get("is_duplicate"): ticket.status = TicketStatus.CLOSED ticket.duplicate_of_id = final_state.get("duplicate_of_id") ticket.resolved_at = datetime.utcnow() ticket.resolution_text = f"Automated Workflow: This ticket has been marked as a duplicate of ticket #{str(ticket.duplicate_of_id)[:8]}." # Effort & Resolution Date hours = final_meta.get("estimated_effort_hours") or 1.0 ticket.estimated_effort_hours = { "value": float(hours), "complexity": final_meta.get("complexity") or "low" } base_time = ticket.created_at or datetime.utcnow() ticket.expected_resolution_at = base_time + timedelta(hours=hours) db.add(ticket) await db.commit() logger.info(f"DONE [{v_tag}]: Ticket {t_id} is fully synchronized via AINVOKE.") else: logger.error(f"SYNC ERROR [{v_tag}]: Ticket {t_id} not found.")
except Exception as e: logger.exception(f"GRAPH ERROR [{v_tag}]: {str(e)}") err_interaction = AIInteraction( workspace_id=initial_state["workspace_id"], ticket_id=t_id, agent_name="workflow_engine", model_info="system", thread_id=thread_id, input_data={}, output_data=sanitize_for_db({"error": str(e)}), status="error", is_automatic=True ) db.add(err_interaction) await db.commit() raise e
except Exception as e: logger.error(f"CRITICAL WORKFLOW FAILURE [{v_tag}]: {str(e)}") raise e return final_state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115# A generic, single database configuration.
[alembic]# path to migration scripts.# Use forward slashes (/) also on windows to provide an os agnostic pathscript_location = alembic
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s# Uncomment the line below if you want the files to be prepended with date and time# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.# defaults to the current working directory.prepend_sys_path = .
# timezone to use when rendering the date within the migration file# as well as the filename.# If specified, requires the python>=3.9 or backports.zoneinfo library.# Any required deps can installed by adding `alembic[tz]` to the pip requirements# string value is passed to ZoneInfo()# leave blank for localtime# timezone =
# max length of characters to apply to the "slug" field# truncate_slug_length = 40
# set to 'true' to run the environment during# the 'revision' command, regardless of autogenerate# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without# a source .py file to be detected as revisions in the# versions/ directory# sourceless = false
# version location specification; This defaults# to alembic/versions. When using multiple version# directories, initial revisions must be specified with --version-path.# The path separator used here should be the separator specified by "version_path_separator" below.# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
# version path separator; As mentioned above, this is the character used to split# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.# Valid values for version_path_separator are:## version_path_separator = :# version_path_separator = ;# version_path_separator = space# version_path_separator = newlineversion_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# set to 'true' to search source files recursively# in each "version_locations" directory# new in Alembic version 1.10# recursive_version_locations = false
# the output encoding used when revision files# are written from script.py.mako# output_encoding = utf-8
sqlalchemy.url = driver://user:pass@localhost/dbname
[post_write_hooks]# post_write_hooks defines scripts or Python functions that are run# on newly generated revision scripts. See the documentation for further# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint# hooks = black# black.type = console_scripts# black.entrypoint = black# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary# hooks = ruff# ruff.type = exec# ruff.executable = %(here)s/.venv/bin/ruff# ruff.options = --fix REVISION_SCRIPT_FILENAME
# Logging configuration[loggers]keys = root,sqlalchemy,alembic
[handlers]keys = console
[formatters]keys = generic
[logger_root]level = WARNhandlers = consolequalname =
[logger_sqlalchemy]level = WARNhandlers =qualname = sqlalchemy.engine
[logger_alembic]level = INFOhandlers =qualname = alembic
[handler_console]class = StreamHandlerargs = (sys.stderr,)level = NOTSETformatter = generic
[formatter_generic]format = %(levelname)-5.5s [%(name)s] %(message)sdatefmt = %H:%M:%S1Generic single-database configuration with an async dbapi.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import asyncioimport pgvectorfrom logging.config import fileConfig
from sqlalchemy import poolfrom sqlalchemy.engine import Connectionfrom sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# this is the Alembic Config object, which provides# access to the values within the .ini file in use.config = context.config
# Interpret the config file for Python logging.# This line sets up loggers basically.if config.config_file_name is not None: fileConfig(config.config_file_name)
from core.database import Basefrom core.config import get_settingsfrom models.workspace import Workspacefrom models.user import Userfrom models.ticket import Ticketfrom models.message import Messagefrom models.project import Projectfrom models.attachment import Attachmentfrom models.feedback import Feedbackfrom models.kb_article import KBArticlefrom models.kb_article_chunk import KBArticleChunkfrom models.notification import Notificationfrom models.escalation_rule import EscalationRulefrom models.remediation import RemediationHookfrom models.ai_interaction import AIInteractionfrom models.ai_workflow import AIWorkflowfrom models.audit_log import AuditLogfrom models.nexus_checkpoint import NexusCheckpointfrom models.nexus_interaction import NexusInteractionfrom models.remediation import RemediationHookfrom models.remediation_audit import RemediationAudit
target_metadata = Base.metadatasettings = get_settings()
# other values from the config, defined by the needs of env.py,# can be acquired:# my_important_option = config.get_main_option("my_important_option")# ... etc.
def run_migrations_offline() -> None: """Run migrations in 'offline' mode.
This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the script output.
""" url = config.get_main_option("sqlalchemy.url") context.configure( url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, )
with context.begin_transaction(): context.run_migrations()
def do_run_migrations(connection: Connection) -> None: context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction(): context.run_migrations()
async def run_async_migrations() -> None: """In this scenario we need to create an Engine and associate a connection with the context.
"""
connectable = async_engine_from_config( config.get_section(config.config_ini_section, {}), prefix="sqlalchemy.", poolclass=pool.NullPool, )
async with connectable.connect() as connection: await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None: """Run migrations in 'online' mode.""" # Escape % as %% to prevent ConfigParser interpolation errors escaped_url = settings.async_database_url.replace("%", "%%") config.set_main_option("sqlalchemy.url", escaped_url) asyncio.run(run_async_migrations())
if context.is_offline_mode(): run_migrations_offline()else: run_migrations_online()1234567891011121314151617181920212223242526"""${message}
Revision ID: ${up_revision}Revises: ${down_revision | comma,n}Create Date: ${create_date}
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa${imports if imports else ""}
# revision identifiers, used by Alembic.revision: str = ${repr(up_revision)}down_revision: Union[str, None] = ${repr(down_revision)}branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None: ${upgrades if upgrades else "pass"}
def downgrade() -> None: ${downgrades if downgrades else "pass"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365"""initial_consolidated
Revision ID: 0001_initial_consolidatedRevises: Create Date: 2026-03-31 11:00:00.000000
"""from typing import Sequence, Unionfrom alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresqlimport pgvector
# revision identifiersrevision: str = '0001_initial_consolidated'down_revision: Union[str, None] = Nonebranch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # 1. Enable extensions op.execute("CREATE EXTENSION IF NOT EXISTS vector")
# 2. Define Enums with safety checks (Postgres DO blocks) op.execute(""" DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'userrole') THEN CREATE TYPE userrole AS ENUM ('CUSTOMER_ADMIN', 'CUSTOMER_USER', 'SC_AGENT', 'SC_LEAD', 'SC_ADMIN'); END IF; IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'ticketpriority') THEN CREATE TYPE ticketpriority AS ENUM ('P0', 'P1', 'P2', 'P3'); END IF; IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'ticketstatus') THEN CREATE TYPE ticketstatus AS ENUM ('OPEN', 'ACKNOWLEDGED', 'IN_PROGRESS', 'RESOLVED', 'CLOSED'); END IF; END $$; """)
# Enum objects with create_type=False to tell SQLAlchemy NOT to attempt creation during create_table userrole_enum = postgresql.ENUM('CUSTOMER_ADMIN', 'CUSTOMER_USER', 'SC_AGENT', 'SC_LEAD', 'SC_ADMIN', name='userrole', create_type=False) ticketpriority_enum = postgresql.ENUM('P0', 'P1', 'P2', 'P3', name='ticketpriority', create_type=False) ticketstatus_enum = postgresql.ENUM('OPEN', 'ACKNOWLEDGED', 'IN_PROGRESS', 'RESOLVED', 'CLOSED', name='ticketstatus', create_type=False)
# 3. Tables op.create_table('workspaces', sa.Column('id', sa.UUID(), nullable=False), sa.Column('name', sa.String(length=255), nullable=False), sa.Column('branding', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('deleted_by_id', sa.UUID(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('id') )
op.create_table('users', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('email', sa.String(length=255), nullable=False), sa.Column('hashed_password', sa.String(length=255), nullable=False), sa.Column('full_name', sa.String(length=255), nullable=False), sa.Column('role', userrole_enum, nullable=False), sa.Column('is_active', sa.Boolean(), nullable=False, default=True), sa.Column('avatar_url', sa.String(length=512), nullable=True), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('deleted_by_id', sa.UUID(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email') )
op.create_table('projects', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('name', sa.String(length=255), nullable=False), sa.Column('description', sa.Text(), nullable=True), sa.Column('status', sa.String(length=50), nullable=True), sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('deleted_by_id', sa.UUID(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), sa.PrimaryKeyConstraint('id') )
op.create_table('tickets', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('created_by', sa.UUID(), nullable=False), sa.Column('assigned_to', sa.UUID(), nullable=True), sa.Column('project_id', sa.UUID(), nullable=True), sa.Column('title', sa.String(length=500), nullable=False), sa.Column('description', sa.Text(), nullable=False), sa.Column('category', sa.String(length=100), nullable=True), sa.Column('priority', ticketpriority_enum, nullable=False), sa.Column('status', ticketstatus_enum, nullable=False), sa.Column('sla_deadline', sa.DateTime(), nullable=True), sa.Column('estimated_effort_hours', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('expected_resolution_at', sa.DateTime(), nullable=True), sa.Column('resolved_at', sa.DateTime(), nullable=True), sa.Column('is_escalated', sa.DateTime(), nullable=True), sa.Column('duplicate_of_id', sa.UUID(), nullable=True), sa.Column('resolution_text', sa.Text(), nullable=True), sa.Column('resolved_by', sa.UUID(), nullable=True), sa.Column('embedding', pgvector.sqlalchemy.Vector(dim=768), nullable=True), sa.Column('ai_metadata', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('deleted_by_id', sa.UUID(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['assigned_to'], ['users.id']), sa.ForeignKeyConstraint(['created_by'], ['users.id']), sa.ForeignKeyConstraint(['duplicate_of_id'], ['tickets.id']), sa.ForeignKeyConstraint(['project_id'], ['projects.id']), sa.ForeignKeyConstraint(['resolved_by'], ['users.id']), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), sa.PrimaryKeyConstraint('id') )
op.create_table('kb_articles', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('author_id', sa.UUID(), nullable=False), sa.Column('project_id', sa.UUID(), nullable=True), sa.Column('title', sa.String(length=500), nullable=False), sa.Column('content', sa.Text(), nullable=False), sa.Column('summary', sa.Text(), nullable=True), sa.Column('category', sa.String(length=100), nullable=True), sa.Column('is_published', sa.Boolean(), nullable=True, default=True), sa.Column('embedding', pgvector.sqlalchemy.Vector(dim=768), nullable=True), sa.Column('views', sa.Integer(), nullable=True, default=0), sa.Column('tags', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('duplicate_of_id', sa.UUID(), nullable=True), sa.Column('force_original', sa.Boolean(), nullable=True, default=False), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('deleted_by_id', sa.UUID(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['author_id'], ['users.id']), sa.ForeignKeyConstraint(['duplicate_of_id'], ['kb_articles.id']), sa.ForeignKeyConstraint(['project_id'], ['projects.id']), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), sa.PrimaryKeyConstraint('id') )
op.create_table('kb_article_chunks', sa.Column('id', sa.UUID(), nullable=False), sa.Column('article_id', sa.UUID(), nullable=False), sa.Column('content', sa.Text(), nullable=False), sa.Column('chunk_index', sa.Integer(), nullable=False), sa.Column('embedding', pgvector.sqlalchemy.Vector(dim=768), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['article_id'], ['kb_articles.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id') )
op.create_table('notifications', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('user_id', sa.UUID(), nullable=False), sa.Column('title', sa.String(length=255), nullable=False), sa.Column('message', sa.Text(), nullable=False), sa.Column('is_read', sa.Boolean(), nullable=True, default=False), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['user_id'], ['users.id']), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), sa.PrimaryKeyConstraint('id') )
op.create_table('messages', sa.Column('id', sa.UUID(), nullable=False), sa.Column('ticket_id', sa.UUID(), nullable=False), sa.Column('sender_id', sa.UUID(), nullable=False), sa.Column('content', sa.Text(), nullable=False), sa.Column('is_internal', sa.Boolean(), nullable=False, default=False), sa.Column('mentions', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['sender_id'], ['users.id']), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id']), sa.PrimaryKeyConstraint('id') )
op.create_table('attachments', sa.Column('id', sa.UUID(), nullable=False), sa.Column('ticket_id', sa.UUID(), nullable=True), sa.Column('article_id', sa.UUID(), nullable=True), sa.Column('file_name', sa.String(length=500), nullable=False), sa.Column('file_url', sa.String(length=1024), nullable=False), sa.Column('source_url', sa.String(length=2048), nullable=True), sa.Column('content_type', sa.String(length=100), nullable=True), sa.Column('file_size', sa.String(length=50), nullable=True), sa.Column('storage_backend', sa.String(length=20), nullable=True), sa.Column('embedding', pgvector.sqlalchemy.Vector(dim=512), nullable=True), sa.Column('ai_caption', sa.Text(), nullable=True), sa.Column('is_processed', sa.Boolean(), nullable=True, default=False), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['article_id'], ['kb_articles.id']), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id']), sa.PrimaryKeyConstraint('id') )
op.create_table('feedbacks', sa.Column('id', sa.UUID(), nullable=False), sa.Column('ticket_id', sa.UUID(), nullable=False), sa.Column('csat_score', sa.Integer(), nullable=False), sa.Column('comment', sa.Text(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.CheckConstraint('csat_score >= 1 AND csat_score <= 5', name='csat_score_range'), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id']), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('ticket_id') )
op.create_table('audit_logs', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('entity_type', sa.String(length=50), nullable=False), sa.Column('entity_id', sa.UUID(), nullable=False), sa.Column('action', sa.String(length=100), nullable=False), sa.Column('user_id', sa.UUID(), nullable=True), sa.Column('old_value', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('new_value', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['user_id'], ['users.id']), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), sa.PrimaryKeyConstraint('id') )
op.create_table('ai_workflows', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('entity_id', sa.UUID(), nullable=False), sa.Column('workflow_type', sa.String(length=50), nullable=False), sa.Column('current_stage', sa.String(length=100), nullable=True), sa.Column('steps', postgresql.JSONB(astext_type=sa.Text()), nullable=False), sa.Column('total_duration_ms', sa.Float(), nullable=True), sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), sa.PrimaryKeyConstraint('id') )
op.create_table('ai_interactions', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('ticket_id', sa.UUID(), nullable=True), sa.Column('agent_name', sa.String(length=100), nullable=False), sa.Column('model_info', sa.String(length=255), nullable=True), sa.Column('thread_id', sa.UUID(), nullable=True), sa.Column('input_data', postgresql.JSONB(astext_type=sa.Text()), nullable=False), sa.Column('output_data', postgresql.JSONB(astext_type=sa.Text()), nullable=False), sa.Column('status', sa.String(length=50), nullable=True), sa.Column('duration_ms', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('usage_metadata', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('is_automatic', sa.Boolean(), nullable=True), sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id']), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), sa.PrimaryKeyConstraint('id') )
op.create_table('escalation_rules', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('name', sa.String(length=255), nullable=False), sa.Column('conditions', postgresql.JSONB(astext_type=sa.Text()), nullable=False), sa.Column('actions', postgresql.JSONB(astext_type=sa.Text()), nullable=False), sa.Column('is_active', sa.Boolean(), nullable=True, default=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), sa.PrimaryKeyConstraint('id') )
op.create_table('remediation_hooks', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('trigger_category', sa.String(length=100), nullable=False), sa.Column('action_type', sa.String(length=50), nullable=False), sa.Column('target', sa.String(length=512), nullable=True), sa.Column('payload_template', sa.JSON(), nullable=True), sa.Column('description', sa.String(length=255), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), sa.PrimaryKeyConstraint('id') )
op.create_table('remediation_audits', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('ticket_id', sa.UUID(), nullable=True), sa.Column('user_id', sa.UUID(), nullable=True), sa.Column('action_type', sa.String(length=100), nullable=False), sa.Column('parameters', postgresql.JSONB(astext_type=sa.Text()), nullable=False), sa.Column('reasoning', sa.Text(), nullable=True), sa.Column('is_successful', sa.Boolean(), nullable=True), sa.Column('execution_log', sa.Text(), nullable=True), sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id']), sa.ForeignKeyConstraint(['user_id'], ['users.id']), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), sa.PrimaryKeyConstraint('id') )
op.create_table('nexus_checkpoints', sa.Column('thread_id', sa.String(), nullable=False), sa.Column('checkpoint_id', sa.String(), nullable=False), sa.Column('parent_id', sa.String(), nullable=True), sa.Column('checkpoint_data', sa.LargeBinary(), nullable=False), sa.Column('metadata_data', sa.LargeBinary(), nullable=True), sa.PrimaryKeyConstraint('thread_id', 'checkpoint_id') )
op.create_table('nexus_interactions', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('user_id', sa.UUID(), nullable=False), sa.Column('thread_id', sa.UUID(), nullable=True), sa.Column('ticket_id', sa.UUID(), nullable=True), sa.Column('input_query', sa.Text(), nullable=False), sa.Column('ai_answer', sa.Text(), nullable=False), sa.Column('tool_trace', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('extracted_params', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('status', sa.String(length=50), nullable=True), sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id']), sa.ForeignKeyConstraint(['user_id'], ['users.id']), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id']), sa.PrimaryKeyConstraint('id') )
def downgrade() -> None: # Cleanup in reverse order tables = [ 'nexus_interactions', 'nexus_checkpoints', 'remediation_audits', 'remediation_hooks', 'escalation_rules', 'ai_interactions', 'ai_workflows', 'audit_logs', 'feedbacks', 'attachments', 'messages', 'notifications', 'kb_article_chunks', 'kb_articles', 'tickets', 'projects', 'users', 'workspaces' ] for table in tables: op.drop_table(table) # Drop Enums op.execute("DROP TYPE userrole") op.execute("DROP TYPE ticketpriority") op.execute("DROP TYPE ticketstatus")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""fix_attachments_schema
Revision ID: 0002_fix_attachments_schemaRevises: 0001_initial_consolidatedCreate Date: 2026-03-31 22:40:00.000000
"""from typing import Sequence, Unionfrom alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresql
# revision identifiersrevision: str = '0002_fix_attachments_schema'down_revision: Union[str, None] = '0001_initial_consolidated'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # 1. Add workspace_id column (nullable first to avoid constraint issues with data) op.add_column('attachments', sa.Column('workspace_id', sa.UUID(), nullable=True)) op.create_foreign_key('fk_attachments_workspace_id', 'attachments', 'workspaces', ['workspace_id'], ['id']) # 2. Add uploader_id column op.add_column('attachments', sa.Column('uploader_id', sa.UUID(), nullable=True)) op.create_foreign_key('fk_attachments_uploader_id', 'attachments', 'users', ['uploader_id'], ['id'])
# 3. Rename columns to match current model op.alter_column('attachments', 'file_name', new_column_name='filename') op.alter_column('attachments', 'file_url', new_column_name='storage_path')
# 4. Change file_size from String to Integer (preserving data via casting) op.execute("ALTER TABLE attachments ALTER COLUMN file_size TYPE INTEGER USING (CASE WHEN file_size ~ E'^\\\\d+$' THEN file_size::INTEGER ELSE NULL END)")
# 5. Populate workspace_id if table is not empty (Backfill with first workspace if needed) op.execute(""" UPDATE attachments SET workspace_id = (SELECT id FROM workspaces LIMIT 1) WHERE workspace_id IS NULL AND (SELECT COUNT(*) FROM workspaces) > 0 """)
def downgrade() -> None: # Reverse renames op.alter_column('attachments', 'filename', new_column_name='file_name') op.alter_column('attachments', 'storage_path', new_column_name='file_url') # Change file_size back to String op.alter_column('attachments', 'file_size', type_=sa.String(length=50)) # Remove columns and FKs op.drop_constraint('fk_attachments_uploader_id', 'attachments', type_='foreignkey') op.drop_column('attachments', 'uploader_id') op.drop_constraint('fk_attachments_workspace_id', 'attachments', type_='foreignkey') op.drop_column('attachments', 'workspace_id')12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""final_schema_reconciliation
Revision ID: 0003_final_schema_reconciliationRevises: 0002_fix_attachments_schemaCreate Date: 2026-03-31 23:05:00.000000
"""from typing import Sequence, Unionfrom alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.revision: str = '0003_final_schema_reconciliation'down_revision: Union[str, None] = '0002_fix_attachments_schema'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # 1. ATTACHMENTS - Fix Soft Delete and Indices (Protected by IF NOT EXISTS) op.execute("ALTER TABLE attachments ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMP WITHOUT TIME ZONE") op.execute("ALTER TABLE attachments ADD COLUMN IF NOT EXISTS deleted_by_id UUID") op.execute("CREATE INDEX IF NOT EXISTS ix_attachments_workspace_id ON attachments (workspace_id)") op.execute("CREATE INDEX IF NOT EXISTS ix_attachments_ticket_id ON attachments (ticket_id)") op.execute("CREATE INDEX IF NOT EXISTS ix_attachments_article_id ON attachments (article_id)") # 2. MESSAGES - Add missing Workspace ID and Soft Delete op.execute("ALTER TABLE messages ADD COLUMN IF NOT EXISTS workspace_id UUID") op.execute("ALTER TABLE messages ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMP WITHOUT TIME ZONE") op.execute("ALTER TABLE messages ADD COLUMN IF NOT EXISTS deleted_by_id UUID") # Backfill workspace_id for messages op.execute(""" UPDATE messages SET workspace_id = (SELECT workspace_id FROM tickets WHERE tickets.id = messages.ticket_id) WHERE workspace_id IS NULL AND EXISTS (SELECT 1 FROM tickets WHERE tickets.id = messages.ticket_id) """) op.execute("DO $$ BEGIN BEGIN ALTER TABLE messages ALTER COLUMN workspace_id SET NOT NULL; EXCEPTION WHEN OTHERS THEN NULL; END; END $$;") op.execute("CREATE INDEX IF NOT EXISTS ix_messages_workspace_id ON messages (workspace_id)")
# 3. FEEDBACKS - Align with modern model op.execute("ALTER TABLE feedbacks ADD COLUMN IF NOT EXISTS workspace_id UUID") op.execute("ALTER TABLE feedbacks ADD COLUMN IF NOT EXISTS user_id UUID") op.execute("ALTER TABLE feedbacks ADD COLUMN IF NOT EXISTS rating INTEGER") op.execute("DO $$ BEGIN IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'feedbacks' AND column_name = 'csat_score') THEN UPDATE feedbacks SET rating = csat_score WHERE rating IS NULL; ALTER TABLE feedbacks DROP COLUMN csat_score; END IF; END $$;") op.execute(""" UPDATE feedbacks SET workspace_id = (SELECT workspace_id FROM tickets WHERE tickets.id = feedbacks.ticket_id) WHERE workspace_id IS NULL AND EXISTS (SELECT 1 FROM workspaces) """) op.execute("DO $$ BEGIN BEGIN ALTER TABLE feedbacks ALTER COLUMN workspace_id SET NOT NULL; EXCEPTION WHEN OTHERS THEN NULL; END; END $$;")
# 4. ESCALATION RULES - Repair missing logic op.execute("ALTER TABLE escalation_rules ADD COLUMN IF NOT EXISTS priority_level VARCHAR(50)") op.execute("ALTER TABLE escalation_rules ADD COLUMN IF NOT EXISTS threshold_minutes INTEGER") op.execute("ALTER TABLE escalation_rules ADD COLUMN IF NOT EXISTS action VARCHAR(50)") # 5. REMEDIATION AUDITS - New Agentic Table op.execute(""" CREATE TABLE IF NOT EXISTS remediation_audits ( id UUID PRIMARY KEY, workspace_id UUID NOT NULL REFERENCES workspaces(id), ticket_id UUID REFERENCES tickets(id), user_id UUID REFERENCES users(id), action_type VARCHAR(100) NOT NULL, parameters JSONB NOT NULL, reasoning TEXT, is_successful BOOLEAN DEFAULT TRUE, execution_log TEXT, metadata_json JSONB DEFAULT '{}', created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL, updated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL ) """) op.execute("CREATE INDEX IF NOT EXISTS ix_remediation_audits_workspace_id ON remediation_audits (workspace_id)")
# 6. Global Index Hardening op.execute("CREATE INDEX IF NOT EXISTS ix_kb_article_chunks_article_id ON kb_article_chunks (article_id)") op.execute("CREATE INDEX IF NOT EXISTS ix_kb_articles_workspace_id ON kb_articles (workspace_id)") op.execute("CREATE INDEX IF NOT EXISTS ix_audit_logs_workspace_id ON audit_logs (workspace_id)") op.execute("CREATE INDEX IF NOT EXISTS ix_audit_logs_entity_id ON audit_logs (entity_id)") op.execute("CREATE INDEX IF NOT EXISTS ix_tickets_workspace_id ON tickets (workspace_id)") op.execute("CREATE INDEX IF NOT EXISTS ix_users_workspace_id ON users (workspace_id)")
def downgrade() -> None: pass1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Add meta_infra_health table
Revision ID: 4c626672022aRevises: 0003_final_schema_reconciliationCreate Date: 2026-04-01 01:36:31.807775
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.revision: str = '4c626672022a'down_revision: Union[str, None] = '0003_final_schema_reconciliation'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.create_table('meta_infra_health', sa.Column('service_name', sa.String(length=50), nullable=False), sa.Column('status', sa.Enum('UP', 'DOWN', 'DEGRADED', name='servicestatus'), nullable=False), sa.Column('latency_ms', sa.Float(), nullable=True), sa.Column('metrics', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('environment', sa.String(length=50), nullable=True), sa.Column('id', sa.UUID(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_meta_infra_health_id'), 'meta_infra_health', ['id'], unique=False) op.create_index(op.f('ix_meta_infra_health_service_name'), 'meta_infra_health', ['service_name'], unique=False) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_meta_infra_health_service_name'), table_name='meta_infra_health') op.drop_index(op.f('ix_meta_infra_health_id'), table_name='meta_infra_health') op.drop_table('meta_infra_health') # ### end Alembic commands ###123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112"""Add resolution fields to Ticket
Revision ID: 0b3641c15213Revises: b2895ed533fcCreate Date: 2026-03-30 01:30:34.190948
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.revision: str = '0b3641c15213'down_revision: Union[str, None] = 'b2895ed533fc'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### # Safety Check: Only drop if tables exist (crucial for fresh cloud deployments) from sqlalchemy.engine.reflection import Inspector bind = op.get_bind() inspector = Inspector.from_engine(bind) tables = inspector.get_table_names() if 'nexus_checkpoints' in tables: op.drop_table('nexus_checkpoints') if 'nexus_interactions' in tables: op.drop_index('ix_nexus_interactions_id', table_name='nexus_interactions') op.drop_index('ix_nexus_interactions_thread_id', table_name='nexus_interactions') op.drop_index('ix_nexus_interactions_ticket_id', table_name='nexus_interactions') op.drop_index('ix_nexus_interactions_user_id', table_name='nexus_interactions') op.drop_index('ix_nexus_interactions_workspace_id', table_name='nexus_interactions') op.drop_table('nexus_interactions') if 'remediation_audits' in tables: op.drop_index('ix_remediation_audits_id', table_name='remediation_audits') op.drop_index('ix_remediation_audits_ticket_id', table_name='remediation_audits') op.drop_index('ix_remediation_audits_user_id', table_name='remediation_audits') op.drop_index('ix_remediation_audits_workspace_id', table_name='remediation_audits') op.drop_table('remediation_audits') op.add_column('tickets', sa.Column('resolution_text', sa.Text(), nullable=True)) op.add_column('tickets', sa.Column('resolved_by', sa.UUID(), nullable=True)) op.create_foreign_key(None, 'tickets', 'users', ['resolved_by'], ['id']) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'tickets', type_='foreignkey') op.drop_column('tickets', 'resolved_by') op.drop_column('tickets', 'resolution_text') op.create_table('remediation_audits', sa.Column('workspace_id', sa.UUID(), autoincrement=False, nullable=False), sa.Column('ticket_id', sa.UUID(), autoincrement=False, nullable=True), sa.Column('user_id', sa.UUID(), autoincrement=False, nullable=True), sa.Column('action_type', sa.VARCHAR(length=100), autoincrement=False, nullable=False), sa.Column('parameters', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False, nullable=False), sa.Column('reasoning', sa.TEXT(), autoincrement=False, nullable=True), sa.Column('is_successful', sa.BOOLEAN(), autoincrement=False, nullable=True), sa.Column('execution_log', sa.TEXT(), autoincrement=False, nullable=True), sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False, nullable=True), sa.Column('id', sa.UUID(), autoincrement=False, nullable=False), sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False), sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], name='remediation_audits_ticket_id_fkey'), sa.ForeignKeyConstraint(['user_id'], ['users.id'], name='remediation_audits_user_id_fkey'), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], name='remediation_audits_workspace_id_fkey'), sa.PrimaryKeyConstraint('id', name='remediation_audits_pkey') ) op.create_index('ix_remediation_audits_workspace_id', 'remediation_audits', ['workspace_id'], unique=False) op.create_index('ix_remediation_audits_user_id', 'remediation_audits', ['user_id'], unique=False) op.create_index('ix_remediation_audits_ticket_id', 'remediation_audits', ['ticket_id'], unique=False) op.create_index('ix_remediation_audits_id', 'remediation_audits', ['id'], unique=False) op.create_table('nexus_interactions', sa.Column('workspace_id', sa.UUID(), autoincrement=False, nullable=False), sa.Column('user_id', sa.UUID(), autoincrement=False, nullable=False), sa.Column('thread_id', sa.UUID(), autoincrement=False, nullable=False), sa.Column('ticket_id', sa.UUID(), autoincrement=False, nullable=True), sa.Column('input_query', sa.TEXT(), autoincrement=False, nullable=False), sa.Column('ai_answer', sa.TEXT(), autoincrement=False, nullable=False), sa.Column('tool_trace', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False, nullable=True), sa.Column('extracted_params', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False, nullable=True), sa.Column('status', sa.VARCHAR(length=50), autoincrement=False, nullable=True), sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False, nullable=True), sa.Column('id', sa.UUID(), autoincrement=False, nullable=False), sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False), sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], name='nexus_interactions_ticket_id_fkey'), sa.ForeignKeyConstraint(['user_id'], ['users.id'], name='nexus_interactions_user_id_fkey'), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], name='nexus_interactions_workspace_id_fkey'), sa.PrimaryKeyConstraint('id', name='nexus_interactions_pkey') ) op.create_index('ix_nexus_interactions_workspace_id', 'nexus_interactions', ['workspace_id'], unique=False) op.create_index('ix_nexus_interactions_user_id', 'nexus_interactions', ['user_id'], unique=False) op.create_index('ix_nexus_interactions_ticket_id', 'nexus_interactions', ['ticket_id'], unique=False) op.create_index('ix_nexus_interactions_thread_id', 'nexus_interactions', ['thread_id'], unique=False) op.create_index('ix_nexus_interactions_id', 'nexus_interactions', ['id'], unique=False) op.create_table('nexus_checkpoints', sa.Column('thread_id', sa.VARCHAR(), autoincrement=False, nullable=False), sa.Column('checkpoint_id', sa.VARCHAR(), autoincrement=False, nullable=False), sa.Column('parent_id', sa.VARCHAR(), autoincrement=False, nullable=True), sa.Column('checkpoint_data', postgresql.BYTEA(), autoincrement=False, nullable=False), sa.Column('metadata_data', postgresql.BYTEA(), autoincrement=False, nullable=True), sa.PrimaryKeyConstraint('thread_id', 'checkpoint_id', name='nexus_checkpoints_pkey') ) # ### end Alembic commands ###12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""Add nexus agent tables
Revision ID: 175b693efa2cRevises: 0b3641c15213Create Date: 2026-03-30 03:59:34.342956
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.revision: str = '175b693efa2c'down_revision: Union[str, None] = '0b3641c15213'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.create_table('nexus_checkpoints', sa.Column('thread_id', sa.String(), nullable=False), sa.Column('checkpoint_id', sa.String(), nullable=False), sa.Column('parent_id', sa.String(), nullable=True), sa.Column('checkpoint_data', sa.LargeBinary(), nullable=False), sa.Column('metadata_data', sa.LargeBinary(), nullable=True), sa.PrimaryKeyConstraint('thread_id', 'checkpoint_id') ) op.create_table('nexus_interactions', sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('user_id', sa.UUID(), nullable=False), sa.Column('thread_id', sa.UUID(), nullable=False), sa.Column('ticket_id', sa.UUID(), nullable=True), sa.Column('input_query', sa.Text(), nullable=False), sa.Column('ai_answer', sa.Text(), nullable=False), sa.Column('tool_trace', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('extracted_params', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('status', sa.String(length=50), nullable=True), sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('id', sa.UUID(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], ), sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_nexus_interactions_id'), 'nexus_interactions', ['id'], unique=False) op.create_index(op.f('ix_nexus_interactions_thread_id'), 'nexus_interactions', ['thread_id'], unique=False) op.create_index(op.f('ix_nexus_interactions_ticket_id'), 'nexus_interactions', ['ticket_id'], unique=False) op.create_index(op.f('ix_nexus_interactions_user_id'), 'nexus_interactions', ['user_id'], unique=False) op.create_index(op.f('ix_nexus_interactions_workspace_id'), 'nexus_interactions', ['workspace_id'], unique=False) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_nexus_interactions_workspace_id'), table_name='nexus_interactions') op.drop_index(op.f('ix_nexus_interactions_user_id'), table_name='nexus_interactions') op.drop_index(op.f('ix_nexus_interactions_ticket_id'), table_name='nexus_interactions') op.drop_index(op.f('ix_nexus_interactions_thread_id'), table_name='nexus_interactions') op.drop_index(op.f('ix_nexus_interactions_id'), table_name='nexus_interactions') op.drop_table('nexus_interactions') op.drop_table('nexus_checkpoints') # ### end Alembic commands ###123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""Initial migration
Revision ID: 263c3f7b1819Revises: Create Date: 2026-03-27 19:02:15.019091
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.revision: str = '263c3f7b1819'down_revision: Union[str, None] = Nonebranch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.create_table('workspaces', sa.Column('name', sa.String(length=255), nullable=False), sa.Column('branding_config', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('id', sa.UUID(), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_workspaces_id'), 'workspaces', ['id'], unique=False) op.create_table('projects', sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('name', sa.String(length=255), nullable=False), sa.Column('description', sa.Text(), nullable=True), sa.Column('status', sa.String(length=50), nullable=True), sa.Column('milestones', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('id', sa.UUID(), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_projects_id'), 'projects', ['id'], unique=False) op.create_index(op.f('ix_projects_workspace_id'), 'projects', ['workspace_id'], unique=False) op.create_table('users', sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('email', sa.String(length=255), nullable=False), sa.Column('hashed_password', sa.String(length=255), nullable=False), sa.Column('full_name', sa.String(length=255), nullable=False), sa.Column('role', sa.Enum('CUSTOMER_ADMIN', 'CUSTOMER_USER', 'SC_AGENT', 'SC_LEAD', 'SC_ADMIN', name='userrole'), nullable=False), sa.Column('is_active', sa.Boolean(), nullable=False), sa.Column('avatar_url', sa.String(length=512), nullable=True), sa.Column('id', sa.UUID(), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) op.create_index(op.f('ix_users_workspace_id'), 'users', ['workspace_id'], unique=False) op.create_table('tickets', sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('created_by', sa.UUID(), nullable=False), sa.Column('assigned_to', sa.UUID(), nullable=True), sa.Column('project_id', sa.UUID(), nullable=True), sa.Column('title', sa.String(length=500), nullable=False), sa.Column('description', sa.Text(), nullable=False), sa.Column('category', sa.String(length=100), nullable=True), sa.Column('priority', sa.Enum('P0', 'P1', 'P2', 'P3', name='ticketpriority'), nullable=False), sa.Column('status', sa.Enum('OPEN', 'ACKNOWLEDGED', 'IN_PROGRESS', 'RESOLVED', 'CLOSED', name='ticketstatus'), nullable=False), sa.Column('sla_deadline', sa.DateTime(timezone=True), nullable=True), sa.Column('ai_metadata', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('id', sa.UUID(), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), sa.ForeignKeyConstraint(['assigned_to'], ['users.id'], ), sa.ForeignKeyConstraint(['created_by'], ['users.id'], ), sa.ForeignKeyConstraint(['project_id'], ['projects.id'], ), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_tickets_assigned_to'), 'tickets', ['assigned_to'], unique=False) op.create_index(op.f('ix_tickets_created_by'), 'tickets', ['created_by'], unique=False) op.create_index(op.f('ix_tickets_id'), 'tickets', ['id'], unique=False) op.create_index(op.f('ix_tickets_project_id'), 'tickets', ['project_id'], unique=False) op.create_index(op.f('ix_tickets_workspace_id'), 'tickets', ['workspace_id'], unique=False) op.create_table('attachments', sa.Column('ticket_id', sa.UUID(), nullable=False), sa.Column('file_name', sa.String(length=500), nullable=False), sa.Column('file_url', sa.String(length=1024), nullable=False), sa.Column('content_type', sa.String(length=100), nullable=True), sa.Column('file_size', sa.String(length=50), nullable=True), sa.Column('id', sa.UUID(), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_attachments_id'), 'attachments', ['id'], unique=False) op.create_index(op.f('ix_attachments_ticket_id'), 'attachments', ['ticket_id'], unique=False) op.create_table('feedbacks', sa.Column('ticket_id', sa.UUID(), nullable=False), sa.Column('csat_score', sa.Integer(), nullable=False), sa.Column('comment', sa.Text(), nullable=True), sa.Column('id', sa.UUID(), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), sa.CheckConstraint('csat_score >= 1 AND csat_score <= 5', name='csat_score_range'), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_feedbacks_id'), 'feedbacks', ['id'], unique=False) op.create_index(op.f('ix_feedbacks_ticket_id'), 'feedbacks', ['ticket_id'], unique=True) op.create_table('messages', sa.Column('ticket_id', sa.UUID(), nullable=False), sa.Column('sender_id', sa.UUID(), nullable=False), sa.Column('content', sa.Text(), nullable=False), sa.Column('is_internal', sa.Boolean(), nullable=False), sa.Column('mentions', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('id', sa.UUID(), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_messages_id'), 'messages', ['id'], unique=False) op.create_index(op.f('ix_messages_sender_id'), 'messages', ['sender_id'], unique=False) op.create_index(op.f('ix_messages_ticket_id'), 'messages', ['ticket_id'], unique=False) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_messages_ticket_id'), table_name='messages') op.drop_index(op.f('ix_messages_sender_id'), table_name='messages') op.drop_index(op.f('ix_messages_id'), table_name='messages') op.drop_table('messages') op.drop_index(op.f('ix_feedbacks_ticket_id'), table_name='feedbacks') op.drop_index(op.f('ix_feedbacks_id'), table_name='feedbacks') op.drop_table('feedbacks') op.drop_index(op.f('ix_attachments_ticket_id'), table_name='attachments') op.drop_index(op.f('ix_attachments_id'), table_name='attachments') op.drop_table('attachments') op.drop_index(op.f('ix_tickets_workspace_id'), table_name='tickets') op.drop_index(op.f('ix_tickets_project_id'), table_name='tickets') op.drop_index(op.f('ix_tickets_id'), table_name='tickets') op.drop_index(op.f('ix_tickets_created_by'), table_name='tickets') op.drop_index(op.f('ix_tickets_assigned_to'), table_name='tickets') op.drop_table('tickets') op.drop_index(op.f('ix_users_workspace_id'), table_name='users') op.drop_index(op.f('ix_users_id'), table_name='users') op.drop_index(op.f('ix_users_email'), table_name='users') op.drop_table('users') op.drop_index(op.f('ix_projects_workspace_id'), table_name='projects') op.drop_index(op.f('ix_projects_id'), table_name='projects') op.drop_table('projects') op.drop_index(op.f('ix_workspaces_id'), table_name='workspaces') op.drop_table('workspaces') # ### end Alembic commands ###123456789101112131415161718192021222324252627282930"""add_is_active_to_escalation_rules
Revision ID: 27de6d53f3f0Revises: 86b5efeb3906Create Date: 2026-03-31 13:31:44.286498
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision: str = '27de6d53f3f0'down_revision: Union[str, None] = '86b5efeb3906'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ###123456789101112131415161718192021222324252627282930"""Add summary to kb_articles
Revision ID: 3dfe53d8e8aaRevises: c1ae7937bc77Create Date: 2026-03-29 11:05:22.858777
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision: str = '3dfe53d8e8aa'down_revision: Union[str, None] = 'c1ae7937bc77'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.add_column('kb_articles', sa.Column('summary', sa.Text(), nullable=True)) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_column('kb_articles', 'summary') # ### end Alembic commands ###12345678910111213141516171819202122232425262728293031323334"""make_nexus_thread_id_nullable
Revision ID: 86b5efeb3906Revises: b480d2a38d7dCreate Date: 2026-03-30 05:15:13.254451
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision: str = '86b5efeb3906'down_revision: Union[str, None] = 'b480d2a38d7d'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.alter_column('nexus_interactions', 'thread_id', existing_type=sa.UUID(), nullable=True) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.alter_column('nexus_interactions', 'thread_id', existing_type=sa.UUID(), nullable=False) # ### end Alembic commands ###123456789101112131415161718192021222324252627282930"""add_attachment_source_url
Revision ID: 9a883ee7d42eRevises: e7f94a821c56Create Date: 2026-03-29 12:25:09.608188
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision: str = '9a883ee7d42e'down_revision: Union[str, None] = 'e7f94a821c56'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.add_column('attachments', sa.Column('source_url', sa.String(length=2048), nullable=True)) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_column('attachments', 'source_url') # ### end Alembic commands ###123456789101112131415161718192021222324252627282930313233343536373839"""create_notifications_table
Revision ID: a1b2c3d4e5f6Revises: 175b693efa2cCreate Date: 2026-03-31 10:50:00.000000
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.revision: str = 'a1b2c3d4e5f6'down_revision: Union[str, None] = '175b693efa2c'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: op.create_table('notifications', sa.Column('id', sa.UUID(), nullable=False), sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('user_id', sa.UUID(), nullable=False), sa.Column('title', sa.String(length=255), nullable=False), sa.Column('message', sa.Text(), nullable=False), sa.Column('is_read', sa.Boolean(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_notifications_id'), 'notifications', ['id'], unique=False)
def downgrade() -> None: op.drop_index(op.f('ix_notifications_id'), table_name='notifications') op.drop_table('notifications')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051"""add_ai_workflows_table_correct
Revision ID: b2895ed533fcRevises: 9a883ee7d42eCreate Date: 2026-03-29 13:15:29.258592
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.revision: str = 'b2895ed533fc'down_revision: Union[str, None] = '9a883ee7d42e'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.create_table('ai_workflows', sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('entity_id', sa.UUID(), nullable=False), sa.Column('workflow_type', sa.String(length=50), nullable=False), sa.Column('current_stage', sa.String(length=100), nullable=True), sa.Column('steps', postgresql.JSONB(astext_type=sa.Text()), nullable=False), sa.Column('total_duration_ms', sa.Float(), nullable=True), sa.Column('metadata_json', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('id', sa.UUID(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_ai_workflows_entity_id'), 'ai_workflows', ['entity_id'], unique=False) op.create_index(op.f('ix_ai_workflows_id'), 'ai_workflows', ['id'], unique=False) op.create_index(op.f('ix_ai_workflows_workflow_type'), 'ai_workflows', ['workflow_type'], unique=False) op.create_index(op.f('ix_ai_workflows_workspace_id'), 'ai_workflows', ['workspace_id'], unique=False) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_ai_workflows_workspace_id'), table_name='ai_workflows') op.drop_index(op.f('ix_ai_workflows_workflow_type'), table_name='ai_workflows') op.drop_index(op.f('ix_ai_workflows_id'), table_name='ai_workflows') op.drop_index(op.f('ix_ai_workflows_entity_id'), table_name='ai_workflows') op.drop_table('ai_workflows') # ### end Alembic commands ###123456789101112131415161718192021222324252627282930"""Add soft delete to notifications
Revision ID: b480d2a38d7dRevises: 175b693efa2cCreate Date: 2026-03-30 04:12:30.482072
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision: str = 'b480d2a38d7d'down_revision: Union[str, None] = 'a1b2c3d4e5f6'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.add_column('notifications', sa.Column('deleted_at', sa.DateTime(), nullable=True)) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_column('notifications', 'deleted_at') # ### end Alembic commands ###1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""Add KBArticle and vector support
Revision ID: c1ae7937bc77Revises: 263c3f7b1819Create Date: 2026-03-27 20:21:25.366896
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresqlimport pgvector
# revision identifiers, used by Alembic.revision: str = 'c1ae7937bc77'down_revision: Union[str, None] = '263c3f7b1819'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # Enable pgvector extension op.execute("CREATE EXTENSION IF NOT EXISTS vector") # ### commands auto generated by Alembic - please adjust! ### op.create_table('kb_articles', sa.Column('workspace_id', sa.UUID(), nullable=False), sa.Column('title', sa.String(length=500), nullable=False), sa.Column('content', sa.Text(), nullable=False), sa.Column('category', sa.String(length=100), nullable=True), sa.Column('embedding', pgvector.sqlalchemy.vector.VECTOR(dim=1536), nullable=True), sa.Column('author_id', sa.UUID(), nullable=True), sa.Column('views', sa.Integer(), nullable=True), sa.Column('tags', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('id', sa.UUID(), nullable=False), sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), sa.ForeignKeyConstraint(['author_id'], ['users.id'], ), sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_kb_articles_id'), 'kb_articles', ['id'], unique=False) op.create_index(op.f('ix_kb_articles_workspace_id'), 'kb_articles', ['workspace_id'], unique=False) op.add_column('tickets', sa.Column('embedding', pgvector.sqlalchemy.vector.VECTOR(dim=1536), nullable=True)) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_column('tickets', 'embedding') op.drop_index(op.f('ix_kb_articles_workspace_id'), table_name='kb_articles') op.drop_index(op.f('ix_kb_articles_id'), table_name='kb_articles') op.drop_table('kb_articles') # ### end Alembic commands ###1234567891011121314151617181920212223242526272829303132333435363738"""Add duplicate tagging to kb_articles
Revision ID: d5fd341999f5Revises: 3dfe53d8e8aaCreate Date: 2026-03-29 11:15:46.342156
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision: str = 'd5fd341999f5'down_revision: Union[str, None] = '3dfe53d8e8aa'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.add_column('kb_articles', sa.Column('duplicate_of_id', sa.UUID(), nullable=True)) op.add_column('kb_articles', sa.Column('force_original', sa.Boolean(), nullable=True)) op.create_index(op.f('ix_kb_articles_duplicate_of_id'), 'kb_articles', ['duplicate_of_id'], unique=False) op.create_index(op.f('ix_kb_articles_force_original'), 'kb_articles', ['force_original'], unique=False) op.create_foreign_key(None, 'kb_articles', 'kb_articles', ['duplicate_of_id'], ['id']) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'kb_articles', type_='foreignkey') op.drop_index(op.f('ix_kb_articles_force_original'), table_name='kb_articles') op.drop_index(op.f('ix_kb_articles_duplicate_of_id'), table_name='kb_articles') op.drop_column('kb_articles', 'force_original') op.drop_column('kb_articles', 'duplicate_of_id') # ### end Alembic commands ###123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051"""add_attachment_multimodal_and_storage
Revision ID: e7f94a821c56Revises: d5fd341999f5Create Date: 2026-03-29 12:12:49.016556
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as saimport pgvector
# revision identifiers, used by Alembic.revision: str = 'e7f94a821c56'down_revision: Union[str, None] = 'd5fd341999f5'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.add_column('attachments', sa.Column('article_id', sa.UUID(), nullable=True)) op.add_column('attachments', sa.Column('storage_backend', sa.String(length=20), nullable=True)) op.add_column('attachments', sa.Column('embedding', pgvector.sqlalchemy.vector.VECTOR(dim=512), nullable=True)) op.add_column('attachments', sa.Column('ai_caption', sa.Text(), nullable=True)) op.add_column('attachments', sa.Column('is_processed', sa.Boolean(), nullable=True)) op.alter_column('attachments', 'ticket_id', existing_type=sa.UUID(), nullable=True) op.create_index(op.f('ix_attachments_article_id'), 'attachments', ['article_id'], unique=False) op.create_index(op.f('ix_attachments_is_processed'), 'attachments', ['is_processed'], unique=False) op.create_foreign_key(None, 'attachments', 'kb_articles', ['article_id'], ['id']) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'attachments', type_='foreignkey') op.drop_index(op.f('ix_attachments_is_processed'), table_name='attachments') op.drop_index(op.f('ix_attachments_article_id'), table_name='attachments') op.alter_column('attachments', 'ticket_id', existing_type=sa.UUID(), nullable=False) op.drop_column('attachments', 'is_processed') op.drop_column('attachments', 'ai_caption') op.drop_column('attachments', 'embedding') op.drop_column('attachments', 'storage_backend') op.drop_column('attachments', 'article_id') # ### end Alembic commands ###123456789101112131415161718192021222324252627282930313233343536"""adjust_vector_dimensions_to_768
Revision ID: f3a2b1c0d9e8Revises: e7f94a821c56Create Date: 2026-03-31 10:45:00.000000
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as saimport pgvector
# revision identifiers, used by Alembic.revision: str = 'f3a2b1c0d9e8'down_revision: Union[str, None] = '27de6d53f3f0'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # Adjust Ticket embedding dimension op.execute("ALTER TABLE tickets ALTER COLUMN embedding TYPE vector(768)") # Adjust KBArticle embedding dimension op.execute("ALTER TABLE kb_articles ALTER COLUMN embedding TYPE vector(768)") # Adjust KBArticleChunk embedding dimension op.execute("ALTER TABLE kb_article_chunks ALTER COLUMN embedding TYPE vector(768)")
def downgrade() -> None: op.execute("ALTER TABLE tickets ALTER COLUMN embedding TYPE vector(1536)") op.execute("ALTER TABLE kb_articles ALTER COLUMN embedding TYPE vector(1536)") op.execute("ALTER TABLE kb_article_chunks ALTER COLUMN embedding TYPE vector(1536)")12345678910111213141516171819202122232425262728"""add_user_gist_column
Revision ID: f62561e3e123Revises: 4c626672022aCreate Date: 2026-04-01 08:01:06.739182
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.revision: str = 'f62561e3e123'down_revision: Union[str, None] = '4c626672022a'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: op.add_column('users', sa.Column('ai_gist', postgresql.JSONB(astext_type=sa.Text()), server_default='{}', nullable=False))
def downgrade() -> None: op.drop_column('users', 'ai_gist')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128from fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import select, descfrom typing import List, Anyfrom uuid import UUID
from core.deps import get_db, get_current_user, get_arq_poolfrom core.permissions import require_roles, ADMIN_ROLES, ALL_SC_ROLESfrom models.user import User, UserRolefrom models.ai_interaction import AIInteractionfrom models.ticket import Ticketfrom models.kb_article import KBArticlefrom models.message import Messagefrom schemas.ai import AITraceResponse, AINodeInteraction, SummaryResponse, TicketSummaryfrom core.llm import get_llmfrom langchain.schema import HumanMessage, SystemMessage
router = APIRouter()
@router.get("/trace/{ticket_id}", response_model=AITraceResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES + ADMIN_ROLES))])async def get_ticket_ai_trace( ticket_id: UUID, db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_user)) -> Any: """ Retrieve a chronological trace of all AI interactions (Triage, Remediation, Embedding) related to a specific ticket. """ stmt = ( select(AIInteraction) .where( AIInteraction.ticket_id == ticket_id, AIInteraction.workspace_id == current_user.workspace_id ) .order_by(AIInteraction.created_at.asc()) ) result = await db.execute(stmt) interactions = result.scalars().all() if not interactions: # Check if ticket exists to return 404 vs empty from models.ticket import Ticket t_stmt = select(Ticket).where( Ticket.id == ticket_id, Ticket.workspace_id == current_user.workspace_id, Ticket.deleted_at.is_(None) ) if not (await db.execute(t_stmt)).scalar_one_or_none(): raise HTTPException(status_code=404, detail="Ticket not found in your workspace") return { "ticket_id": ticket_id, "interactions": [], "total_steps": 0, "total_duration_ms": 0.0 }
total_duration = sum([i.duration_ms.get("total", 0) for i in interactions if i.duration_ms]) return { "ticket_id": ticket_id, "thread_id": interactions[0].thread_id if interactions else None, "interactions": interactions, "total_steps": len(interactions), "total_duration_ms": round(total_duration, 2) }
@router.post("/summarize/ticket/{ticket_id}", response_model=SummaryResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES + [UserRole.SC_ADMIN]))])async def summarize_ticket( ticket_id: UUID, db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_user), arq_pool: Any = Depends(get_arq_pool)) -> Any: """ Manually triggers dual summary generation (Internal vs Customer). """ stmt = select(Ticket).where( Ticket.id == ticket_id, Ticket.workspace_id == current_user.workspace_id, Ticket.deleted_at.is_(None) ) result = await db.execute(stmt) ticket = result.scalar_one_or_none() if not ticket: raise HTTPException(status_code=404, detail="Ticket not found")
await arq_pool.enqueue_job("auto_summarize_ticket", ticket.id)
from datetime import datetime return { "id": ticket.id, "summary": "Summarization enqueued. Please check back in a few seconds.", "generated_at": datetime.utcnow() }
@router.post("/summarize/kb/{article_id}", response_model=SummaryResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES + [UserRole.SC_ADMIN]))])async def summarize_kb( article_id: UUID, db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_user), arq_pool: Any = Depends(get_arq_pool)) -> Any: """ Manually triggers KB article summary generation. """ stmt = select(KBArticle).where( KBArticle.id == article_id, KBArticle.workspace_id == current_user.workspace_id, KBArticle.deleted_at.is_(None) ) result = await db.execute(stmt) article = result.scalar_one_or_none() if not article: raise HTTPException(status_code=404, detail="Article not found")
await arq_pool.enqueue_job("auto_summarize_kb", article.id)
from datetime import datetime return { "id": article.id, "summary": "Summarization enqueued.", "generated_at": datetime.utcnow() }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182"""Attachment endpoints: Upload, Download, and Delete with BOLA protection."""
from datetime import datetimeimport uuidfrom typing import List, Anyfrom fastapi import APIRouter, Depends, HTTPException, status, UploadFile, Filefrom pathlib import Pathfrom core.deps import get_db, get_current_userfrom core.permissions import ALL_SC_ROLESfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import selectfrom core.storage import get_storage_providerfrom fastapi.responses import FileResponse, RedirectResponsefrom models.user import Userfrom models.ticket import Ticketfrom models.attachment import Attachmentfrom schemas.attachment import AttachmentResponse
router = APIRouter()
# Local storage for attachments (Hackathon sim)# UPLOAD_DIR = Path("uploads")# UPLOAD_DIR.mkdir(exist_ok=True)
@router.post("/{ticket_id}/attachments", response_model=AttachmentResponse, status_code=status.HTTP_201_CREATED)async def upload_attachment( ticket_id: uuid.UUID, file: UploadFile = File(...), current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """Upload a file for a specific ticket. Enforces ownership for customers.""" is_staff = current_user.role in ALL_SC_ROLES stmt = select(Ticket).where( Ticket.id == ticket_id, Ticket.workspace_id == current_user.workspace_id, Ticket.deleted_at.is_(None) ) if not is_staff: # Customers can ONLY upload to tickets they created stmt = stmt.where(Ticket.created_by == current_user.id)
result = await db.execute(stmt) if not result.scalar_one_or_none(): raise HTTPException(status_code=404, detail="Ticket not found or access denied") storage = get_storage_provider() content = await file.read() upload_res = await storage.upload(content, file.filename, current_user.workspace_id) new_attachment = Attachment( workspace_id=current_user.workspace_id, ticket_id=ticket_id, uploader_id=current_user.id, filename=file.filename, storage_path=upload_res.path, storage_backend=upload_res.backend, content_type=file.content_type, file_size=len(content) ) db.add(new_attachment) await db.commit() await db.refresh(new_attachment) return new_attachment
@router.get("/{ticket_id}/attachments", response_model=List[AttachmentResponse])async def list_attachments( ticket_id: uuid.UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """List all attachments for a specific ticket. Enforces ownership for customers.""" is_staff = current_user.role in ALL_SC_ROLES # 1. Verify ticket access stmt = select(Ticket).where( Ticket.id == ticket_id, Ticket.workspace_id == current_user.workspace_id, Ticket.deleted_at.is_(None) ) if not is_staff: # Customers can ONLY list attachments for tickets they created stmt = stmt.where(Ticket.created_by == current_user.id)
result = await db.execute(stmt) if not result.scalar_one_or_none(): raise HTTPException(status_code=404, detail="Ticket not found or access denied") # 2. Fetch attachments att_stmt = select(Attachment).where( Attachment.ticket_id == ticket_id, Attachment.deleted_at.is_(None) ).order_by(Attachment.created_at.desc()) att_res = await db.execute(att_stmt) return att_res.scalars().all()
@router.get("/attachments/{attachment_id}/download")async def download_attachment( attachment_id: uuid.UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """Download an attachment. Enforces ownership check via parent ticket.""" is_staff = current_user.role in ALL_SC_ROLES # Fetch attachment and join with Ticket to verify ownership stmt = ( select(Attachment, Ticket) .join(Ticket, Attachment.ticket_id == Ticket.id) .where( Attachment.id == attachment_id, Attachment.workspace_id == current_user.workspace_id, Attachment.deleted_at.is_(None) ) ) result = await db.execute(stmt) row = result.fetchone() if not row: raise HTTPException(status_code=404, detail="Attachment not found") attachment, ticket = row[0], row[1] if not is_staff and ticket.created_by != current_user.id: raise HTTPException(status_code=403, detail="Not authorized to download this attachment") storage = get_storage_provider() if attachment.storage_backend == "s3": url = await storage.get_url(attachment.storage_path) return RedirectResponse(url=url) return FileResponse( path=storage.get_local_path(attachment.storage_path), filename=attachment.filename, media_type=attachment.content_type )
@router.delete("/attachments/{attachment_id}", status_code=status.HTTP_200_OK)async def delete_attachment( attachment_id: uuid.UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """Soft Delete an attachment. Enforces ownership check.""" is_staff = current_user.role in ALL_SC_ROLES stmt = ( select(Attachment, Ticket) .join(Ticket, Attachment.ticket_id == Ticket.id) .where( Attachment.id == attachment_id, Attachment.workspace_id == current_user.workspace_id, Attachment.deleted_at.is_(None) ) ) result = await db.execute(stmt) row = result.fetchone() if not row: raise HTTPException(status_code=404, detail="Attachment not found") attachment, ticket = row[0], row[1] # Permission: Sender of the attachment OR Admin OR Owner of the Parent Ticket is_uploader = attachment.uploader_id == current_user.id is_ticket_owner = ticket.created_by == current_user.id if not (is_staff or is_uploader or is_ticket_owner): raise HTTPException(status_code=403, detail="Not authorized to delete this attachment") attachment.deleted_at = datetime.utcnow() attachment.deleted_by_id = current_user.id db.add(attachment) await db.commit() return {"status": "deleted"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242"""Authentication endpoints: Registration, Login, Token generation, Password management."""
from fastapi import APIRouter, Depends, HTTPException, status, Headerfrom fastapi.security import OAuth2PasswordRequestFormfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import selectfrom typing import Any, Optional
from core.database import async_session_factoryfrom core.deps import get_db, get_current_user, get_current_refresh_userfrom core.security import verify_password, get_password_hash, create_access_token, create_refresh_tokenfrom core.logging import get_loggerfrom models.user import User, UserRolefrom models.workspace import Workspacefrom schemas.auth import Token, UserRegister, PasswordChangeRequest, TokenRefreshResponse, ForgotPasswordRequest, ResetPasswordRequest
router = APIRouter()logger = get_logger(__name__)
@router.post("/register", response_model=Token, status_code=status.HTTP_201_CREATED)async def register_user(user_in: UserRegister, db: AsyncSession = Depends(get_db)) -> Any: """ Register a new user. If workspace_id is absent, creates a new workspace and makes the user a CUSTOMER_ADMIN. Otherwise joins an existing workspace as CUSTOMER_USER. """ # Check if user exists stmt = select(User).where(User.email == user_in.email) result = await db.execute(stmt) if result.scalar_one_or_none(): logger.warning(f"Registration failed: User with email {user_in.email} already exists") raise HTTPException(status_code=400, detail="User with this email already exists")
# Handle Workspace if user_in.workspace_id: # Join existing workspace stmt = select(Workspace).where( Workspace.id == user_in.workspace_id, Workspace.deleted_at.is_(None) ) result = await db.execute(stmt) workspace = result.scalar_one_or_none() if not workspace: raise HTTPException(status_code=404, detail="Workspace not found") role = UserRole.CUSTOMER_USER else: # Create new workspace ws_name = user_in.workspace_name or f"{user_in.full_name}'s Workspace" workspace = Workspace(name=ws_name) db.add(workspace) await db.flush() # get id role = UserRole.CUSTOMER_ADMIN
# --- AUTO-PROVISION SC_ADMIN --- # Format: admin_<ws_slug>@3sc.com import re ws_slug = re.sub(r'[^a-z0-9]', '_', ws_name.lower()) sc_email = f"admin_{ws_slug}@3sc.com" sc_password = f"SC_Admin_{str(workspace.id)[:8]}!"
# Ensure unique SC email (unlikely conflict, but safe) sc_stmt = select(User).where(User.email == sc_email) sc_exists = (await db.execute(sc_stmt)).scalar_one_or_none() if not sc_exists: sc_admin = User( email=sc_email, hashed_password=get_password_hash(sc_password), full_name=f"{ws_name} SC Admin", role=UserRole.SC_ADMIN, workspace_id=workspace.id, ) db.add(sc_admin) logger.info(f"AUTO-PROVISION: Created SC Admin {sc_email} for workspace {workspace.id}")
# Create Initial User (Customer Admin) new_user = User( email=user_in.email, hashed_password=get_password_hash(user_in.password), full_name=user_in.full_name, role=role, workspace_id=workspace.id, ) db.add(new_user) await db.commit() await db.refresh(new_user)
logger.info(f"User registration successful: {new_user.email} (ID: {new_user.id})")
# Generate tokens for the Registrant access_token = create_access_token(subject=new_user.id, workspace_id=new_user.workspace_id) refresh_token = create_refresh_token(subject=new_user.id)
return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}
@router.post("/login", response_model=Token)async def login( form_data: OAuth2PasswordRequestForm = Depends(), db: AsyncSession = Depends(get_db), x_nexus_portal: Optional[str] = Header(None, alias="X-Nexus-Portal")) -> Any: """OAuth2 compatible token login, get an access token for future requests.""" stmt = select(User).where( User.email == form_data.username, User.deleted_at.is_(None) ) result = await db.execute(stmt) user = result.scalar_one_or_none()
if not user: logger.warning(f"Login failed: Account not found for {form_data.username}") raise HTTPException(status_code=400, detail="Account not found. Please contact your administrator.")
if not verify_password(form_data.password, user.hashed_password): logger.warning(f"Login failed: Invalid password for {form_data.username}") raise HTTPException(status_code=400, detail="Incorrect password. Please try again.") # --- PORTAL AUTHORIZATION --- if x_nexus_portal == "internal": if user.role not in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]: logger.warning(f"Login failed: Customer {user.email} attempted Internal Portal access") raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Access Denied: Customers cannot access the Operations Console." ) elif x_nexus_portal == "customer": if user.role not in [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]: # Optional: Allow staff to access customer portal for support? # For now, let's keep it strict if requested. logger.warning(f"Login failed: Staff {user.email} attempted Customer Portal access") raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Access Denied: Staff must use the Operations Console." )
if not user.is_active: logger.warning(f"Login failed: Account inactive for {form_data.username}") raise HTTPException(status_code=400, detail="Inactive user")
logger.info(f"User login successful: {user.email} (Workspace ID: {user.workspace_id})") access_token = create_access_token(subject=user.id, workspace_id=user.workspace_id) refresh_token = create_refresh_token(subject=user.id)
return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}
@router.post("/change-password")async def change_password( payload: PasswordChangeRequest, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """Change user password.""" if not verify_password(payload.old_password, current_user.hashed_password): raise HTTPException(status_code=400, detail="Invalid old password") current_user.hashed_password = get_password_hash(payload.new_password) db.add(current_user) await db.commit() return {"message": "Password updated successfully"}
@router.post("/refresh", response_model=TokenRefreshResponse)async def refresh_token( current_user: User = Depends(get_current_refresh_user)) -> Any: """Exchange a refresh token for a new access token.""" new_access_token = create_access_token( subject=current_user.id, workspace_id=current_user.workspace_id ) return {"access_token": new_access_token, "token_type": "bearer"}
@router.post("/logout")async def logout() -> Any: """ Log out the current user (Stateless). In a full production system, this would add the token to a blocklist. """ return {"message": "Successfully logged out"}
@router.post("/forgot-password")async def forgot_password(payload: ForgotPasswordRequest) -> Any: """ Initiate password reset. In production, this would send an email with a signed token. """ # For now, we'll return a dummy token for the 'reset-password' demo # In reality, this token would be a short-lived JWT with type='reset' reset_token = create_access_token(subject=payload.email, expires_delta=None) # Just for demo return { "message": "Password reset email sent (simulated)", "reset_token": reset_token # Returning here ONLY for hackathon/testing ease }
@router.post("/reset-password")async def reset_password( payload: ResetPasswordRequest, db: AsyncSession = Depends(get_db)) -> Any: """Reset password using a token.""" try: from core.config import get_settings from jose import jwt settings = get_settings() decoded_payload = jwt.decode(payload.token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) email: str = decoded_payload.get("sub") if not email: raise HTTPException(status_code=400, detail="Invalid token") stmt = select(User).where( User.email == email, User.deleted_at.is_(None) ) result = await db.execute(stmt) user = result.scalar_one_or_none() if not user: raise HTTPException(status_code=404, detail="User not found") user.hashed_password = get_password_hash(payload.new_password) db.add(user) await db.commit() return {"message": "Password reset successful"} except Exception: raise HTTPException(status_code=400, detail="Invalid or expired reset token")
@router.get("/me", response_model=Any)async def get_my_profile(current_user: User = Depends(get_current_user)) -> Any: """Get profile of the currently logged-in user.""" return { "id": str(current_user.id), "email": current_user.email, "full_name": current_user.full_name, "role": current_user.role, "workspace_id": str(current_user.workspace_id) }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272"""Dashboard endpoints for summary stats and activity."""
from typing import Any, Dict, Listfrom fastapi import APIRouter, Dependsfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import select, func, or_
from core.deps import get_db, get_current_userfrom core.llm import get_llmfrom langchain_core.prompts import ChatPromptTemplatefrom models.user import User, UserRolefrom models.ticket import Ticket, TicketStatus
from schemas.ticket import TicketResponse
router = APIRouter()
@router.get("/stats")async def get_dashboard_stats( workspace_id: str = None, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: from datetime import datetime is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] # Identify target workspace target_ws = current_user.workspace_id is_global = False if is_staff: if workspace_id and workspace_id != "all": target_ws = workspace_id else: is_global = True # Global view for staff if no specific workspace selected
# 1. Basic Status Counts stmt = ( select(Ticket.status, func.count(Ticket.id)) .where(Ticket.deleted_at.is_(None)) ) if not is_global: stmt = stmt.where(Ticket.workspace_id == target_ws) if not is_staff: from sqlalchemy.orm import aliased Creator = aliased(User) stmt = stmt.join(Creator, Ticket.created_by == Creator.id).where(Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER])) stmt = stmt.group_by(Ticket.status) counts_res = await db.execute(stmt) counts = {row[0]: row[1] for row in counts_res.all()} for s in TicketStatus: if s not in counts: counts[s] = 0 total = sum(counts.values())
# 2. Advanced Metrics (SLA, Resolution, CSAT) metrics_stmt = select(Ticket).where(Ticket.deleted_at.is_(None)) if not is_global: metrics_stmt = metrics_stmt.where(Ticket.workspace_id == target_ws) if not is_staff: from sqlalchemy.orm import aliased M_Creator = aliased(User) metrics_stmt = metrics_stmt.join(M_Creator, Ticket.created_by == M_Creator.id).where(M_Creator.role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER])) metrics_res = await db.execute(metrics_stmt) all_tickets = metrics_res.scalars().all() now = datetime.now() resolved = [t for t in all_tickets if t.status in [TicketStatus.RESOLVED, TicketStatus.CLOSED] and t.resolved_at] avg_res = sum((t.resolved_at - t.created_at).total_seconds() / 3600 for t in resolved) / len(resolved) if resolved else 0.0 breached = len([t for t in all_tickets if t.status not in [TicketStatus.RESOLVED, TicketStatus.CLOSED] and t.sla_deadline and t.sla_deadline < now]) ratings = [t.ai_metadata.get("rating") for t in all_tickets if t.ai_metadata and t.ai_metadata.get("rating") is not None] avg_csat = sum(ratings) / len(ratings) if ratings else 0.0
# 3. Personalized Metrics my_open_stmt = select(func.count(Ticket.id)).where( Ticket.assigned_to == current_user.id, Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), Ticket.deleted_at.is_(None) ) if not is_global: my_open_stmt = my_open_stmt.where(Ticket.workspace_id == target_ws) my_open_res = await db.execute(my_open_stmt) my_open_count = my_open_res.scalar() or 0
# 4. Personnel Load personnel_stmt = ( select(User.full_name, func.count(Ticket.id)) .join(Ticket, Ticket.assigned_to == User.id) .where( Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), Ticket.deleted_at.is_(None) ) ) if not is_global: personnel_stmt = personnel_stmt.where(Ticket.workspace_id == target_ws) personnel_stmt = personnel_stmt.group_by(User.full_name) p_res = await db.execute(personnel_stmt) personnel_load = [{"name": row[0], "count": row[1]} for row in p_res.all()] unassigned = len([t for t in all_tickets if t.assigned_to is None and t.status in [TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]]) if unassigned > 0: personnel_load.append({"name": "Unassigned", "count": unassigned})
return { "total_tickets": total, "by_status": counts, "workspace_id": target_ws, "my_open_count": my_open_count, "personnel_load": personnel_load, "performance": { "avg_resolution_hours": round(avg_res, 1), "csat_score": round(avg_csat, 1), "resolved_count": len(resolved), "rated_count": len(ratings), "sla_breached_count": breached } }
@router.get("/my-tickets", response_model=List[TicketResponse])async def get_my_tickets( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: from sqlalchemy.orm import aliased Creator = aliased(User) Assignee = aliased(User)
stmt = ( select( Ticket, Creator.full_name.label("creator_name"), Assignee.full_name.label("assigned_name") ) .outerjoin(Creator, Ticket.created_by == Creator.id) .outerjoin(Assignee, Ticket.assigned_to == Assignee.id) .where( ((Ticket.created_by == current_user.id) | (Ticket.assigned_to == current_user.id)), Ticket.workspace_id == current_user.workspace_id, Ticket.deleted_at.is_(None) ) .order_by(Ticket.updated_at.desc()) ) result = await db.execute(stmt) out = [] for row in result.all(): t = row[0] t.creator_name = row.creator_name t.assigned_name = row.assigned_name out.append(t) return out
@router.get("/agent-queue", response_model=List[TicketResponse])async def get_agent_queue( workspace_id: str = None, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: from sqlalchemy.orm import aliased is_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] target_ws = current_user.workspace_id is_global = False if is_staff: if workspace_id and workspace_id != "all": target_ws = workspace_id else: is_global = True
Creator = aliased(User) Assignee = aliased(User)
stmt = ( select( Ticket, Creator.full_name.label("creator_name"), Assignee.full_name.label("assigned_name") ) .outerjoin(Creator, Ticket.created_by == Creator.id) .outerjoin(Assignee, Ticket.assigned_to == Assignee.id) .where( Ticket.deleted_at.is_(None) ) ) if not is_global: stmt = stmt.where(Ticket.workspace_id == target_ws) stmt = stmt.order_by(Ticket.priority.asc(), Ticket.created_at.asc()) result = await db.execute(stmt) out = [] for row in result.all(): t = row[0] t.creator_name = row.creator_name t.assigned_name = row.assigned_name out.append(t) return out
@router.get("/ai-insights")async def get_ai_insights( workspace_id: str = None, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """ Generates a live AI summary and suggested actions for the landing screen. Uses current workspace context (stats, queue) to provide actionable intelligence. """ # 1. Gather context stats = await get_dashboard_stats(workspace_id, current_user, db) queue = await get_agent_queue(workspace_id, current_user, db) # 2. Prepare Prompt llm = get_llm() prompt = ChatPromptTemplate.from_template(""" You are the Nexus Workspace Intelligence Engine. Analyze the following workspace operational data and provide: 1. A concise, professional "Mission Summary" (2-3 sentences). 2. Exactly 3 "Suggested Actions" for the lead agent. DATA: - Total Active Tickets: {total} - Breached/Urgent: {breached} - Distribution: {status_dist} - Personnel: {agents} TICKET SAMPLE: {ticket_sample} Respond in JSON format: {{ "summary": "...", "actions": ["...", "...", "..."] }} """) # Format ticket sample for context sample = "\n".join([f"- {t.title} ({t.priority}, {t.status})" for t in queue[:5]]) chain = prompt | llm try: response = await chain.ainvoke({ "total": stats["total_tickets"], "breached": any(t.priority == "P0" for t in queue), # If we have P0s, mention urgency "status_dist": stats["by_status"], "agents": len(queue), "ticket_sample": sample }) # Parse JSON from response content import json insights = json.loads(response.content.strip().replace("```json", "").replace("```", "")) return insights except Exception as e: # Fallback to generic if AI fails return { "summary": f"Workspace stabilization in progress. {stats['total_tickets']} active tickets identified in the stream.", "actions": [ "Review unassigned P0 tickets in the Operational Board", "Perform load balance check across active personnel", "Analyze SLA trends for potential breach risks" ] }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Escalation management endpoints: Rules and Audit."""
from typing import List, Anyfrom uuid import UUIDfrom fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import select, and_, String, cast
from core.deps import get_db, get_current_userfrom core.permissions import require_roles, ADMIN_ROLES, ALL_SC_ROLESfrom models.user import Userfrom models.escalation_rule import EscalationRulefrom models.audit_log import AuditLogfrom schemas.escalation import EscalationRuleCreate, EscalationRuleUpdate, EscalationRuleResponse, AuditLogResponse
router = APIRouter()
@router.post("/rules", response_model=EscalationRuleResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_roles(ADMIN_ROLES))])async def create_escalation_rule( payload: EscalationRuleCreate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """Admin only: Create an escalation rule.""" new_rule = EscalationRule( workspace_id=current_user.workspace_id, **payload.model_dump() ) db.add(new_rule) await db.commit() await db.refresh(new_rule) return new_rule
@router.get("/rules", response_model=List[EscalationRuleResponse], dependencies=[Depends(require_roles(ALL_SC_ROLES))])async def list_escalation_rules( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """Service Center roles: List escalation rules.""" stmt = select(EscalationRule).where(EscalationRule.workspace_id == current_user.workspace_id).order_by(EscalationRule.priority_level.asc()) result = await db.execute(stmt) return result.scalars().all()
@router.patch("/rules/{rule_id}", response_model=EscalationRuleResponse, dependencies=[Depends(require_roles(ADMIN_ROLES))])async def update_escalation_rule( rule_id: UUID, payload: EscalationRuleUpdate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """Admin only: Update an escalation rule or toggle its active state.""" stmt = select(EscalationRule).where( EscalationRule.id == rule_id, EscalationRule.workspace_id == current_user.workspace_id ) result = await db.execute(stmt) rule = result.scalar_one_or_none() if not rule: raise HTTPException(status_code=404, detail="Rule not found") update_data = payload.model_dump(exclude_unset=True) for key, value in update_data.items(): setattr(rule, key, value) await db.commit() await db.refresh(rule) return rule
@router.delete("/rules/{rule_id}", status_code=status.HTTP_204_NO_CONTENT, dependencies=[Depends(require_roles(ADMIN_ROLES))])async def delete_escalation_rule( rule_id: UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> None: """Admin only: Remove an escalation rule.""" stmt = select(EscalationRule).where( EscalationRule.id == rule_id, EscalationRule.workspace_id == current_user.workspace_id ) result = await db.execute(stmt) rule = result.scalar_one_or_none() if not rule: raise HTTPException(status_code=404, detail="Rule not found") await db.delete(rule) await db.commit() return None
@router.get("/audit", response_model=List[AuditLogResponse], dependencies=[Depends(require_roles(ALL_SC_ROLES))])async def view_escalation_audit( skip: int = 0, limit: int = 100, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """View audit trail of escalations and status changes.""" stmt = select(AuditLog).where( AuditLog.workspace_id == current_user.workspace_id, AuditLog.action.in_(["escalation", "status_change"]) ).offset(skip).limit(limit).order_by(AuditLog.created_at.desc()) result = await db.execute(stmt) return result.scalars().all()
@router.get("/breaches", dependencies=[Depends(require_roles(ALL_SC_ROLES))])async def list_active_breaches( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """Get all tickets that are currently in BREACH status based on ACTIVE rules.""" from models.ticket import Ticket, TicketStatus from datetime import datetime # 1. Fetch tickets and ACTIVE rules stmt = ( select(Ticket, EscalationRule.threshold_minutes) .join(EscalationRule, and_( EscalationRule.workspace_id == Ticket.workspace_id, EscalationRule.priority_level == cast(Ticket.priority, String), EscalationRule.is_active == True ), isouter=True) .where( Ticket.workspace_id == current_user.workspace_id, Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), Ticket.deleted_at.is_(None) ) ) result = await db.execute(stmt) rows = result.all() now = datetime.utcnow() breached_tickets = [] for ticket, threshold in rows: # Default to 24h if no active rule exists limit = threshold or 1440 age_mins = (now - ticket.created_at).total_seconds() / 60 if age_mins > limit: breached_tickets.append({ "id": str(ticket.id), "title": ticket.title, "priority": ticket.priority, "status": ticket.status, "age_minutes": round(age_mins, 1), "threshold": limit, "is_escalated": ticket.is_escalated is not None }) return breached_tickets1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""Feedback endpoints: Submit and View CSAT ratings."""
import uuidfrom typing import List, Anyfrom fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import select
from core.deps import get_db, get_current_userfrom core.permissions import require_roles, ALL_CUSTOMER_ROLES, ALL_SC_ROLESfrom models.user import Userfrom models.ticket import Ticket, TicketStatusfrom models.feedback import Feedbackfrom schemas.feedback import FeedbackCreate, FeedbackResponse
router = APIRouter()
@router.post("/{ticket_id}/feedback", response_model=FeedbackResponse, status_code=status.HTTP_201_CREATED)async def submit_feedback( ticket_id: uuid.UUID, payload: FeedbackCreate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """Submit CSAT feedback for a resolved/closed ticket.""" # Validate ticket exists and is resolved/closed stmt = select(Ticket).where( Ticket.id == ticket_id, Ticket.workspace_id == current_user.workspace_id, Ticket.deleted_at.is_(None) ) result = await db.execute(stmt) ticket = result.scalar_one_or_none() if not ticket: raise HTTPException(status_code=404, detail="Ticket not found in your workspace") if ticket.status not in [TicketStatus.RESOLVED, TicketStatus.CLOSED]: raise HTTPException(status_code=400, detail="Feedback can only be submitted for resolved or closed tickets") # Check if feedback already exists stmt = select(Feedback).where(Feedback.ticket_id == ticket_id) result = await db.execute(stmt) if result.scalar_one_or_none(): raise HTTPException(status_code=400, detail="Feedback already submitted for this ticket") new_feedback = Feedback( id=uuid.uuid4(), workspace_id=current_user.workspace_id, ticket_id=ticket_id, user_id=current_user.id, rating=payload.rating, comment=payload.comment ) db.add(new_feedback) await db.commit() await db.refresh(new_feedback) return new_feedback
@router.get("/{ticket_id}/feedback", response_model=FeedbackResponse)async def get_ticket_feedback( ticket_id: uuid.UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """View feedback for a specific ticket.""" stmt = select(Feedback).where(Feedback.ticket_id == ticket_id, Feedback.workspace_id == current_user.workspace_id) result = await db.execute(stmt) feedback = result.scalar_one_or_none() if not feedback: raise HTTPException(status_code=404, detail="Feedback not found") return feedback.dockerignoreAdded+17
.gitignoreAdded+82
DockerfileAdded+56
README.mdAdded+19
agents/__init__.pyAdded
agents/analytics.pyAdded+46
agents/duplication.pyAdded+145
agents/nexus_checkpoint.pyAdded+93
agents/nexus_master.pyAdded+562
agents/remediation.pyAdded+96
agents/routing.pyAdded+110
agents/safety.pyAdded+97
agents/state.pyAdded+44
agents/suggestion.pyAdded+118
agents/summarizer.pyAdded+43
agents/tools/nexus_tools.pyAdded+434
agents/triage.pyAdded+102
agents/utils.pyAdded+213
agents/workflow.pyAdded+247
alembic.iniAdded+115
alembic/READMEAdded+1
alembic/env.pyAdded+111
alembic/script.py.makoAdded+26
alembic/versions/0001_initial_consolidated.pyAdded+365
alembic/versions/0002_fix_attachments_schema.pyAdded+54
alembic/versions/0003_final_schema_reconciliation.pyAdded+85
alembic/versions/4c626672022a_add_meta_infra_health_table.pyAdded+44
alembic/versions/archive/0b3641c15213_add_resolution_fields_to_ticket.pyAdded+112
alembic/versions/archive/175b693efa2c_add_nexus_agent_tables.pyAdded+67
alembic/versions/archive/263c3f7b1819_initial_migration.pyAdded+162
alembic/versions/archive/27de6d53f3f0_add_is_active_to_escalation_rules.pyAdded+30
alembic/versions/archive/3dfe53d8e8aa_add_summary_to_kb_articles.pyAdded+30
alembic/versions/archive/86b5efeb3906_make_nexus_thread_id_nullable.pyAdded+34
alembic/versions/archive/9a883ee7d42e_add_attachment_source_url.pyAdded+30
alembic/versions/archive/a1b2c3d4e5f6_create_notifications_table.pyAdded+39
alembic/versions/archive/b2895ed533fc_add_ai_workflows_table_correct.pyAdded+51
alembic/versions/archive/b480d2a38d7d_add_soft_delete_to_notifications.pyAdded+30
alembic/versions/archive/c1ae7937bc77_add_kbarticle_and_vector_support.pyAdded+56
alembic/versions/archive/d5fd341999f5_add_duplicate_tagging_to_kb_articles.pyAdded+38
alembic/versions/archive/e7f94a821c56_add_attachment_multimodal_and_storage.pyAdded+51
alembic/versions/archive/f3a2b1c0d9e8_adjust_vector_dimensions_to_768.pyAdded+36
alembic/versions/f62561e3e123_add_user_gist_column.pyAdded+28
api/__init__.pyAdded
api/v1/__init__.pyAdded
api/v1/ai.pyAdded+128
api/v1/attachments.pyAdded+182
api/v1/auth.pyAdded+242
api/v1/dashboard.pyAdded+272
api/v1/escalations.pyAdded+148
api/v1/feedback.pyAdded+74