diff --git "a/core/tasks.py" "b/core/tasks.py" --- "a/core/tasks.py" +++ "b/core/tasks.py" @@ -1,2050 +1,20 @@ """ -Background task definitions for Arq worker. +Background task definitions for Arq worker. (Refactored to domain-specific modules) """ -import httpx -from typing import Optional, Dict, Any -from uuid import UUID -from datetime import datetime, timedelta -from sqlalchemy import select, func, desc, text, delete, cast, String -from sqlalchemy.exc import OperationalError, InternalError -from core.database import async_session_factory -import asyncio -from core.logging import get_logger - -from models.ticket import Ticket, TicketStatus -from models.notification import Notification -from models.audit_log import AuditLog -from models.escalation_rule import EscalationRule -from models.message import Message -from models.kb_article import KBArticle -from core.llm import get_llm, get_text_embeddings, get_image_embeddings -from core.vision import extract_visual_context, resolve_image -from langchain_core.prompts import ChatPromptTemplate -from langchain.schema import HumanMessage, SystemMessage -from models.attachment import Attachment -from models.meta_infra_health import MetaInfraHealth, ServiceStatus -from models.kb_article_chunk import KBArticleChunk -from models.workspace import Workspace -from core.search import chunk_text -from core.sync import sync_markdown_images -from core.observability import record_workflow_step -from core.config import get_settings -from core.email import send_email -import time -import json - -from core.cache import get_redis_client, get_worker_redis_client, invalidate_cache -from arq.worker import Retry as ArqRetry - -settings = get_settings() - -logger = get_logger(__name__) -_redis_pool = None - -async def get_task_pool(): - global _redis_pool - if _redis_pool is None: - from arq import create_pool - from core.config import get_redis_settings - _redis_pool = await create_pool(get_redis_settings()) - return _redis_pool - -async def check_cron_lock(ctx, task_name: str, window_seconds: int = 60) -> bool: - """ - Prevent cross-replica cron duplication using the shared Postgres database. - Since Hugging Face replicas use local Redis, they cannot de-duplicate via Arq. - Returns True if the task should proceed, False if it's already being handled. - """ - from models.worker_job import WorkerJob, JobStatus - from datetime import datetime, timedelta - from sqlalchemy import select - from agents.utils import get_deterministic_uuid - - # 1. Generate the same stable ID Arq uses for this cron (if available in ctx) - job_id_raw = ctx.get('job_id') - if not job_id_raw: - return True # Cannot lock, proceed safely - - job_id = get_deterministic_uuid(job_id_raw) - - async with async_session_factory() as db: - try: - # Check if another record exists for this specific cron ID that is RUNNING - # or was recently STARTED by another replica. - limit = datetime.utcnow() - timedelta(seconds=window_seconds) - stmt = select(WorkerJob).where( - WorkerJob.id == job_id, - WorkerJob.status == JobStatus.SUCCESS # If it already succeeded, don't re-run - ) - res = await db.execute(stmt) - if res.scalar_one_or_none(): - logger.info(f"⏭️ Skipping {task_name}: Already successfully completed by another replica.") - return False - - # If it's currently RUNNING and was started very recently, assume another replica has it. - stmt = select(WorkerJob).where( - WorkerJob.id == job_id, - WorkerJob.status == JobStatus.RUNNING, - WorkerJob.started_at > limit - ) - res = await db.execute(stmt) - if res.scalar_one_or_none(): - logger.info(f"⏭️ Skipping {task_name}: Already running on another replica.") - return False - - return True - except Exception as e: - logger.warning(f"Cron lock check failed for {task_name}: {e}") - return True - -async def check_job_latch(ctx, entity_id: Any, task_type: str) -> bool: - """ - Implements Latest-Only Job Deduplication. - Checks if a newer job has been enqueued for the same entity and task type. - """ - try: - redis = get_worker_redis_client() - # Arq stores custom kwargs in job_kwargs - job_kwargs = ctx.get('job_kwargs', {}) - enqueue_time = job_kwargs.get('enqueue_time_ms') - - if not enqueue_time: - return True # Cannot verify, proceed safely - - latch_key = f"job_latch:{task_type}:{str(entity_id)}" - - # 1. Update/Set the latest enqueue time for this task - # We use a pipeline or simple set to ensure we mark ourselves as the latest candidate - # But we only DO THIS when the job is enqueued, not when it starts. - # Wait, if we do it when it starts, we might overwrite a newer job that hasn't started yet. - # So the producer should set the latch. - - # For simplicity in this implementation, we check if our enqueue time is still the latest. - # This assumes the producer updates the latch on every enqueue. - latest_time_str = await redis.get(latch_key) - if latest_time_str: - latest_time = int(latest_time_str) - if enqueue_time < latest_time: - logger.info(f"⏭️ Skipping stale job {ctx.get('job_id')} for {task_type}:{entity_id} (Newer job exists)") - return False - - return True - except Exception as e: - logger.warning(f"Job latch check failed: {e}") - return True - -async def enqueue_task(task_or_pool: Any, *args, **kwargs): - """ - Enqueues an ARQ job and updates the deduplication latch in Redis. - Polymorphic: - - Mode A: enqueue_task(pool, "task_name", entity_id, *args) - - Mode B: enqueue_task("task_name", entity_id, *args) - """ - try: - pool_obj = await get_task_pool() - - # 1. Resolve Pool and Task Name - if isinstance(task_or_pool, str): - task_name = task_or_pool - target_pool = pool_obj - final_args = args - else: - target_pool = task_or_pool - if not args: - raise ValueError("enqueue_task(pool, ...) requires a task_name string as the second argument.") - task_name = args[0] - final_args = args[1:] - - # 2. Extract entity_id for deduplication - entity_id = final_args[0] if final_args else "none" - - # 3. Queue Routing Logic - HEAVY_TASKS = [ - "generate_ticket_embedding", "run_ai_workflow", "auto_summarize_ticket", - "index_kb_article", "vectorize_nexus_interaction", "generate_global_insight", - "crystallize_memory", "generate_workspace_insights", "harvest_expertise_task", - "process_kb_import_task" - ] - queue_name = "arq:heavy" if task_name in HEAVY_TASKS else "arq:regular" - - # 4. Redis Latch for latest-only execution - now_ms = int(time.time() * 1000) - latch_key = f"job_latch:{task_name}:{str(entity_id)}" - redis = get_worker_redis_client() - await redis.set(latch_key, now_ms, ex=86400) - - # 5. Metadata and Dispatch - task_kwargs = kwargs.copy() - # HARDENING: Always provide enqueue_time_ms to prevent latch bypass (Issue #7) - task_kwargs['enqueue_time_ms'] = now_ms - task_kwargs['metadata_json'] = { - "entity_id": str(entity_id), - "task_group": queue_name.split(':')[-1], - "enqueued_at": datetime.utcnow().isoformat(), - "latch_key_override": task_name - } - if "thread_id" in task_kwargs: - task_kwargs['metadata_json']["thread_id"] = str(task_kwargs["thread_id"]) - - await target_pool.enqueue_job(task_name, *final_args, _queue_name=queue_name, **task_kwargs) - logger.info(f"📤 Enqueued {task_name} to {queue_name} for {entity_id}") - - except Exception as e: - logger.error(f"Failed to enqueue task: {e}") - -async def auto_summarize_ticket(ctx, ticket_id: UUID, **kwargs): - """ - Background task to generate dual summaries (Internal/Customer). - """ - if not await check_job_latch(ctx, ticket_id, "auto_summarize_ticket"): - return - - # 3-Attempt Retry Logic for Ollama Stability - for attempt in range(1, 4): - try: - async with async_session_factory() as db: - # 1. Fetch Ticket - stmt = select(Ticket).where( - Ticket.id == ticket_id, - Ticket.deleted_at.is_(None) - ) - result = await db.execute(stmt) - ticket = result.scalar_one_or_none() - if not ticket: - return - - # 2. Fetch Messages: Sliding Window (last 10) to prevent context blowout - msg_stmt = select(Message).where( - Message.ticket_id == ticket_id, - Message.deleted_at.is_(None) - ).order_by(Message.created_at.desc()).limit(10) - msg_result = await db.execute(msg_stmt) - messages = list(reversed(msg_result.scalars().all())) - - # --- COOL-OFF OPTIMIZATION --- - # Rule: Only summarize after the 5th message (as per user request) - # UNLESS: It's a manual trigger (manual=True) - is_manual = kwargs.get('manual', False) - msg_count = len(messages) - - if not is_manual: - if msg_count < 5: - logger.debug(f"Skipping auto-summary for ticket {ticket_id}: Initial cool-off ({msg_count} < 5 msgs).") - return - - # Checkpoints every 5 messages - is_checkpoint = (msg_count % 5 == 0) - - # Informative Signal: Detect long technical messages (>500 chars) that warrant an update - last_msg = messages[-1] if messages else None - is_informative = last_msg and len(last_msg.content) > 500 - - if not (is_checkpoint or is_informative): - logger.debug(f"Skipping auto-summary for ticket {ticket_id}: Cool-off active ({msg_count} msgs, not a checkpoint).") - return - else: - logger.info(f"Manual summarization requested for ticket {ticket_id}. Bypassing cool-off logic.") - - # 3. Partition Messages - public_messages = [m for m in messages if not m.is_internal] - - llm = get_llm(timeout=120, is_heavy_task=True) # Elevated timeout - - def format_convo(msg_list): - return "\n".join([f"{'['+'INTERNAL'+'] ' if m.is_internal else ''}{m.sender_id}: {m.content}" for m in msg_list]) - - # 4. Multimodal Resolution: Hardened limit for stability - all_imgs = await extract_visual_context(db, ticket.workspace_id, ticket.description, limit=2) - for m in messages: - if len(all_imgs) >= 3: break - all_imgs.extend(await extract_visual_context(db, ticket.workspace_id, m.content, limit=1)) - - # Final stability slice - all_imgs = all_imgs[:3] - - # Customer Summary - cust_txt = f"Title: {ticket.title}\nDescription: {ticket.description}\n\nConversation:\n{format_convo(public_messages)}" - cust_blocks = [{"type": "text", "text": cust_txt}] - cust_blocks.extend(all_imgs[:5]) - - cust_prompt = [ - SystemMessage(content="You are a support assistant. Summarize for a CUSTOMER. No internal jargon. Max 3 sentences."), - HumanMessage(content=cust_blocks) - ] - - # Internal Summary - intl_txt = f"Title: {ticket.title}\nDescription: {ticket.description}\n\nConversation:\n{format_convo(messages)}" - intl_blocks = [{"type": "text", "text": intl_txt}] - intl_blocks.extend(all_imgs) - - intl_prompt = [ - SystemMessage(content="You are a support lead. Summarize for an INTERNAL AGENT. Use a **Markdown Table** to list key technical facts or recent events if relevant. Include internal notes. Max 4 sentences for text portion."), - HumanMessage(content=intl_blocks) - ] - - try: - cust_resp = await llm.ainvoke(cust_prompt) - intl_resp = await llm.ainvoke(intl_prompt) - summary_data = { - "customer_summary": cust_resp.content, - "internal_summary": intl_resp.content - } - except Exception as sum_err: - logger.error(f"Summarization AI invocation failed: {sum_err}") - # Local fallback if even global resilience fails - summary_data = { - "customer_summary": "Auto-summarization in progress.", - "internal_summary": "Technical analysis in progress (AI provider delay)." - } - - # Persist - meta = dict(ticket.ai_metadata or {}) - meta["summaries"] = summary_data - ticket.ai_metadata = meta - db.add(ticket) - - from core.observability import record_workflow_step - await record_workflow_step( - db, - entity_id=ticket.id, - workspace_id=ticket.workspace_id, - workflow_type="LIFECYCLE", - step_name="AI_SUMMARIZATION_COMPLETE", - output_data=summary_data, - current_stage="CONTEXT_SUMMARIZED" - ) - await db.commit() - - # --- Detail Cache Invalidation --- - await invalidate_cache(f"ticket:detail:{ticket_id}") - - # Real-time Broadcast - from core.websockets import manager - from models.user import UserRole - cust_payload = {"event": "summary_updated", "ticket_id": str(ticket.id), "summary": summary_data.get("customer_summary")} - await manager.broadcast_to_role(ticket.workspace_id, str(UserRole.CUSTOMER_USER.value), cust_payload) - staff_payload = {"event": "summary_updated", "ticket_id": str(ticket.id), "summary": summary_data.get("internal_summary")} - await manager.broadcast_to_role(ticket.workspace_id, str(UserRole.SC_AGENT.value), staff_payload) - - logger.info(f"SUCCESS: Auto-summary generated for ticket {ticket_id} (Attempt {attempt})") - break # Success! - - except (Exception, OperationalError, InternalError) as e: - if attempt < 3: - logger.warning(f"AI Summarization attempt {attempt} failed for {ticket_id}: {str(e)}. Connection might be unstable via tunnel. Retrying...") - await asyncio.sleep(attempt * 5) # Increased backoff - else: - logger.error(f"CRITICAL: All primary summarization attempts failed for {ticket_id}: {str(e)}") - # --- EMERGENCY FALLBACK: Attempt baseline summary using Fast Model --- - try: - logger.info(f"FALLBACK: Attempting emergency generation for {ticket_id} using {settings.AI_FAST_MODEL}") - from core.config import get_settings - fallback_settings = get_settings() - fast_llm = get_llm(model=fallback_settings.AI_FAST_MODEL, timeout=30, is_heavy_task=True) - - # Fetch basic info again to ensure fallback has data context if previous try failed early - async with async_session_factory() as f_db: - f_ticket_stmt = select(Ticket).where(Ticket.id == ticket_id) - f_ticket_res = await f_db.execute(f_ticket_stmt) - f_ticket_obj = f_ticket_res.scalar_one_or_none() - - if not f_ticket_obj: - return - - f_cust_txt = f"Title: {f_ticket_obj.title}\n{f_ticket_obj.description}" - f_intl_txt = f_cust_txt # Simplified for emergency - - # Use text-only prompts for maximum stability in fallback - fallback_cust_prompt = [ - SystemMessage(content="Summarize for CUSTOMER. Plain text. 2 sentences."), - HumanMessage(content=f_cust_txt) - ] - fallback_intl_prompt = [ - SystemMessage(content="Summarize for INTERNAL STAFF. Plain text. 2 sentences."), - HumanMessage(content=f_intl_txt) - ] - - f_cust_resp = await fast_llm.ainvoke(fallback_cust_prompt) - f_intl_resp = await fast_llm.ainvoke(fallback_intl_prompt) - - fallback_data = { - "customer_summary": f_cust_resp.content, - "internal_summary": f_intl_resp.content + " (Fallback Generation)" - } - - f_meta = dict(f_ticket_obj.ai_metadata or {}) - f_meta["summaries"] = fallback_data - f_ticket_obj.ai_metadata = f_meta - f_db.add(f_ticket_obj) - await f_db.commit() - - # Broadcast fallback result - from core.websockets import manager - from models.user import UserRole - await manager.broadcast_to_role(f_ticket_obj.workspace_id, UserRole.SC_AGENT, { - "event": "summary_updated", - "ticket_id": str(f_ticket_obj.id), - "summary": fallback_data["internal_summary"] - }) - logger.info(f"FALLBACK SUCCESS: Baseline summary restored for {ticket_id}") - except Exception as fallback_err: - logger.error(f"FALLBACK FAILED: Emergency generation also crashed for {ticket_id}: {fallback_err}") - -async def crystallize_memory( - ctx, - user_id: UUID, - workspace_id: UUID, - thread_id: Optional[UUID], - history_str: str, - old_summary: str, - old_gist: Dict[str, Any], - **kwargs -): - """ - Hardened AI Distillation Task with nested retry and multi-stage fallback. - """ - from core.llm import get_llm, get_text_embeddings - from langchain_core.prompts import ChatPromptTemplate - from agents.prompts import get_prompt - import json - import re - - logger.info(f"Crystallizing memory for user {user_id} via ARQ...") - - for attempt in range(1, 4): - try: - llm = get_llm(is_heavy_task=True) - embedder = get_text_embeddings() - - # 0) FETCH TECHNICAL SCOPE - from models.ticket import Ticket - from sqlalchemy import select, desc - async with async_session_factory() as db: - scope_stmt = select(Ticket.title, Ticket.category).where(Ticket.assigned_to == user_id, Ticket.deleted_at.is_(None)).order_by(desc(Ticket.created_at)).limit(5) - scope_items = (await db.execute(scope_stmt)).all() - active_scope = "\n".join([f"- {t[0]} [{t[1] or 'Uncategorized'}]" for t in scope_items]) or "No active tickets." - - # A) DISTILL SUMMARY - prompt = ChatPromptTemplate.from_template(get_prompt("memory_distiller")) - new_summary_resp = await (prompt | llm).ainvoke({"old_summary": old_summary, "new_history": history_str}) - new_thread_summary = new_summary_resp.content.strip() - - # B) EXTRACT GIST (Stage 1 or Stage 2) - from schemas.ai import UserIdentityGist - new_gist = old_gist - - try: - # Stage 1: Structured - gist_llm = get_llm(is_heavy_task=True).with_structured_output(UserIdentityGist) - gist_prompt = ChatPromptTemplate.from_template(get_prompt("identity_architect")) - new_gist_obj = await (gist_prompt | gist_llm).ainvoke({"old_gist": json.dumps(old_gist), "new_history": history_str, "active_scope": active_scope}) - new_gist = new_gist_obj.model_dump() - logger.info("✅ Stage 1 Gist extraction successful.") - except Exception as gist_err: - logger.warning(f"⚠️ Stage 1 Failed: {gist_err}. Initiating Stage 2 Raw Parsing...") - raw_prompt = f"Update User Identity Gist JSON.\nOLD: {json.dumps(old_gist)}\nHISTORY: {history_str}\nSCOPE: {active_scope}\nRespond ONLY with valid JSON." - raw_res = await llm.ainvoke(raw_prompt) - json_match = re.search(r'(\{.*\})', raw_res.content, re.DOTALL) - if json_match: - new_gist = json.loads(json_match.group()) - logger.info("✅ Stage 2 recovery successful.") - - new_gist["last_synchronized"] = datetime.utcnow().isoformat() - - # B.2) EXTRACT ATOMIC KNOWLEDGE CRYSTALS (Granular Fact Extraction) - # This is the heart of the AKG (Asynchronous Knowledge Graph) - crystals = [] - try: - crystal_prompt = ( - "Extract 3-5 discrete, atomic facts or insights from this conversation " - "that would be useful for a support lead to remember. Each fact should be " - "self-contained. Return ONLY a JSON list of strings.\n\n" - f"HISTORY: {history_str}" - ) - crystal_res = await llm.ainvoke(crystal_prompt) - json_match = re.search(r'(\[.*\])', crystal_res.content, re.DOTALL) - if json_match: - crystals = json.loads(json_match.group()) - logger.info(f"💎 Extracted {len(crystals)} knowledge crystals.") - except Exception as crystal_err: - logger.warning(f"⚠️ Crystal extraction failed: {crystal_err}") - - # C) ATOMIC PERSISTENCE - async with async_session_factory() as db: - from models.user import User - from models.nexus_interaction import NexusInteraction - from models.nexus_memory import NexusMemory - from models.nexus_thread import NexusThread - from sqlalchemy import update - - # 0.5 Defensive Thread Latch - if thread_id: - t_stmt = select(NexusThread).where(NexusThread.id == thread_id) - t_res = await db.execute(t_stmt) - if not t_res.scalar_one_or_none(): - logger.warning(f"Thread {thread_id} missing during crystallization. Creating recovery record.") - db.add(NexusThread( - id=thread_id, - workspace_id=workspace_id, - user_id=user_id, - title="Recovered Session" - )) - await db.flush() - - await db.execute(update(User).where(User.id == user_id).values(ai_gist=new_gist)) - - gist_str = f"USER_FACTS: {json.dumps(new_gist)}" - fact_vec = await embedder.aembed_query(gist_str) - db.add(NexusMemory(workspace_id=workspace_id, user_id=user_id, thread_id=thread_id, content=gist_str, memory_type="fact", embedding=fact_vec)) - - interaction_vec = await embedder.aembed_query(new_thread_summary) - db.add(NexusMemory(workspace_id=workspace_id, user_id=user_id, thread_id=thread_id, content=new_thread_summary, memory_type="interaction", embedding=interaction_vec)) - - if thread_id: - await db.execute(update(NexusInteraction).where(NexusInteraction.thread_id == thread_id).values(thread_summary=new_thread_summary)) - - # 3. Store individual Knowledge Crystals in the AKG (Batched Embedding) - if crystals: - crystal_vecs = await embedder.aembed_documents(crystals) - for crystal, c_vec in zip(crystals, crystal_vecs): - db.add(NexusMemory( - workspace_id=workspace_id, - user_id=user_id, - thread_id=thread_id, - content=crystal, - memory_type="knowledge_crystal", - embedding=c_vec - )) - - await db.commit() - logger.info(f"SUCCESS: Crystallization + AKG update complete (Attempt {attempt})") - break - except (Exception, OperationalError, InternalError) as e: - if attempt < 3: - logger.warning(f"Crystallization attempt {attempt} failed: {e}. Connection may be unstable via tunnel. Retrying...") - await asyncio.sleep(attempt * 7) - else: - logger.error(f"FAILURE: All crystallization attempts failed: {e}. Triggering emergency fallback summary.") - try: - # 4. EMERGENCY FALLBACK - fast_llm = get_llm(use_fast_model=True, timeout=30) - prompt = ChatPromptTemplate.from_template("Summarize these support interactions briefly for an agent memory file: {new_history}") - fallback_res = await (prompt | fast_llm).ainvoke({"new_history": history_str}) - new_thread_summary = fallback_res.content.strip() + " (Fallback Distillation)" - - # Store minimal Gist to prevent crash - async with async_session_factory() as db: - interaction_vec = await embedder.aembed_query(new_thread_summary) - from models.nexus_memory import NexusMemory - from models.nexus_interaction import NexusInteraction - from sqlalchemy import update - db.add(NexusMemory(workspace_id=workspace_id, user_id=user_id, thread_id=thread_id, content=new_thread_summary, memory_type="interaction", embedding=interaction_vec)) - if thread_id: - await db.execute(update(NexusInteraction).where(NexusInteraction.thread_id == thread_id).values(thread_summary=new_thread_summary)) - await db.commit() - logger.info(f"FALLBACK SUCCESS: Basic memory persisted for {user_id}") - except Exception as final_err: - logger.error(f"CRITICAL: Emergency fallback also failed for crystallization: {final_err}") - -def truncate_content(text: str, max_chars: int = 15000) -> str: - """ - Ensures content stays within a safe character limit for LLM processing, - approximating token limits (1 token ~= 4 chars). - """ - if not text: - return "" - if len(text) <= max_chars: - return text - return text[:max_chars] + "\n\n... [Content Truncated due to Length] ..." - -async def index_kb_article(ctx, article_id: UUID, **kwargs): - """ - Durable ARQ worker task for full KB indexing lifecycle: - Syncing images, Categorization, Embedding, Chunking, Vision, Duplicate detection, and Summary. - """ - if not await check_job_latch(ctx, article_id, "index_kb_article"): - return - - start_time = time.perf_counter() - async with async_session_factory() as db: - try: - # 1. Fetch Article (Optimized: No long-held lock) - stmt = select(KBArticle).where( - KBArticle.id == article_id, - KBArticle.deleted_at.is_(None) - ) - res = await db.execute(stmt) - article = res.scalar_one_or_none() - if not article: - logger.error(f"Unified KB Indexing failed: Article {article_id} not found.") - return - - # --- PHASE 0: Hash & Fast-Path Deduplication (GAP-DEDUP) --- - if not article.content_hash: - import hashlib - payload_str = f"{(article.title or '').strip()}|{(article.content or '').strip()}" - article.content_hash = hashlib.sha256(payload_str.encode('utf-8')).hexdigest() - db.add(article) - await db.commit() - - # Fast-path check for identical content in this workspace - dup_stmt = select(KBArticle.id).where( - KBArticle.workspace_id == article.workspace_id, - KBArticle.content_hash == article.content_hash, - KBArticle.id != article.id, - KBArticle.deleted_at.is_(None) - ).limit(1) - dup_res = await db.execute(dup_stmt) - fast_dup = dup_res.scalar() - - if fast_dup and not article.force_original: - logger.info(f"PHASE 0 [Fast-Dedup] Identical match for {article_id} -> {fast_dup}") - # Update with lock - article.duplicate_of_id = fast_dup - article.is_published = False - db.add(article) - await db.commit() - return # Fast exit - - # --- 2. Multi-Model Initialization --- - text_model = get_text_embeddings() - llm = get_llm() - - async def _abort_if_deleted(): - async with async_session_factory() as chk_db: - _chk = await chk_db.execute(select(KBArticle.deleted_at).where(KBArticle.id == article_id)) - if _chk.scalar() is not None: - logger.warning(f"KB Indexing Aborted: Article {article_id} was deleted.") - return True - return False - - phases_succeeded = [] - phases_failed = [] - is_transient = lambda e: any(err in str(e) for err in ["502", "503", "504", "ConnectionReset", "Timeout", "RemoteDisconnected"]) - - # --- PHASE 1: Sync Markdown Images --- - try: - await sync_markdown_images(db, article.id, article.workspace_id, article.content, entity_type="article", uploader_id=article.author_id) - if await _abort_if_deleted(): return - await db.commit() - phases_succeeded.append("PHASE 1 [Images]") - logger.debug(f"PHASE 1 [Images] Complete for {article_id}") - except Exception as e: - logger.error(f"PHASE 1 [Images] Failed for {article_id}: {e}") - phases_failed.append("PHASE 1 [Images]") - await db.rollback() - - # --- PHASE 2: Core Embeddings (Idempotent) --- - if article.embedding is None: - try: - text_to_embed = truncate_content(f"{article.title} {article.content}", 8000) - logger.info(f"PHASE 2 [Embeddings] Generating for {article_id}") - vector = await text_model.aembed_query(text_to_embed) - - if vector and len(vector) == settings.AI_EMBEDDING_DIM: - # Re-fetch with lock for write - await db.refresh(article) - article.embedding = vector - db.add(article) - await db.commit() - phases_succeeded.append("PHASE 2 [Embeddings]") - else: - raise ValueError(f"Dim mismatch: {len(vector) if vector else 0}") - except Exception as e: - logger.error(f"PHASE 2 [Embeddings] Failed for {article_id}: {str(e)}") - phases_failed.append("PHASE 2 [Embeddings]") - await db.rollback() - if is_transient(e): - # Use ARQ's native retry (NOT RuntimeError) for proper job reschedule. - # Exponential backoff: attempt 1→30s, 2→60s, 3→120s. - retry_num = ctx.get("job_try", 1) - backoff = min(30 * (2 ** (retry_num - 1)), 120) - logger.warning(f"PHASE 2 transient failure for {article_id} (attempt {retry_num}). Retrying in {backoff}s.") - raise ArqRetry(defer=backoff) - else: - logger.info(f"PHASE 2 [Embeddings] Already present for {article_id}, skipping.") - phases_succeeded.append("PHASE 2 [Embeddings] (Cached)") - - # --- PHASE 3: Chunking (Idempotent) --- - chunk_check = await db.execute(select(func.count(KBArticleChunk.id)).where(KBArticleChunk.article_id == article_id)) - if chunk_check.scalar() == 0: - try: - raw_chunks = chunk_text(article.content, chunk_size=1200, chunk_overlap=200) - for i, text_content in enumerate(raw_chunks): - processed_text = text_content - if "```mermaid" in text_content.lower() or "```json" in text_content.lower(): - try: - enrich_res = await llm.ainvoke(f"Summarize this block in one sentence for indexing:\n{text_content[:1500]}") - if enrich_res and enrich_res.content: - processed_text = f"[NAV: {enrich_res.content.strip()}]\n" + text_content - except: pass - - chunk_vector = await text_model.aembed_query(f"{article.title}: {processed_text}") - db.add(KBArticleChunk(article_id=article.id, content=processed_text, chunk_index=i, embedding=chunk_vector)) - - if await _abort_if_deleted(): return - await db.commit() - phases_succeeded.append("PHASE 3 [Chunking]") - except Exception as e: - logger.error(f"PHASE 3 [Chunking] Failed: {e}") - phases_failed.append("PHASE 3 [Chunking]") - await db.rollback() - if is_transient(e): - retry_num = ctx.get("job_try", 1) - backoff = min(30 * (2 ** (retry_num - 1)), 120) - logger.warning(f"PHASE 3 transient failure for {article_id} (attempt {retry_num}). Retrying in {backoff}s.") - raise ArqRetry(defer=backoff) - else: - logger.info(f"PHASE 3 [Chunking] Already present for {article_id}, skipping.") - phases_succeeded.append("PHASE 3 [Chunking] (Cached)") - - # --- PHASE 4: Auto-Categorization --- - if not article.category or article.category in ["N/A", "General", "Imported"]: - try: - cat_stmt = select(KBArticle.category).where(KBArticle.workspace_id == article.workspace_id, KBArticle.deleted_at.is_(None)).distinct() - cat_res = await db.execute(cat_stmt) - existing_cats = [c for c in cat_res.scalars().all() if c and c not in ["N/A", "General", "Imported"]] - cat_prompt = f"Categorize this article. Existing: {', '.join(existing_cats)}\nTitle: {article.title}\nReturn ONLY the category name." - cat_res = await llm.ainvoke(cat_prompt) - if cat_res and cat_res.content: - await db.refresh(article) - article.category = cat_res.content.strip().title() - db.add(article) - await db.commit() - phases_succeeded.append("PHASE 4 [Category]") - except Exception as e: - logger.error(f"PHASE 4 Failed: {e}") - phases_failed.append("PHASE 4 [Category]") - await db.rollback() - - # --- PHASE 5: Attachment Indexing --- - try: - att_stmt = select(Attachment).where(Attachment.article_id == article.id, Attachment.deleted_at.is_(None)) - att_res = await db.execute(att_stmt) - attachments = att_res.scalars().all() - for att in attachments: - if att.content_type and att.content_type.startswith("image/") and not att.embedding: - img_data = await resolve_image(db, article.workspace_id, str(att.id)) - if img_data: - img_model = get_image_embeddings() - att.embedding = await img_model.aembed_image(img_data) - db.add(att) - await db.commit() - phases_succeeded.append("PHASE 5 [Multimodal]") - except Exception as e: - logger.error(f"PHASE 5 Failed: {e}") - phases_failed.append("PHASE 5 [Multimodal]") - await db.rollback() - - # --- PHASE 6: Duplicate Detection (Optimized Issue #5) --- - if article.embedding is not None and article.duplicate_of_id is None: - try: - # PROJECT DISTANCE: Avoid N+1 (Issue #5) - dup_stmt = ( - select(KBArticle, (KBArticle.embedding.cosine_distance(article.embedding)).label("dist")) - .where(KBArticle.workspace_id == article.workspace_id, KBArticle.id != article.id, - KBArticle.is_published, KBArticle.duplicate_of_id.is_(None), KBArticle.deleted_at.is_(None)) - .order_by("dist") - .limit(1) - ) - dup_res = await db.execute(dup_stmt) - hit = dup_res.first() - # Hardened Threshold: Change from 0.3 (aggressive) to 0.1 (strict) - # 0.1 distance = 0.9 similarity. This prevents distinct but related topics from colliding. - if hit and hit.dist <= 0.1: - await db.refresh(article) - article.duplicate_of_id = hit.KBArticle.id - article.is_published = False - db.add(article) - await db.commit() - logger.info(f"PHASE 6 [Deduplication] Hit: {hit.KBArticle.id}") - except Exception as e: - logger.error(f"PHASE 6 Failed: {e}") - await db.rollback() - - # --- PHASE 7: Summarization --- - if not article.summary: - try: - article_imgs = await extract_visual_context(db, article.workspace_id, article.content, limit=5) - content_txt = f"Title: {article.title}\n\nContent:\n{truncate_content(article.content, 12000)}" - content_blocks = [{"type": "text", "text": content_txt}] - if article_imgs: content_blocks.extend(article_imgs) - - resp = await llm.ainvoke([ - SystemMessage(content="Summarize this technical article in 2-3 sentences. Plain text only, no code."), - HumanMessage(content=content_blocks) - ]) - await db.refresh(article) - article.summary = resp.content - db.add(article) - await db.commit() - phases_succeeded.append("PHASE 7 [Summarization]") - except Exception as e: - logger.error(f"PHASE 7 Failed: {e}") - phases_failed.append("PHASE 7 [Summarization]") - await db.rollback() - - # --- Trace Recording --- - await record_workflow_step( - db, article_id, article.workspace_id, "LIFECYCLE", "KB_INDEXING_COMPLETE", - output_data={"succeeded": phases_succeeded, "failed": phases_failed}, - current_stage="READY_FOR_SEARCH", duration_ms=(time.perf_counter() - start_time) * 1000 - ) - await db.commit() - logger.info(f"SUCCESS: KB indexing finished for {article_id}. Status: {'DEGRADED' if phases_failed else 'SUCCESS'}") - - except Exception as e: - await db.rollback() - logger.error(f"CRITICAL: KB indexing crashed for {article_id}: {str(e)}") - raise e - -async def send_triple_notification(ctx, user_id: UUID, workspace_id: UUID, title: str, message: str, link: Optional[str] = None, **kwargs): - """Send notification to DB, real-time WebSocket, and simulated Email.""" - async with async_session_factory() as db: - # 1. Fetch User Emails (Priority Routing: real_email -> primary_email) - from models.user import User - user_stmt = select(User.email, User.real_email).where(User.id == user_id) - u_res = (await db.execute(user_stmt)).first() - - primary_email, real_email = u_res if u_res else (None, None) - delivery_target = real_email or primary_email - - - # 2. DB Persistence - notification = Notification( - workspace_id=workspace_id, - user_id=user_id, - title=title, - message=message, - link=link - ) - db.add(notification) - await db.commit() - - # 3. WebSocket Real-time (Targeted Delivery) - # We no longer broadcast to the whole workspace to prevent cross-user alerts - from core.websockets import manager - await manager.send_to_user(user_id, { - "type": "notification", - "id": str(notification.id), - "title": title, - "message": message, - "link": link, - "created_at": datetime.utcnow().isoformat() - }) - - # 4. Email Notification (Hardened Delivery) - if delivery_target: - from core.email import template_nexus_email - from core.config import get_settings - app_settings = get_settings() - - # Construct deep link for the resource - resource_url = None - if link: - if link.startswith('http'): - resource_url = link - else: - resource_url = f"{app_settings.effective_frontend_url}/{link.lstrip('/')}" - - email_html = template_nexus_email( - title=title, - message=message, - action_link=resource_url, - action_label="View Details", - footer_note=f"Workspace: {workspace_id} | Security Alert level: High" - ) - - email_text = f"Hello,\n\n{message}\n\nAccess it here: {resource_url if resource_url else 'N/A'}\n\nThis is an automated operational alert from Nexus AI." - await send_email(delivery_target, title, email_text, html_body=email_html) - - - # 5. External Webhook (Slack/Discord) - REAL WORLD DELIVERY - from core.config import get_settings - settings = get_settings() - if settings.NOTIFICATION_WEBHOOK_URL: - try: - import httpx - async with httpx.AsyncClient() as client: - # Generic Webhook Payload (Works for Slack/Discord) - payload = { - "content" if "discord" in settings.NOTIFICATION_WEBHOOK_URL.lower() else "text": - f"🔔 *{title}*\n{message}\n{link if link else ''}" - } - await client.post(settings.NOTIFICATION_WEBHOOK_URL, json=payload, timeout=5.0) - logger.info("Real notification pushed to external webhook.") - except Exception as w_err: - logger.error(f"Failed to push external webhook: {w_err}") - - logger.info(f"Triple notification sent to user {user_id} ({delivery_target})") - -async def notify_mentions(ctx, workspace_id: UUID, title: str, mentions: list, ticket_id: Optional[UUID] = None, **kwargs): - """ - Background task to notify multiple users about a mention. - mentions: list of dicts [{"user_id": "...", "name": "..."}] - """ - link = f"/dashboard?ticket={ticket_id}" if ticket_id else None - logger.info(f"Triggering mention notifications for workspace {workspace_id} on ticket {ticket_id}. Targets: {[m['user_id'] for m in mentions]}") - for mention in mentions: - user_id = UUID(mention["user_id"]) if isinstance(mention["user_id"], str) else mention["user_id"] - await send_triple_notification( - ctx, - user_id=user_id, - workspace_id=workspace_id, - title=title, - message=f"You were mentioned in a ticket message: {title}", - link=link - ) - logger.info(f"Mention notifications sent to {len(mentions)} users") - -async def monitor_sla_thresholds(ctx, *args, **kwargs): - """ - Periodic task to check for SLA breaches and apply escalation rules. - Runs every 5 minutes (configured in worker.py). - """ - if not await check_cron_lock(ctx, "monitor_sla_thresholds", window_seconds=120): - return - - from core.logging import get_logger - from nexus_worker import log_memory_usage - logger.info("Starting SLA monitoring check...") - log_memory_usage("SLA_Monitor_Start") - async with async_session_factory() as db: - now = datetime.utcnow() - # BATCH FETCH: Find potential breaches (capped at 500 per run for memory safety) - stmt = ( - select(Ticket, EscalationRule) - .join(EscalationRule, (EscalationRule.workspace_id == Ticket.workspace_id) & (EscalationRule.priority_level == cast(Ticket.priority, String))) - .where( - Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED]), - Ticket.deleted_at.is_(None), - Ticket.is_escalated.is_(None), - EscalationRule.is_active - ) - .limit(500) - ) - result = await db.execute(stmt) - breached_candidates = result.all() - log_memory_usage("SLA_Candidates_Loaded") - - # 2. MANAGER PRE-FETCH: Avoid N+1 lookups inside the loop - manager_cache = {} - ws_ids = list({t.workspace_id for t, r in breached_candidates}) - - # We fill the cache only once per run - from agents.utils import get_workspace_manager - manager_lookups = [get_workspace_manager(db, ws_id) for ws_id in ws_ids] - managers = await asyncio.gather(*manager_lookups) - for ws_id, mgr in zip(ws_ids, managers): - manager_cache[ws_id] = mgr - - # 3. STREAMING PROCESSING: Iterate directly on result to save memory - notification_tasks = [] - redis = get_redis_client() - - count = 0 - for ticket, rule in breached_candidates: - try: - count += 1 - # Handle potential offset-naive datetimes from DB - threshold_time = ticket.created_at.replace(tzinfo=None) - age_minutes = (now - threshold_time).total_seconds() / 60 - minutes_remaining = rule.threshold_minutes - age_minutes - - manager_user = manager_cache.get(ticket.workspace_id) - - # CASE A: ACTUAL BREACH (Escalation) - if age_minutes >= rule.threshold_minutes: - logger.warning(f"SLA Breach: Ticket {ticket.id} officially breached Rule: {rule.name}") - - if manager_user: - notification_tasks.append(send_triple_notification( - ctx, manager_user.id, ticket.workspace_id, - "🚨 SLA BREACHED: Immediate Intervention Required", - f"Ticket '{ticket.title}' (Priority: {ticket.priority}) has exceeded its SLA threshold of {rule.threshold_minutes} minutes.", - link=f"/dashboard?ticket={ticket.id}" - )) - # MARK AS ESCALATED - ticket.is_escalated = now - db.add(ticket) - await invalidate_cache(f"ticket:detail:{ticket.id}") - db.add(AuditLog( - workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id, - action="SLA_ESCALATION", user_id=None, new_value={"rule": rule.name} - )) - else: - logger.warning(f"SLA Breach: No Lead/Admin found for workspace {ticket.workspace_id}") - - # CASE B: PROACTIVE WARNING (T-minus 2 Hours) - elif 0 <= minutes_remaining <= 120: - warning_latch = f"notified_sla_pre_breach_2h:{str(ticket.id)}" - if not await redis.get(warning_latch) and manager_user: - notification_tasks.append(send_triple_notification( - ctx, manager_user.id, ticket.workspace_id, - "⚠️ CRITICAL WARNING: SLA Breach in 2 Hours", - f"Ticket '{ticket.title}' is approaching its SLA threshold. Approximately {int(minutes_remaining)} minutes remain.", - link=f"/dashboard?ticket={ticket.id}" - )) - await redis.set(warning_latch, "1", ex=86400) - db.add(AuditLog( - workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id, - action="SLA_PRE_BREACH_WARNING", user_id=None, new_value={"rule": rule.name} - )) - - except Exception as e: - logger.error(f"SLA Monitor: Failed to process ticket {ticket.id}: {e}") - - if count % 50 == 0: - # Commit after each batch to release DB locks and persist partial progress - await db.commit() - # Execute notifications in sub-batches to prevent event loop saturation - if notification_tasks: - sub_size = 10 - for j in range(0, len(notification_tasks), sub_size): - await asyncio.gather(*notification_tasks[j:j+sub_size], return_exceptions=True) - notification_tasks = [] - - # Final cleanup for remaining items - await db.commit() - if notification_tasks: - sub_size = 10 - for j in range(0, len(notification_tasks), sub_size): - await asyncio.gather(*notification_tasks[j:j+sub_size], return_exceptions=True) - - -async def ai_dynamic_nudge_pulse(ctx, **kwargs): - """ - Proactive AI Nudge: Identifies tickets at >75% SLA and posts resolution advice. - Runs periodically to prevent breaches. - """ - logger.info("Starting AI Dynamic Nudge pulse...") - async with async_session_factory() as db: - now = datetime.utcnow() - - # 1. Fetch tickets at 75% - 99% SLA - stmt = ( - select(Ticket, EscalationRule) - .join(EscalationRule, (EscalationRule.workspace_id == Ticket.workspace_id) & (EscalationRule.priority_level == cast(Ticket.priority, String))) - .where( - Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED]), - Ticket.deleted_at.is_(None), - Ticket.is_escalated.is_(None) - ) - ) - result = await db.execute(stmt) - candidates = result.all() - - for ticket, rule in candidates: - age_mins = (now - ticket.created_at.replace(tzinfo=None)).total_seconds() / 60 - threshold = rule.threshold_minutes - - # If between 75% and 100% of the SLA threshold - if age_mins >= (threshold * 0.75) and age_mins < threshold: - # Check if we already nudged about this (prevent spam) - if (ticket.ai_metadata or {}).get("last_nudge_at"): - continue - - logger.info(f"AI NUDGE: Ticket {ticket.id} reached 75% SLA. Generating proactive note.") - - # 2. Invoke LLM for specific resolution advice (Context Window: 5) - llm = get_llm() - msg_stmt = select(Message).where(Message.ticket_id == ticket.id).order_by(Message.created_at.desc()).limit(5) - msgs = list(reversed((await db.execute(msg_stmt)).scalars().all())) - convo = "\n".join([f"{m.sender_id}: {m.content}" for m in msgs]) - - prompt = [ - SystemMessage(content=f"You are a Senior Support Engineer. This ticket is at 75% of its SLA ({threshold} min limit). Provide a GENTLE but TECHNICAL internal nudge to the assigned agent to help them resolve this faster. Max 2 sentences."), - HumanMessage(content=f"Title: {ticket.title}\nDescription: {ticket.description}\nRecent Conversation:\n{convo}") - ] - resp = await llm.ainvoke(prompt) - - # 3. Post Internal Message - nudge_msg = Message( - workspace_id=ticket.workspace_id, - ticket_id=ticket.id, - sender_id=UUID("00000000-0000-0000-0000-000000000000"), # System/AI - content=f"🤖 **AI SLA Nudge**: {resp.content}", - is_internal=True - ) - db.add(nudge_msg) - - # 4. Update Metadata to avoid double nudges - meta = dict(ticket.ai_metadata or {}) - meta["last_nudge_at"] = now.isoformat() - ticket.ai_metadata = meta - db.add(ticket) - await invalidate_cache(f"ticket:detail:{ticket.id}") - - await db.commit() - -async def execute_remediation_hook(ctx, ticket_id: str, hook_id: str, **kwargs): - """Execute a specific remediation action safely in the background.""" - from models.remediation import RemediationHook, RemediationActionType - - async with async_session_factory() as db: - ticket_stmt = select(Ticket).where( - Ticket.id == UUID(ticket_id), - Ticket.deleted_at.is_(None) - ) - hook_stmt = select(RemediationHook).where(RemediationHook.id == UUID(hook_id)) - - ticket = (await db.execute(ticket_stmt)).scalar_one_or_none() - hook = (await db.execute(hook_stmt)).scalar_one_or_none() - - if not ticket or not hook: - return - - logger.info(f"Executing remediation hook {hook.trigger_category} for ticket {ticket.id}") - - import httpx - if hook.action_type == RemediationActionType.WEBHOOK: - async with httpx.AsyncClient() as client: - try: - # Replace placeholders in template - payload_str = str(hook.payload_template).replace("{{ticket_id}}", str(ticket.id)) - - # Hardening: Check if payload is valid JSON or needs to be wrapped - try: - payload = json.loads(payload_str) - except ValueError: - payload = {"ticket_id": str(ticket.id), "raw": payload_str} - - resp = await client.post(hook.target, json=payload, timeout=10.0) - if resp.status_code >= 400: - logger.error(f"Remediation webhook {hook.target} failed with status {resp.status_code}") - return # Abort resolution on failure - - logger.info(f"Webhook {hook.target} responded with {resp.status_code}") - except Exception as e: - logger.error(f"Failed to trigger remediation webhook: {str(e)}") - return # Abort resolution on exception - - # Mark ticket as resolved ONLY after successful remediation action - ticket.status = TicketStatus.RESOLVED - db.add(ticket) - await db.commit() - await invalidate_cache(f"ticket:detail:{ticket_id}") - logger.info(f"Remediation successful: Ticket {ticket_id} resolved via hook {hook_id}") - -async def nexus_pulse_check(ctx, *args, **kwargs): - """ - Proactive AI "Pulse" Nudge. - Runs every 15 minutes to survey workspaces for anomalies (like an SLA breach cluster) - and pushes alerts live to the internal staff UI. - """ - if not await check_cron_lock(ctx, "nexus_pulse_check", window_seconds=300): - return - - logger.info("Executing Proactive AI Pulse Check...") - from core.websockets import manager - - async with async_session_factory() as db: - # 1. Get only workspaces that have had ticket updates in the last 15 minutes - # This prevents scanning thousands of stale tenants and triggering watchdogs. - fifteen_mins_ago = datetime.utcnow() - timedelta(minutes=15) - stmt = ( - select(Ticket.workspace_id) - .where(Ticket.updated_at >= fifteen_mins_ago) - .distinct() - ) - workspaces = (await db.execute(stmt)).scalars().all() - - if not workspaces: - logger.info("Pulse Check: No active workspaces to survey.") - return - - async def process_workspace(w_id): - try: - # 2. Heuristic: Spike in critical SLA breaches - sla_breach_count = ( - await db.execute( - select(func.count(Ticket.id)) - .where( - Ticket.workspace_id == w_id, - Ticket.priority == "P0", - Ticket.status != "CLOSED", - Ticket.updated_at >= fifteen_mins_ago - ) - ) - ).scalar() or 0 - - # If anomaly detected - if sla_breach_count >= 3: - alert_payload = { - "type": "NEXUS_PULSE_ALERT", - "level": "critical", - "title": "Anomaly Detected", - "message": f"{sla_breach_count} urgent tickets updated in the last 15 minutes. Potential cascading failure." - } - - # Broadcasters to staff roles - await asyncio.gather( - manager.broadcast_to_role(w_id, "3sc_admin", alert_payload), - manager.broadcast_to_role(w_id, "3sc_lead", alert_payload), - return_exceptions=True - ) - logger.info(f"Broadcasted Pulse Anomaly for workspace: {w_id}") - except Exception as e: - logger.error(f"Pulse Check: Failed to survey workspace {w_id}: {e}") - - # Process each workspace sequentially to avoid SQLAlchemy session deadlocks - for w_id in workspaces: - await process_workspace(w_id) - -async def generate_ticket_embedding(ctx, ticket_id: UUID, **kwargs): - """ - Background task to generate vector embeddings for a ticket's content. - Enables semantic search and similarity matching. - """ - import time - from models.ai_interaction import AIInteraction - from core.config import get_settings - settings = get_settings() - - start_time = time.perf_counter() - - async with async_session_factory() as db: - stmt = select(Ticket).where( - Ticket.id == ticket_id, - Ticket.deleted_at.is_(None) - ) - result = await db.execute(stmt) - ticket = result.scalar_one_or_none() - - if not ticket: - logger.error(f"Generate Ticket Embedding: Ticket {ticket_id} not found.") - return - - # Prepare content: Title + Description - text_to_embed = f"{ticket.title}\n\n{ticket.description}" - start_time = time.perf_counter() - - try: - from core.observability import record_workflow_step - from core.sync import sync_markdown_images - - # --- 0. Sync Markdown Images --- - sync_start = time.perf_counter() - await sync_markdown_images(db, ticket.id, ticket.workspace_id, ticket.description, entity_type="ticket", uploader_id=ticket.created_by) - await record_workflow_step( - db, ticket.id, ticket.workspace_id, "LIFECYCLE", - "IMAGE_SYNC_COMPLETE", - input_data={"content_len": len(ticket.description)}, - duration_ms=(time.perf_counter() - sync_start) * 1000 - ) - - vector = None - try: - # --- 1. Textual Embedding --- - embed_start = time.perf_counter() - logger.info(f"Generating embedding for ticket {ticket_id}...") - text_model = get_text_embeddings() - vector = await text_model.aembed_query(text_to_embed) - ticket.embedding = vector - db.add(ticket) - await record_workflow_step( - db, ticket.id, ticket.workspace_id, "LIFECYCLE", - "TEXT_EMBEDDING_GEN", - duration_ms=(time.perf_counter() - embed_start) * 1000 - ) - except Exception as e_err: - logger.error(f"Textual embedding failed for ticket {ticket_id}: {e_err}") - - # --- 1.5 Duplicate Check (Threshold 0.7) - # BUG-1 Fix: The entire duplicate-check block MUST live inside the `else` - # branch. Previously dup_res/match ran unconditionally at the outer try level, - # causing NameError (dup_start undefined) whenever vector generation failed. - if vector is None: - logger.warning(f"Skipping duplicate check for ticket {ticket_id}: Textual embedding failed.") - else: - dup_start = time.perf_counter() - from sqlalchemy import desc - dup_stmt = ( - select( - Ticket, - (1 - Ticket.embedding.cosine_distance(vector)).label("sim_score") - ) - .where( - Ticket.workspace_id == ticket.workspace_id, - Ticket.id != ticket.id, - Ticket.deleted_at.is_(None), - Ticket.duplicate_of_id.is_(None), - Ticket.embedding.isnot(None) - ) - .order_by(desc("sim_score")) - .limit(1) - ) - dup_res = await db.execute(dup_stmt) - match = dup_res.first() - - dup_status = "no_match" - if match and match.sim_score >= 0.7: - ticket.duplicate_of_id = match.Ticket.id - ticket.status = TicketStatus.CLOSED - ticket.resolved_at = datetime.utcnow() - ticket.resolution_text = f"Automated Detection: This ticket has been identified as a duplicate of ticket #{str(match.Ticket.id)[:8]} ({match.Ticket.title})." - dup_status = "duplicate_found" - - # Log this as an automated action - audit = AuditLog( - workspace_id=ticket.workspace_id, - entity_type="ticket", - entity_id=ticket.id, - action="AI_AUTO_CLOSE_DUPLICATE", - user_id=None, # System action - old_value={"status": TicketStatus.OPEN}, - new_value={ - "status": TicketStatus.CLOSED, - "duplicate_of": str(match.Ticket.id), - "resolution": ticket.resolution_text - } - ) - db.add(audit) - logger.info(f"Duplicate Ticket detected: {ticket.id} clones {match.Ticket.id} (score: {match.sim_score}). Auto-closed with metadata.") - - await record_workflow_step( - db, ticket.id, ticket.workspace_id, "LIFECYCLE", - "DUPLICATE_DETECTION", - output_data={"status": dup_status, "max_score": float(match.sim_score) if match else 0.0}, - duration_ms=(time.perf_counter() - dup_start) * 1000 - ) - - # --- 2. Multimodal Attachment Indexing --- - # Fetch all image attachments for this ticket that haven't been processed - att_stmt = select(Attachment).where( - Attachment.ticket_id == ticket_id, - Attachment.content_type.like("image/%"), - Attachment.is_processed.is_(False) - ) - att_res = await db.execute(att_stmt) - attachments = att_res.scalars().all() - - if attachments: - logger.info(f"Indexing {len(attachments)} images for ticket {ticket_id}...") - llm = get_llm() - for att in attachments: - try: - # A. Generate Text Caption - # We use the existing resolve_image helper to get Base64 - resolved = await resolve_image(db, ticket.workspace_id, str(att.id)) - if resolved: - try: - caption_prompt = [ - SystemMessage(content="Describe this support ticket image/screenshot briefly (1-2 sentences). Focus on technical errors or UI state."), - HumanMessage(content=[resolved]) - ] - caption_res = await llm.ainvoke(caption_prompt) - if caption_res: - att.ai_caption = caption_res.content - except Exception as cap_err: - logger.warning(f"Vision Caption failed for {att.id}: {cap_err}") - - att.is_processed = True - db.add(att) - except Exception as img_err: - logger.error(f"Failed to process attachment metadata for {att.id}: {img_err}") - - # Log this as a system AI interaction - duration_ms = (time.perf_counter() - start_time) * 1000 - interaction = AIInteraction( - workspace_id=ticket.workspace_id, - ticket_id=ticket.id, - agent_name="system:multimodal_indexing", - model_info=f"{settings.AI_TEXT_EMBEDDING_MODEL} + {settings.AI_IMAGE_EMBEDDING_MODEL}", - input_data={"text_length": len(text_to_embed), "img_count": len(attachments)}, - output_data={"status": "completed"}, - duration_ms={"total": round(duration_ms, 2)}, - is_automatic=True - ) - db.add(interaction) - - # --- 3. Record Completion Trace --- - await record_workflow_step( - db, ticket.id, ticket.workspace_id, "LIFECYCLE", - "TICKET_INDEXING_COMPLETE", - output_data={"text_length": len(text_to_embed), "img_count": len(attachments), "duration_ms": round(duration_ms, 2)}, - current_stage="READY_FOR_SEARCH" - ) - - await db.commit() - logger.info(f"Ticket {ticket.id} indexing complete and traced.") - except Exception as e: - logger.error(f"Failed to generate multimodal embedding for ticket {ticket_id}: {str(e)}") - -async def record_system_heartbeat(ctx, *args, **kwargs): - """ - Periodic task to record infrastructure health snapshots. - Runs every 5 minutes (configured in nexus_worker.py). - """ - if not await check_cron_lock(ctx, "record_system_heartbeat", window_seconds=120): - return - - from core.config import get_settings - from arq import create_pool - settings = get_settings() - - logger.info("Recording system heartbeat...") - - async with async_session_factory() as db: - # 1. Database Heartbeat - db_start = time.perf_counter() - db_status = ServiceStatus.DOWN - db_latency = 0 - try: - from sqlalchemy import text - await db.execute(text("SELECT 1")) - db_status = ServiceStatus.UP - db_latency = (time.perf_counter() - db_start) * 1000 - except Exception as e: - logger.error(f"Heartbeat: Database check failed: {e}") - - db_heartbeat = MetaInfraHealth( - service_name="DATABASE", - status=db_status, - latency_ms=db_latency, - environment="production" - ) - db.add(db_heartbeat) - - # 2. Redis Heartbeat (Arq) - redis_start = time.perf_counter() - redis_status = ServiceStatus.DOWN - redis_latency = 0 - redis_metrics = {} - try: - # We use the pool from ctx if available, otherwise create a temp one - pool = ctx.get('redis') - if not pool: - from core.config import get_redis_settings - pool = await create_pool(get_redis_settings()) - - # Check keys to gauge activity (SAFE SCAN replacement for KEYS) - pending_count = 0 - async for _ in pool.scan_iter("arq:job:*"): - pending_count += 1 - - redis_status = ServiceStatus.UP - redis_latency = (time.perf_counter() - redis_start) * 1000 - redis_metrics = {"pending_jobs": pending_count} - except Exception as e: - logger.error(f"Heartbeat: Redis check failed: {e}") - - redis_heartbeat = MetaInfraHealth( - service_name="REDIS", - status=redis_status, - latency_ms=redis_latency, - metrics=redis_metrics, - environment="production" - ) - db.add(redis_heartbeat) - - # 3. Ollama Heartbeat - ollama_start = time.perf_counter() - ollama_status = ServiceStatus.DOWN - ollama_latency = 0 - ollama_metrics = {} - try: - async with httpx.AsyncClient(timeout=5.0) as client: - resp = await client.get(f"{settings.OLLAMA_BASE_URL}/api/tags") - if resp.status_code == 200: - ollama_status = ServiceStatus.UP - ollama_latency = (time.perf_counter() - ollama_start) * 1000 - ollama_metrics = {"models": resp.json().get("models", [])} - except Exception as e: - logger.error(f"Heartbeat: Ollama check failed: {e}") - - ollama_heartbeat = MetaInfraHealth( - service_name="OLLAMA", - status=ollama_status, - latency_ms=ollama_latency, - metrics=ollama_metrics, - environment="production" - ) - db.add(ollama_heartbeat) - - await db.commit() - logger.info("System heartbeat recorded successfully.") - -async def vectorize_nexus_interaction(ctx, workspace_id: UUID, user_id: UUID, content: str, interaction_id: Optional[UUID] = None, thread_id: Optional[UUID] = None, memory_type: str = "interaction", **kwargs): - """ - Background task to embed and store an interaction or fact for long-term semantic memory. - Enables forensic recall and enterprise-grade context retention. - """ - from core.llm import get_text_embeddings - from models.nexus_memory import NexusMemory - - async with async_session_factory() as db: - # 1. Semantic Embedding - text_model = get_text_embeddings() - vector = await text_model.aembed_query(content) - - # 2. Persistence - memory = NexusMemory( - workspace_id=workspace_id, - user_id=user_id, - content=content, - thread_id=thread_id, - interaction_id=interaction_id, - memory_type=memory_type, - embedding=vector - ) - db.add(memory) - await db.commit() - logger.info(f"SUCCESS: Nexus Memory vectorized and persisted: {memory_type} for workspace {workspace_id}") - - # Invalidate thread history cache to ensure fresh hydration on next load - if thread_id: - try: - from core.cache import invalidate_cache - logger.debug(f"Invalidating Nexus thread cache: {thread_id}") - # BUG-3 Fix: await directly — asyncio.create_task() in a worker context - # risks the task being GC'd before completion, silently losing the invalidation. - await invalidate_cache(f"nexus:thread:{thread_id}:masked") - except Exception as ie: - logger.warning(f"Nexus cache invalidation failed: {str(ie)}") - -async def generate_global_insight(ctx, *args, **kwargs): - """ - Background task to generate a platform-wide strategic summary for Super Admins. - Analyzes cross-tenant NexusMemory clusters identifying global patterns. - """ - # BUG-4 Fix: Add cron lock to prevent multi-replica duplication at 3 AM. - if not await check_cron_lock(ctx, "generate_global_insight", window_seconds=600): - return - - from models.nexus_memory import NexusMemory - from models.platform_insight import PlatformInsight - from core.llm import get_llm - from core.database import async_session_factory - from sqlalchemy import select - import json - - logger.info("Starting Global Strategic Insight generation...") - - async with async_session_factory() as db: - # 1. Fetch recent long-term memories across ALL tenants - # We look at the last 150 interaction-type memories globally - stmt = ( - select(NexusMemory.content) - .where(NexusMemory.memory_type == "interaction") - .order_by(desc(NexusMemory.created_at)) - .limit(150) - ) - mem_res = await db.execute(stmt) - memories = mem_res.scalars().all() - - if not memories: - logger.info("Global Insight: No memories found to analyze.") - return - - context_txt = "\n".join([f"- {m}" for m in memories]) - - # 2. Strategic Analysis via LLM - llm = get_llm() - prompt = ChatPromptTemplate.from_template(""" - You are the Nexus Platform Architect. Analyze these cross-tenant support interactions and provide: - 1. **Platform Mission Summary**: A 3-sentence high-level overview of global platform stability and user sentiment. - 2. **Topic Clusters**: Identify 3-5 recurring technical themes or friction points appearing across different tenants. - - Global Context Data: - {context} - - Respond strictly in JSON format: - {{ - "summary": "...", - "trends": {{ "TOPIC_NAME": "reasoning/frequency", ... }} - }} - """) - - try: - chain = prompt | llm - resp = await chain.ainvoke({"context": context_txt}) - - # 3. Parse and Persist - insights = json.loads(resp.content.strip().replace("```json", "").replace("```", "")) - - new_report = PlatformInsight( - summary=insights.get("summary", "Analysis complete."), - trends=insights.get("trends", {}), - metrics_snapshot={"memory_scan_count": len(memories)} - ) - db.add(new_report) - await db.commit() - logger.info("SUCCESS: Global Platform Insight generated and cached.") - - except Exception as e: - logger.error(f"FAILURE: Global Insight generation failed: {str(e)}") - await db.rollback() - -async def purge_stale_semantic_cache(ctx, *args, **kwargs): - """ - Periodic task to physically delete semantic cache records older than 12 hours. - Maintains a 6-hour functional TTL buffer for troubleshooting. - """ - if not await check_cron_lock(ctx, "purge_stale_semantic_cache", window_seconds=600): - return - - from models.nexus_semantic_cache import NexusSemanticCache - from sqlalchemy import delete - - logger.info("Executing Semantic Cache Purge...") - async with async_session_factory() as db: - try: - # Delete records older than 12 hours - stmt = delete(NexusSemanticCache).where( - NexusSemanticCache.created_at < (func.now() - text("INTERVAL '12 hours'")) - ) - result = await db.execute(stmt) - count = result.rowcount - await db.commit() - logger.info(f"SUCCESS: Purged {count} stale semantic cache entries.") - except Exception as e: - logger.error(f"FAILURE: Semantic Cache Purge failed: {e}") - await db.rollback() - -async def harvest_expertise_task(ctx, ticket_id: UUID, **kwargs): - """ - Background task to analyze a resolved ticket and harvest skills for the agent. - """ - from agents.staff_profiler import harvest_agent_skills - from models.user import User - - async with async_session_factory() as db: - try: - # 1. Fetch Ticket + Messages - stmt = select(Ticket).where(Ticket.id == ticket_id) - res = await db.execute(stmt) - ticket = res.scalar_one_or_none() - if not ticket or not ticket.assigned_to: - return - - msg_stmt = select(Message).where(Message.ticket_id == ticket_id).order_by(Message.created_at.asc()) - msgs = (await db.execute(msg_stmt)).scalars().all() - - # 2. Fetch Agent - agent_stmt = select(User).where(User.id == ticket.assigned_to) - agent = (await db.execute(agent_stmt)).scalar_one_or_none() - if not agent: - return - - # 3. Harvest Skills - await harvest_agent_skills(db, ticket, msgs, agent) - - except Exception as e: - # ISSUE-7 Fix: Harvest failures must be ERROR, not INFO, to surface in alert dashboards. - logger.error(f"Expertise Harvesting task failed for ticket {ticket_id}: {e}") - -async def generate_workspace_insights(ctx, workspace_id: str, **kwargs): - """ - Background task to generate a live AI summary and suggested actions for a workspace. - This helps pre-warm the cache and avoids 524 timeouts for users. - """ - from api.v1.dashboard import get_dashboard_stats, get_agent_queue - from core.llm import get_llm - from core.cache import set_cached_search - from langchain_core.prompts import ChatPromptTemplate - from models.user import User, UserRole - import json - - logger.info(f"Generating background AI insights for workspace {workspace_id}...") - - async with async_session_factory() as db: - try: - # 1. Mock a system user for context - # Hardening: Avoiding _legacy_role. Search for any active staff member or use global superadmin. - from sqlalchemy import or_ - system_user_stmt = select(User).where( - or_(User.global_role == UserRole.SUPERADMIN, User._legacy_role == UserRole.SC_ADMIN), - User.is_active - ).limit(1) - system_user = (await db.execute(system_user_stmt)).scalar_one_or_none() - if not system_user: - logger.error("No system admin user found for AI insights.") - return - - # 2. Gather context - stats = await get_dashboard_stats(workspace_id, current_user=system_user, db=db) - queue = await get_agent_queue(workspace_id, current_user=system_user, db=db) - - # 3. Invoke LLM - llm = get_llm(timeout=120) # Safe side timeout for background processing - 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} - - GOALS: - 1. A concise "Mission Summary" (Exactly 2 sentences). - 2. Exactly 3 "Suggested Actions" for the lead agent. - 3. Three short metric insights for the visual dashboard cards (1 sentence each). - - Respond strictly in JSON format: - {{ - "summary": "...", - "actions": ["...", "...", "..."], - "metric_insights": {{ - "intensity": "DEEP SCAN: ...", - "velocity": "OUTPUT STEADY: ...", - "thermal": "THERMAL STABILITY: ..." - }} - }} - """) - - sample = "\n".join([f"- {t['title']} ({t['priority']}, {t['status']})" for t in queue[:5]]) - chain = prompt | llm - - response = await chain.ainvoke({ - "total": stats["total_tickets"], - "breached": any(t.get("priority") == "P0" for t in queue), - "status_dist": stats["by_status"], - "agents": len(queue), - "ticket_sample": sample - }) - - text = response.content if hasattr(response, 'content') else str(response) - if "524: A timeout occurred" in text or "" in text: - raise ValueError("LLM Provider Timeout in background (CF 524)") - - json_str = text.replace("```json", "").replace("```", "").strip() - insights = json.loads(json_str) - - result = { - "summary": insights.get("summary", "Analysis complete."), - "actions": insights.get("actions", ["Review unassigned tickets", "Check SLA trends", "Balance personnel load"])[:3], - "metric_insights": insights.get("metric_insights", { - "intensity": "DEEP SCAN: Analyzing tier velocity. Neural load balancing recommended.", - "velocity": "OUTPUT STEADY: Workspace resolution cycle maintaining benchmarks.", - "thermal": "THERMAL STABILITY: Escalation friction points minimized." - }), - "type": "BACKGROUND_AI_INSIGHT", - "last_refreshed": datetime.utcnow().isoformat() - } - - # 4. Persistence to cache (global format used by dashboard) - # Note: This cache key must match api/v1/dashboard.py - # Since this is background, we can't easily target a specific user's cache, - # so we'll store it in a general workspace cache that dashboard.py will check. - cache_key = f"dashboard:insights:{workspace_id}:system" - await set_cached_search(cache_key, result, ttl=1800) # 30 min cache - - logger.info(f"SUCCESS: Background AI insights generated for workspace {workspace_id}") - - except Exception as e: - logger.error(f"FAILURE: Background AI insights failed: {str(e)}") -async def recover_nexus_history(ctx, thread_id: UUID, workspace_id: UUID, user_role: str, **kwargs): - """ - Background worker task to load and mask conversational history for a Nexus thread. - Optimizes performance for heavy threads and ensures zero-trust masking is applied. - """ - from models.nexus_interaction import NexusInteraction - from agents.security import mask_for_role - - logger.info(f"💾 Recovering nexus history for thread {thread_id}...") - - async with async_session_factory() as db: - from models.user import User as UserTable - stmt = ( - select(NexusInteraction, UserTable.full_name) - .join(UserTable, NexusInteraction.user_id == UserTable.id) - .where( - NexusInteraction.thread_id == thread_id, - NexusInteraction.workspace_id == workspace_id - ) - .order_by(NexusInteraction.created_at.asc()) - ) - result = await db.execute(stmt) - rows = result.all() - - if not rows: - return [] - - # Convert to dicts for masking - interaction_dicts = [dict( - id=i.id, - input_query=i.input_query, - ai_answer=i.ai_answer, - sender_name=full_name, - created_at=i.created_at.isoformat() - ) for i, full_name in rows] - - # Apply role-based masking - masked = mask_for_role(interaction_dicts, user_role) - - # Flatten into conversational messages with metadata - history = [] - for i in masked: - history.append({ - "role": "user", - "content": i["input_query"], - "senderName": i.get("sender_name", "User"), - "timestamp": i["created_at"] - }) - history.append({ - "role": "assistant", - "content": i["ai_answer"], - "senderName": "Nexus", - "timestamp": i["created_at"] - }) - - logger.info(f"✅ History recovery complete for {thread_id} ({len(history)} messages)") - return history - -async def record_workflow_step_task( - ctx: Any, - entity_id: str, - workspace_id: str, - workflow_type: str, - step_name: str, - input_data: Optional[Dict] = None, - output_data: Optional[Dict] = None, - current_stage: Optional[str] = None, - duration_ms: Optional[float] = None, - **kwargs -): - """Background task to record a workflow lifecycle step.""" - try: - async with async_session_factory() as db: - from core.observability import record_workflow_step - await record_workflow_step( - db, - entity_id=UUID(entity_id), - workspace_id=UUID(workspace_id), - workflow_type=workflow_type, - step_name=step_name, - input_data=input_data, - output_data=output_data, - current_stage=current_stage, - duration_ms=duration_ms or 0.0 - ) - await db.commit() - except Exception as e: - logger.warning(f"Failed to record workflow step in background: {e}") - -async def process_kb_import_task( - ctx: Any, - workspace_id: UUID, - author_id: UUID, - file_content: str, - original_filename: str, - **kwargs -): - """ - Heavy Worker Task: Converts raw text into a structured KB Article using LLM. - Creates a DRAFT article upon success. - """ - from core.llm import get_llm - from langchain_core.messages import SystemMessage, HumanMessage - from models.kb_article import KBArticle - import re - - start_time = datetime.utcnow() - logger.info(f"IMPORT TASK: Starting AI transformation for {original_filename} in workspace {workspace_id}") - - try: - # 1. AI Transformation - llm = get_llm(timeout=180) # Workers can afford high timeouts - prompt = [ - SystemMessage(content=( - "You are an expert technical writer. Convert the following unstructured text " - "into a high-quality Markdown knowledge base article.\n\n" - "REQUIREMENTS:\n" - "1. Output ONLY the raw markdown content without any summary or conversational preamble.\n" - "2. Add a clear # Title at the top.\n" - "3. Use structured headings (##, ###).\n" - "4. Add bolding for emphasis, code blocks for technical parameters, and tables for comparative data.\n" - )), - HumanMessage(content=f"UNSTRUCTURED CONTENT FROM {original_filename}:\n\n{file_content}") - ] - - resp = await llm.ainvoke(prompt) - ai_content = resp.content.strip() - - # Cleanup markdown wrappers - if ai_content.startswith("```markdown") and ai_content.endswith("```"): - ai_content = ai_content[11:-3].strip() - - # Extract title - title_match = re.search(r'^#\s+(.+)$', ai_content, re.MULTILINE) - title = title_match.group(1).strip() if title_match else f"Import: {original_filename}" - - # 2. Database Persistence - async with async_session_factory() as db: - new_article = KBArticle( - workspace_id=workspace_id, - author_id=author_id, - title=title, - content=ai_content, - category="General", - is_published=False # Always Draft on import for review - ) - db.add(new_article) - await db.flush() # Get the ID - - article_id = new_article.id - workspace_id_obj = new_article.workspace_id - - # Record observability - from core.observability import record_workflow_step - await record_workflow_step( - db, - entity_id=article_id, - workspace_id=workspace_id_obj, - workflow_type="KNOWLEDGE_IMPORT", - step_name="AI_TRANSFORMATION", - status="success", - duration_ms=(datetime.utcnow() - start_time).total_seconds() * 1000, - current_stage="PENDING_REVIEW" - ) - - await db.commit() - logger.info(f"IMPORT TASK SUCCESS: Created draft article {article_id} from {original_filename}") - - # 3. Trigger full indexing pipeline (Async) - from core.tasks import enqueue_task - await enqueue_task("index_kb_article", article_id) - - except Exception as e: - logger.error(f"IMPORT TASK CRITICAL FAILURE for {original_filename}: {str(e)}") - # We don't have an article record to update error status on yet, so we just log. - raise e - - -async def generate_nightly_personnel_analytics(ctx, **kwargs): - """ - CRON: Runs nightly at midnight. - Gathers user activity metrics and generates a persistent AI narrative. - """ - if not await check_cron_lock(ctx, "generate_nightly_personnel_analytics"): - return - - async with async_session_factory() as db: - from models.user_workspace import UserWorkspace - from models.user import UserRole - from models.ticket import Ticket - from models.message import Message - from models.kb_article import KBArticle - from models.escalation_rule import EscalationRule - - # 1. Fetch all staff members across all workspaces - stmt = select(UserWorkspace).where( - UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), - UserWorkspace.is_active == True - ) - res = await db.execute(stmt) - memberships = res.scalars().all() - - now = datetime.utcnow() - last_7d = now - timedelta(days=7) - - logger.info(f"🌙 Starting nightly personnel analytics for {len(memberships)} staff records.") - - for uw in memberships: - uid = uw.user_id - wid = uw.workspace_id - - try: - # GATHER METRICS (Last 7 Days) - # Tickets Resolved - res_stmt = select(func.count(Ticket.id)).where( - Ticket.workspace_id == wid, - Ticket.resolved_by == uid, - Ticket.resolved_at >= last_7d, - Ticket.deleted_at.is_(None) - ) - res_count = (await db.execute(res_stmt)).scalar() or 0 - - # Articles Published - art_stmt = select(func.count(KBArticle.id)).where( - KBArticle.workspace_id == wid, - KBArticle.author_id == uid, - KBArticle.created_at >= last_7d, - KBArticle.deleted_at.is_(None) - ) - art_count = (await db.execute(art_stmt)).scalar() or 0 - - # Comments / Messages - msg_stmt = select(func.count(Message.id)).where( - Message.workspace_id == wid, - Message.sender_id == uid, - Message.created_at >= last_7d, - Message.deleted_at.is_(None) - ) - msg_count = (await db.execute(msg_stmt)).scalar() or 0 - - # SLA Compliance (7d) - rules_res = await db.execute(select(EscalationRule).where(EscalationRule.workspace_id == wid)) - rules = {r.priority_level: r.threshold_minutes for r in rules_res.scalars().all()} - - sla_stmt = select(Ticket).where( - Ticket.workspace_id == wid, - Ticket.resolved_by == uid, - Ticket.resolved_at >= last_7d, - Ticket.deleted_at.is_(None) - ) - resolved_tickets = (await db.execute(sla_stmt)).scalars().all() - - breached = 0 - for t in resolved_tickets: - limit = rules.get(str(t.priority), 1440) - duration = (t.resolved_at - t.created_at).total_seconds() / 60 - if duration > limit: - breached += 1 - - compliance = round((res_count - breached) / res_count, 2) if res_count > 0 else 1.0 - - # 2. Generate AI Narrative - llm = get_llm(timeout=30) - prompt = ChatPromptTemplate.from_template(""" - You are a Senior Personnel Performance Analyst. - Generate a concise, data-grounded performance narrative for the following staff member based on their activity in the last 7 days. - - METRICS (Last 7 Days): - - Tickets Resolved: {res} - - Knowledge Articles Published: {art} - - Communication Volume (Messages): {msg} - - SLA Compliance Rate: {sla}% - - RULES: - 1. Use professional, high-fidelity language. - 2. Highlight the primary operational strength. - 3. If activity is zero, report "Monitoring for workspace engagement". - 4. MAX 2-3 SENTENCES. NO PREAMBLE. - """) - - narrative_res = await (prompt | llm).ainvoke({ - "res": res_count, - "art": art_count, - "msg": msg_count, - "sla": int(compliance * 100) - }) - narrative = narrative_res.content.strip() - - # 3. Update UserWorkspace - uw.ai_narrative = narrative - uw.activity_summary = { - "resolved_7d": res_count, - "articles_7d": art_count, - "messages_7d": msg_count, - "compliance_7d": compliance, - "last_calculated": now.isoformat() - } - db.add(uw) - - except Exception as e: - logger.error(f"Failed analysis for User {uid} in Workspace {wid}: {str(e)}") - continue - - await db.commit() - logger.info("✅ Nightly personnel analytics cycle complete.") - +# Re-exporting for backward compatibility +from tasks.system import ( + get_task_pool, check_cron_lock, check_job_latch, enqueue_task, + monitor_sla_thresholds, record_system_heartbeat, nexus_pulse_check, + purge_stale_semantic_cache, record_workflow_step_task, + recover_nexus_history +) +from tasks.ai import ( + auto_summarize_ticket, crystallize_memory, index_kb_article, + generate_ticket_embedding, vectorize_nexus_interaction, + generate_global_insight, generate_workspace_insights, + process_kb_import_task, ai_dynamic_nudge_pulse +) +from tasks.notifications import send_triple_notification, notify_mentions +from tasks.analytics import harvest_expertise_task, generate_nightly_personnel_analytics +from tasks.remediation import execute_remediation_hook