import uuid import logging import time import asyncio from typing import Dict, Any from datetime import datetime, timedelta from langgraph.graph import StateGraph, START, END from langgraph.types import RetryPolicy from agents.state import AgentState from agents.ingestion import ingestion_node from agents.triage import triage_node from agents.duplication import duplication_node from agents.remediation import remediation_node, should_continue_remediation from agents.routing import routing_node from agents.suggestion import suggestion_node from agents.kb_node import kb_search_node # Added KB Node from agents.utils import sanitize_for_db, safe_uuid from core.database import async_session_factory from models.ticket import Ticket, TicketStatus from models.user import User from models.attachment import Attachment from models.knowledge_insight import KnowledgeInsight, InsightStatus from models.knowledge_insight_ticket import KnowledgeInsightTicket from sqlalchemy import select from core.cache import invalidate_cache 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" # --- SINGLETON WORKFLOW APP (GAP-3 Fix) --- _workflow_app = None _workflow_lock = None async def get_workflow_app(): global _workflow_app, _workflow_lock if _workflow_app is not None: return _workflow_app if _workflow_lock is None: _workflow_lock = asyncio.Lock() async with _workflow_lock: if _workflow_app is not None: return _workflow_app workflow = StateGraph(AgentState) retry_policy = RetryPolicy(max_attempts=3) workflow.add_node("ingestion", ingestion_node, retry=retry_policy) workflow.add_node("duplication", duplication_node, retry=retry_policy) workflow.add_node("kb_search", kb_search_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.add_edge(START, "ingestion") workflow.add_edge("ingestion", "duplication") workflow.add_conditional_edges( "duplication", should_proceed_after_duplication, {"triage": "triage", END: END} ) workflow.add_edge("triage", "kb_search") workflow.add_edge("kb_search", "remediation") workflow.add_conditional_edges( "remediation", should_continue_remediation, {"routing": "routing", "suggestion": "suggestion"} ) workflow.add_edge("routing", "suggestion") workflow.add_edge("suggestion", END) _workflow_app = workflow.compile() return _workflow_app async def run_ai_workflow(ctx: Any, ticket_id: Any, workspace_id: Any = None, **kwargs: Any) -> Dict[str, Any]: """ Main entry point to run the agentic workflow for a new ticket. Hydrates data purely from DB (GAP-9 Fix). """ from core.tasks import check_job_latch, enqueue_task t_id = uuid.UUID(str(ticket_id)) if ticket_id else None ws_id = uuid.UUID(str(workspace_id)) if workspace_id else None if not await check_job_latch(ctx, t_id, "ai_workflow"): return {} thread_id = uuid.uuid4() v_tag = f"v_{int(time.time() % 1000)}" logger.info(f"TASK START [{v_tag}]: Orchestrating AI for ticket {t_id}") # FETCH DATA (GAP-9: hydrate source of truth) 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: logger.error(f"Workflow: Ticket {t_id} not found.") return {} ws_id = ws_id or ticket.workspace_id ticket_title = ticket.title ticket_desc = ticket.description ticket_cat = ticket.category ticket_prio = ticket.priority # --- PHASE 0: Hash & Fast-Path Deduplication (GAP-DEDUP) --- if not ticket.content_hash: import hashlib payload_str = f"{ticket_title.strip()}|{ticket_desc.strip()}" ticket.content_hash = hashlib.sha256(payload_str.encode('utf-8')).hexdigest() db.add(ticket) await db.commit() # Check for existing UNRESOLVED duplicate in this workspace dup_stmt = select(Ticket.id).where( Ticket.workspace_id == ws_id, Ticket.content_hash == ticket.content_hash, Ticket.id != t_id, Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]), Ticket.deleted_at.is_(None) ).limit(1) dup_res = await db.execute(dup_stmt) fast_dup = dup_res.scalar() if fast_dup and not kwargs.get("force_skip_duplication"): logger.warning(f"Workflow Fast-Dedup: Ticket {t_id} is identical to {fast_dup} (AUTO-CLOSING)") ticket.status = TicketStatus.CLOSED ticket.duplicate_of_id = fast_dup ticket.resolved_at = datetime.utcnow() ticket.resolution_text = f"Automated Workflow: Marked as fast-duplicate of #{str(fast_dup)[:8]}." await db.commit() # TRIGGER: Immediate summarization for fast-duplicates (even with 0 messages) from core.tasks import enqueue_task await enqueue_task( ctx.get("redis") if isinstance(ctx, dict) else None, 'auto_summarize_ticket', t_id, manual=True, _job_id=f"summarize_init_{t_id}" ) return {"is_duplicate": True, "duplicate_of_id": fast_dup} app = await get_workflow_app() initial_state = AgentState( ticket_id=t_id, workspace_id=ws_id, thread_id=thread_id, title=ticket_title, description=ticket_desc, attachments=[], # Ingestion node handles hydration embedding=None, vision_context=[], is_duplicate=False, duplicate_of_id=None, category=ticket_cat, priority=ticket_prio, sentiment=None, assigned_to=None, status=None, suggested_reply=None, internal_summary=None, target_team=None, next_node=None, kb_extracts=[], is_new_topic=False, kb_suggested_solution=None, proposed_insights=[], errors=[], metadata={"force_skip_duplication": kwargs.get("force_skip_duplication", False)}, processed_steps=[] ) from agents.state import merge_dict, merge_list from models.ai_interaction import AIInteraction from core.config import get_settings settings = get_settings() final_state = initial_state.copy() interactions_to_save = [] # Accumulate mid-flight deltas here — one DB write after the stream instead of per-node _pending_sync: dict = {} logger.info(f"STARTING AI WORKFLOW [{v_tag}] for ticket {t_id}") # 2. AI ORCHESTRATION: Primary Stream try: async for event in app.astream( initial_state, config={"configurable": { "force_reroute": kwargs.get("force_reroute", False), "force_skip_duplication": kwargs.get("force_skip_duplication", False), "arq_pool": ctx.get("redis") if isinstance(ctx, dict) else None }}, stream_mode="updates" ): if not event: continue # --- Capture PRE-NODE State for Forensic Input Log --- # We take a lightweight snapshot of the current state before applying node updates node_input_snapshot = { "title": final_state.get("title"), "description": final_state.get("description")[:1000] if final_state.get("description") else None, "category": final_state.get("category"), "priority": final_state.get("priority"), "metadata": final_state.get("metadata"), "errors_count": len(final_state.get("errors", [])), "v_tag": v_tag } for node_name, updates in event.items(): # Manually replicate LangGraph's reducers for the final_state for key, val in updates.items(): if key == "metadata": final_state["metadata"] = merge_dict(final_state.get("metadata"), val) elif key in ["processed_steps", "proposed_insights", "errors"]: final_state[key] = merge_list(final_state.get(key), val) else: final_state[key] = val # Standard overwrite # --- Mid-Flight Delta Accumulation (Resilience Layer) --- # Accumulate critical field updates from each node. A single DB write # is performed after the stream completes — eliminates N per-node sessions. if updates.get("category"): _pending_sync["category"] = updates["category"] if updates.get("priority"): _pending_sync["priority"] = updates["priority"] if updates.get("assigned_to"): _pending_sync["assigned_to"] = updates["assigned_to"] node_meta = updates.get("metadata", {}) if node_meta.get("estimated_effort_hours"): _pending_sync.setdefault("metadata", {}).update({ "estimated_effort_hours": node_meta["estimated_effort_hours"], "complexity": node_meta.get("complexity", "low"), }) # Use sanitize_for_db for the interaction log clean_updates = sanitize_for_db(updates) interactions_to_save.append({ "agent_name": node_name, "input_data": sanitize_for_db(node_input_snapshot), "output_data": clean_updates, "metadata_json": clean_updates.get("metadata", {}) }) logger.info(f"NODE COMPLETE [{v_tag}]: {node_name}") except Exception as stream_err: logger.error(f"AI Stream failed for ticket {t_id}: {stream_err}") # We proceed to save whatever progress we have in the atomic layer # 2b. SINGLE MID-FLIGHT SYNC — one session for all accumulated node deltas if _pending_sync: try: async with async_session_factory() as db: stmt = select(Ticket).where(Ticket.id == t_id) t = (await db.execute(stmt)).scalar_one_or_none() if t: if _pending_sync.get("category"): t.category = _pending_sync["category"] if _pending_sync.get("priority"): t.priority = _pending_sync["priority"] if _pending_sync.get("assigned_to"): try: t.assigned_to = uuid.UUID(str(_pending_sync["assigned_to"])) t.status = TicketStatus.ACKNOWLEDGED except Exception: logger.warning(f"Mid-flight sync: invalid assigned_to value {_pending_sync['assigned_to']}") sync_meta = _pending_sync.get("metadata", {}) if sync_meta.get("estimated_effort_hours"): hours = float(sync_meta["estimated_effort_hours"]) t.estimated_effort_hours = {"value": hours, "complexity": sync_meta.get("complexity", "low")} t.expected_resolution_at = (t.created_at or datetime.utcnow()) + timedelta(hours=hours) await db.commit() logger.debug(f"[NEXUS_RESILIENCE] Single consolidated mid-flight sync complete for ticket {t_id}") except Exception as mse: logger.warning(f"Consolidated mid-flight sync failed: {mse}") # 3. ATOMIC PERSISTENCE LAYER (Merged Phases - BUG-4/ISSUE-1 Fix) # We now use a single session and a single commit for all AI outputs. try: async with async_session_factory() as db: logger.info(f"ATOMIC PERSISTENCE [{v_tag}] for ticket {t_id}") # --- Step A: Re-fetch Ticket --- stmt = select(Ticket).where(Ticket.id == t_id) res = await db.execute(stmt) ticket = res.scalar_one_or_none() if not ticket: raise ValueError("Ticket disappeared during workflow.") # --- Step B: Save AI Interactions --- for inter_data in interactions_to_save: interaction = AIInteraction( workspace_id=ws_id, ticket_id=t_id, agent_name=inter_data["agent_name"], model_info=settings.AI_MODEL, thread_id=thread_id, input_data=inter_data["input_data"], output_data=inter_data["output_data"], status="success", is_automatic=True, metadata_json=inter_data["metadata_json"] ) db.add(interaction) # --- Step C: Triage & Field Enrichment --- hours = final_state.get("metadata", {}).get("estimated_effort_hours") or 1.0 ticket.estimated_effort_hours = {"value": float(hours), "complexity": final_state.get("metadata", {}).get("complexity") or "low"} ticket.expected_resolution_at = (ticket.created_at or datetime.utcnow()) + timedelta(hours=hours) ticket.category = final_state.get("category") or ticket.category or "OTHER" ticket.priority = final_state.get("priority") or ticket.priority or "P2" if final_state.get("assigned_to"): try: ticket.assigned_to = uuid.UUID(str(final_state.get("assigned_to"))) except: pass 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: Marked as duplicate of #{str(ticket.duplicate_of_id)[:8]}." if final_state.get("embedding"): ticket.embedding = final_state.get("embedding") # --- Step D: AI Metadata & Root Cause Analysis --- final_meta = final_state.get("metadata", {}) is_duplicate = final_state.get("is_duplicate") internal_summary = final_state.get("internal_summary") or "Diagnostic analysis complete." # For duplicates, we don't want to pollute with "Under investigation" placeholders # The internal portal will hide the RCA section anyway, but the data should be clean. rca = final_state.get("root_cause_analysis") if not rca: rca = "Marked as duplicate." if is_duplicate else "Under investigation." tech_solution = final_state.get("proposed_technical_solution") if not tech_solution: tech_solution = "See original ticket." if is_duplicate else "Diagnostics in progress." # ── FORENSIC TRAIL FIX ────────────────────────────────────────── # processed_steps are accumulated in final_state by the merge_list reducer # but were never written into ai_metadata — so the frontend always saw an # empty array and displayed "Awaiting initiation...". processed_steps = final_state.get("processed_steps", []) final_meta.update({ "worker_version": v_tag, "processed_steps": processed_steps, # ← Forensic Trail data for the UI "kb_extracts": final_state.get("kb_extracts", []), "summaries": { "internal_summary": internal_summary, "customer_summary": final_state.get("customer_summary") or "Technical analysis is complete. Our specialists are reviewing the findings to provide you with a resolution." }, "initial_analysis": { "rca": rca, "technical_solution": tech_solution, "relevant_article": final_meta.get("cited_sources", [])[0] if final_meta.get("cited_sources", []) else None, "timestamp": datetime.utcnow().isoformat(), "cited_sources": final_meta.get("cited_sources", []) } }) ticket.rca_notes = rca ticket.ai_metadata = final_meta db.add(ticket) # --- Step E: Post-Analysis Message (Debounced) --- if final_state.get("suggested_reply"): from models.message import Message from models.user_workspace import UserWorkspace from models.user import UserRole # Resolve Sender ID (Fallback to first SC_ADMIN if Super Admin missing) sender_stmt = select(User.id).where(User.email == settings.SUPER_ADMIN_EMAIL) sender_id = (await db.execute(sender_stmt)).scalar() if not sender_id: # Fallback: Get first staff member linked to this workspace fallback_stmt = select(User.id).join(UserWorkspace).where( UserWorkspace.workspace_id == ws_id, UserWorkspace.role.in_([UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]) ).limit(1) sender_id = (await db.execute(fallback_stmt)).scalar() if sender_id: ai_note = Message( workspace_id=ws_id, ticket_id=t_id, sender_id=sender_id, is_internal=True, content=( f"### 🛡️ Nexus Initial Analysis\n" f"**Root Cause Analysis (RCA):**\n{rca}\n\n" f"**Proposed Technical Solution:**\n{tech_solution}\n\n" f"---\n" f"**✨ AI Draft Reply for Customer:**\n" f"> {final_state.get('suggested_reply', 'Analysis in progress.')}" ) ) db.add(ai_note) # --- Step F: Knowledge Insights --- for prop in final_state.get("proposed_insights", []): action = prop.get("action") if action == "CREATE_NEW": insight = KnowledgeInsight( workspace_id=ws_id, source_ticket_id=t_id, target_article_id=safe_uuid(prop.get("target_article_id")), insight_type=prop.get("insight_type"), category=prop.get("category"), suggested_title=prop.get("suggested_title"), reasoning=prop.get("reasoning"), suggested_content=final_state.get("kb_suggested_solution") or prop.get("suggested_content"), confidence_score=prop.get("confidence_score", 0.0), embedding=prop.get("embedding"), status=InsightStatus.PENDING ) db.add(insight) await db.flush() db.add(KnowledgeInsightTicket(insight_id=insight.id, ticket_id=t_id, impact_context=prop.get("impact_context"))) elif action in ["UPDATE_EVIDENCE", "UPDATE_AND_MERGE_EVIDENCE"]: i_id = safe_uuid(prop.get("insight_id")) if i_id: from sqlalchemy import update update_vals = {"evidence_count": KnowledgeInsight.evidence_count + 1} # Only update content if merging was successful and provided in payload if action == "UPDATE_AND_MERGE_EVIDENCE": if prop.get("reasoning"): update_vals["reasoning"] = prop["reasoning"] if prop.get("suggested_content"): update_vals["suggested_content"] = prop["suggested_content"] await db.execute( update(KnowledgeInsight) .where(KnowledgeInsight.id == i_id) .values(**update_vals) ) db.add(KnowledgeInsightTicket(insight_id=i_id, ticket_id=t_id, impact_context=prop.get("impact_context"))) # --- Step G: Telemetry (Citation Increments - ISSUE-5 Fix) --- cited = final_meta.get("cited_sources", []) if cited: from models.kb_article import KBArticle from sqlalchemy import update await db.execute(update(KBArticle).where(KBArticle.title.in_(cited), KBArticle.workspace_id == ws_id).values(citation_count=KBArticle.citation_count + 1)) # --- FINAL COMMIT --- await db.commit() logger.info(f"AI SUCCESS [{v_tag}]: Atomic persistence complete.") # --- WebSocket Broadcast: notify connected clients that enrichment is done --- try: from core.websockets import manager await manager.broadcast_to_workspace( workspace_id=ws_id, message={ "type": "ticket_enriched", "ticket_id": str(t_id), "category": ticket.category, "priority": str(ticket.priority) if ticket.priority else None, "assigned_to": str(ticket.assigned_to) if ticket.assigned_to else None, "internal_summary": internal_summary[:300] if internal_summary else None, } ) logger.info(f"[Workflow] WebSocket broadcast sent for ticket {t_id}") except Exception as ws_err: # Non-fatal: broadcast failure must never abort the workflow logger.debug(f"[Workflow] WebSocket broadcast skipped (no active connections or manager unavailable): {ws_err}") # --- 4. Cache Invalidation --- # Ensure fresh ticket details are served after AI enrichment await invalidate_cache(f"ticket:detail:{t_id}") except Exception as e: logger.exception(f"CRITICAL WORKFLOW FAILURE [{v_tag}]: {str(e)}") # Failure Sink: Ensure ticket is at least reachable try: async with async_session_factory() as db: stmt = select(Ticket).where(Ticket.id == t_id) t = (await db.execute(stmt)).scalar_one_or_none() if t: if not t.category or t.category == "PENDING": t.category = "OTHER" if not t.priority: t.priority = "P2" await db.commit() from models.ai_interaction import AIInteraction db.add(AIInteraction( workspace_id=ws_id, ticket_id=t_id, agent_name="workflow_engine", model_info="system", thread_id=thread_id, input_data={}, output_data={"error": str(e)}, status="error", is_automatic=True )) await db.commit() except: pass raise e try: await enqueue_task( ctx.get("redis") if isinstance(ctx, dict) else None, 'auto_summarize_ticket', t_id, manual=True, # Ensure it runs even for immediate duplicates/resolutions _job_id=f"summarize_init_{t_id}" ) except: pass return final_state