Spaces:
Paused

File size: 53,397 Bytes
5eb4857
 
 
 
 
b7980f7
5eb4857
 
b7980f7
5eb4857
 
 
 
 
 
 
 
 
 
 
b7980f7
5eb4857
 
 
b7980f7
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25925c2
 
 
 
 
 
 
 
 
 
 
b7980f7
5eb4857
b7980f7
 
5eb4857
b7980f7
5eb4857
 
b7980f7
 
 
 
 
5eb4857
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25925c2
 
 
 
 
 
 
 
 
 
 
b7980f7
cf95cd1
 
25925c2
cf95cd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25925c2
 
b7980f7
2d0e9e3
25925c2
 
2d0e9e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25925c2
2d0e9e3
25925c2
 
 
2d0e9e3
25925c2
 
 
 
b7980f7
25925c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
25925c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
25925c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
25925c2
b7980f7
25925c2
 
 
 
 
 
 
 
 
4e16b54
 
 
 
25925c2
 
 
 
 
 
 
 
 
 
b7980f7
25925c2
cf95cd1
 
 
 
25925c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
25925c2
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
25925c2
5eb4857
f3a5b2f
b7980f7
5eb4857
b7980f7
 
 
 
 
 
5eb4857
 
 
 
f3a5b2f
 
5eb4857
 
 
 
b7980f7
5eb4857
 
 
 
 
f3a5b2f
5eb4857
 
b7980f7
 
 
 
 
 
 
5eb4857
f3a5b2f
5eb4857
 
 
 
f3a5b2f
5eb4857
 
b7980f7
5eb4857
 
 
 
f3a5b2f
 
5eb4857
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
b7980f7
5eb4857
b7980f7
 
 
 
 
 
 
5eb4857
b7980f7
 
5eb4857
b7980f7
 
 
5eb4857
b7980f7
5eb4857
b7980f7
 
 
 
 
 
 
 
 
f3a5b2f
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
b7980f7
 
 
5eb4857
 
b7980f7
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94b1a89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
accf280
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91ebb5b
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc1617c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
"""
Background task definitions for Arq worker.
"""

import httpx
from typing import Optional, Dict, Any, List
from uuid import UUID
from datetime import datetime
from sqlalchemy import select, update, func, desc, text, delete
from core.database import async_session_factory
from core.logging import get_logger
from core.websockets import manager
from models.ticket import Ticket, TicketStatus, TicketPriority
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 core.search import chunk_text
from core.sync import sync_markdown_images
from core.observability import record_workflow_step
from core.email import send_email
import time

logger = get_logger(__name__)

async def auto_summarize_ticket(ctx, ticket_id: UUID):
    """
    Background task to generate dual summaries (Internal/Customer).
    """
    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
        msg_stmt = select(Message).where(
            Message.ticket_id == ticket_id,
            Message.deleted_at.is_(None)
        ).order_by(Message.created_at.asc())
        msg_result = await db.execute(msg_stmt)
        messages = msg_result.scalars().all()

        # 3. Partition Messages
        public_messages = [m for m in messages if not m.is_internal]
        
        llm = get_llm()
        
        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
        # Resolve images from description and messages
        all_imgs = await extract_visual_context(db, ticket.workspace_id, ticket.description, limit=3)
        for m in messages:
            if len(all_imgs) >= 10: break
            all_imgs.extend(await extract_visual_context(db, ticket.workspace_id, m.content, limit=2))

        # 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}]
        # Only include images found in public messages or description
        cust_blocks.extend(all_imgs[:5]) # Hard limit for customer
        
        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) # Full internal context
        
        intl_prompt = [
            SystemMessage(content="You are a support lead. Summarize for an INTERNAL AGENT. Include internal notes. Use visual info if screenshots present. Max 4 sentences."),
            HumanMessage(content=intl_blocks)
        ]

        # Execute
        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
        }

        # Persist
        meta = dict(ticket.ai_metadata or {})
        meta["summaries"] = summary_data
        ticket.ai_metadata = meta
        db.add(ticket)
        
        # --- Observability: Record Summarization ---
        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()
        logger.info(f"Auto-summary generated for ticket {ticket_id}")

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):
    """
    Durable ARQ worker task for full KB indexing lifecycle:
    Syncing images, Categorization, Embedding, Chunking, Vision, Duplicate detection, and Summary.
    """
    start_time = time.perf_counter()
    async with async_session_factory() as db:
        try:
            # 1. Fetch Article with Row-Level Lock (FOR UPDATE)
            stmt = select(KBArticle).where(
                KBArticle.id == article_id,
                KBArticle.deleted_at.is_(None)
            ).with_for_update()
            
            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

            # --- 2. Multi-Model Initialization ---
            text_model = get_text_embeddings()
            llm = get_llm()

            async def _abort_if_deleted():
                _chk = await 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 during processing.")
                    return True
                return False

            # --- 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() 
                await db.refresh(article)
                logger.info(f"PHASE 1 [Images] Complete for {article_id}")
            except Exception as e:
                logger.error(f"PHASE 1 [Images] Failed for {article_id}: {e}")
                await db.rollback()
                await db.refresh(article)

            # --- PHASE 2: Core Embeddings ---
            phase2_success = False
            try:
                text_model = get_text_embeddings()
                text_to_embed = truncate_content(f"{article.title} {article.content}", 8000)
                
                logger.info(f"PHASE 2 [Embeddings] Generating for {article_id} (Length: {len(text_to_embed)})")
                vector = await text_model.aembed_query(text_to_embed)
                
                # Smart Persistence: Validate Dimension (768 is default for nomic/google-embed)
                if vector and len(vector) == settings.AI_EMBEDDING_DIM:
                    article.embedding = vector
                    db.add(article)
                    await db.commit()
                    await db.refresh(article)
                    phase2_success = True
                    logger.info(f"PHASE 2 [Embeddings] Complete for {article_id} (Dim: {len(vector)})")
                else:
                    error_msg = f"Dimension mismatch: Got {len(vector) if vector else 0}, expected {settings.AI_EMBEDDING_DIM}"
                    logger.error(f"PHASE 2 [Embeddings] Failed for {article_id}: {error_msg}")
            except Exception as e:
                logger.error(f"PHASE 2 [Embeddings] Failed for {article_id} (Length: {len(text_to_embed)}): {str(e)}")

            # --- PHASE 3: Chunking & Architecture Enrichment ---
            try:
                await db.execute(delete(KBArticleChunk).where(KBArticleChunk.article_id == article_id))
                raw_chunks = chunk_text(article.content, chunk_size=1200, chunk_overlap=100)
                
                for i, text_content in enumerate(raw_chunks):
                    # Architecture Enrichment Step
                    processed_text = text_content
                    if "```mermaid" in text_content.lower() or "```json" in text_content.lower() or "graph " in text_content[:50].lower():
                        try:
                            logger.info(f"Technical block detected in chunk {i} of {article_id}. Generating TEK_NAV...")
                            enrich_prompt = (
                                f"Explain this technical block in ONE concise sentence for search indexing. "
                                f"Identify what the flow/data represents.\n\nBLOCK:\n{text_content[:2000]}"
                            )
                            enrich_res = await llm.ainvoke(enrich_prompt)
                            if enrich_res and enrich_res.content:
                                nav_tag = f"[TEK_NAV: {enrich_res.content.strip()}]\n"
                                processed_text = nav_tag + text_content
                        except Exception as enrich_err:
                            logger.warning(f"Architecture Enrichment failed for chunk {i}: {enrich_err}")
                    
                    chunk_vector = await text_model.aembed_query(f"{article.title}: {processed_text}")
                    new_chunk = KBArticleChunk(
                        article_id=article.id, 
                        content=processed_text, 
                        chunk_index=i, 
                        embedding=chunk_vector
                    )
                    db.add(new_chunk)
                    
                if await _abort_if_deleted(): return
                await db.commit()
                await db.refresh(article)
                logger.info(f"PHASE 3 [Enrichment] Complete for {article_id} ({len(raw_chunks)} chunks)")
            except Exception as e:
                logger.error(f"PHASE 3 [Chunking] Failed for {article_id}: {e}")
                await db.rollback()
                await db.refresh(article)

            # --- PHASE 4: Auto-Categorization ---
            try:
                if not article.category or article.category in ["N/A", "General"]:
                    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"]]
                    
                    cat_context = f"Existing categories: {', '.join(existing_cats)}" if existing_cats else "No existing categories."
                    cat_prompt = (
                        f"Categorize this KB article. {cat_context}\n"
                        f"Title: {article.title}\nContent Snippet: {truncate_content(article.content, 1000)}\n"
                        f"Return ONLY the category name (1-3 words)."
                    )
                    cat_res = await llm.ainvoke(cat_prompt)
                    if cat_res and cat_res.content:
                        article.category = cat_res.content.strip().title()
                        db.add(article)
                        if await _abort_if_deleted(): return
                        await db.commit()
                        await db.refresh(article)
                        logger.info(f"PHASE 4 [Category] Complete for {article_id}: {article.category}")
            except Exception as e:
                logger.error(f"PHASE 4 [Category] Failed for {article_id}: {e}")
                await db.rollback()
                await db.refresh(article)

            # --- PHASE 5: Attachment/Multimodal 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.file_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)
                if await _abort_if_deleted(): return
                await db.commit()
                await db.refresh(article)
                logger.info(f"PHASE 5 [Multimodal] Complete for {article_id}")
            except Exception as e:
                logger.error(f"PHASE 5 [Multimodal] Failed for {article_id}: {e}")
                await db.rollback()
                await db.refresh(article)

            # --- PHASE 6: Duplicate Detection ---
            try:
                if article.embedding is not None:
                    dup_stmt = (
                        select(KBArticle)
                        .where(KBArticle.workspace_id == article.workspace_id, KBArticle.id != article.id, 
                               KBArticle.is_published == True, KBArticle.duplicate_of_id.is_(None), KBArticle.deleted_at.is_(None))
                        .order_by(KBArticle.embedding.cosine_distance(article.embedding))
                        .limit(1)
                    )
                    dup_res = await db.execute(dup_stmt)
                    match = dup_res.scalar_one_or_none()
                    
                    if match:
                        dist_stmt = select(KBArticle.embedding.cosine_distance(article.embedding)).where(KBArticle.id == match.id)
                        dist_res = await db.execute(dist_stmt)
                        distance = dist_res.scalar()
                        
                        if distance is not None and distance <= 0.3:
                            article.duplicate_of_id = match.id
                            article.is_published = False
                            db.add(article)
                            if await _abort_if_deleted(): return
                            await db.commit()
                            await db.refresh(article)
                            logger.info(f"PHASE 6 [Deduplication] Complete for {article_id}: Hit {match.id}")
            except Exception as e:
                logger.error(f"PHASE 6 [Deduplication] Failed for {article_id}: {e}")
                await db.rollback()
                await db.refresh(article)

            # --- PHASE 7: Advanced Summarization & Final Hardening ---
            try:
                # 1. Generate Summary (Vision-Aware if possible, else text-only)
                llm = get_llm()
                article_imgs = await extract_visual_context(db, article.workspace_id, article.content, limit=5)
                truncated_content = truncate_content(article.content, 12000)
                content_txt = f"Title: {article.title}\n\nContent:\n{truncated_content}"
                
                try:
                    content_blocks = [{"type": "text", "text": content_txt}]
                    if article_imgs: content_blocks.extend(article_imgs)
                    prompt = [
                        SystemMessage(content="Summarize this technical KB article in 2-3 sentences. Focus on clarity. IMPORTANT: DO NOT include any code blocks, backticks, or raw technical snippets in the summary. Keep it plain text."), 
                        HumanMessage(content=content_blocks)
                    ]
                    resp = await llm.ainvoke(prompt)
                    article.summary = resp.content
                except Exception as vision_err:
                    logger.warning(f"Vision-aware summary failed for {article_id}, falling back to simple text: {vision_err}")
                    resp = await llm.ainvoke([
                        ("system", "You are an expert technical writer. Provide a 2-3 sentence internal summary for this article."),
                        ("human", content_txt)
                    ])
                    if resp and resp.content:
                        article.summary = resp.content

                # 2. Defensive Check: Emergency Embedding Generation if Phase 2 failed
                if article.embedding is None:
                    # SMART PERSISTENCE: Re-fetch from DB first to see if Phase 2 commit was successful but session stale
                    await db.refresh(article, attribute_names=["embedding"])
                    
                if article.embedding is None:
                    logger.warning(f"PHASE 7 [Critical Check]: Embedding still NULL for {article_id}. Attempting emergency generation with 4k limit.")
                    try:
                        emergency_text = truncate_content(f"{article.title} {article.content}", 4000)
                        article.embedding = await text_model.aembed_query(emergency_text)
                        logger.info(f"PHASE 7 [Critical Check]: Emergency embedding generation SUCCESSFUL for {article_id}")
                    except Exception as e_inner:
                        logger.error(f"PHASE 7 [Critical Check]: Emergency embedding generation FAILED for {article_id}: {str(e_inner)}")

                db.add(article)
                if await _abort_if_deleted(): return
                await db.commit()
                await db.refresh(article)
                logger.info(f"PHASE 7 [Summarization] Complete for {article_id}")
            except Exception as e:
                logger.error(f"PHASE 7 [Summarization] Failed for {article_id}: {e}")
                await db.rollback()
                await db.refresh(article)

            # --- 10. Record Trace ---
            try:
                await record_workflow_step(
                    db, article_id, article.workspace_id, "LIFECYCLE", "KB_INDEXING_COMPLETE",
                    output_data={"images": len(attachments) if 'attachments' in locals() else 0, "summary_len": len(article.summary or "")},
                    current_stage="READY_FOR_SEARCH", duration_ms=(time.perf_counter() - start_time) * 1000
                )
                await db.commit()
            except Exception as e:
                logger.warning(f"Final trace recording failed for {article_id}: {e}")

            logger.info(f"SUCCESS: Hardened KB indexing complete for {article_id}")

        except Exception as e:
            await db.rollback()
            logger.error(f"CRITICAL FAILURE: Unified KB indexing crashed for {article_id}: {str(e)}")

async def send_triple_notification(ctx, user_id: UUID, workspace_id: UUID, title: str, message: str, link: Optional[str] = None):
    """Send notification to DB, real-time WebSocket, and simulated Email."""
    async with async_session_factory() as db:
        # 1. Fetch User Email (Security Audit: Ensure we have a valid recipient)
        from models.user import User
        user_stmt = select(User.email).where(User.id == user_id)
        user_email = (await db.execute(user_stmt)).scalar()
        
        # 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
        await manager.broadcast_to_workspace(workspace_id, {
            "type": "notification",
            "id": str(notification.id),
            "title": title,
            "message": message,
            "link": link,
            "created_at": datetime.utcnow().isoformat()
        })
        
        # 4. Email Notification (Simulated Forensics)
        if user_email:
            email_body = f"Hello,\n\n{message}\n\nThis is a priority alert from Nexus AI."
            await send_email(user_email, title, email_body)

        logger.info(f"Triple notification sent to user {user_id} ({user_email})")
        
async def notify_mentions(ctx, workspace_id: UUID, title: str, mentions: list, ticket_id: Optional[UUID] = None):
    """
    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
    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):
    """
    Periodic task to check for SLA breaches and apply escalation rules.
    Runs every 5 minutes (configured in worker.py).
    """
    logger.info("Starting SLA monitoring check...")
    async with async_session_factory() as db:
        now = datetime.utcnow()
        # 1. BATCH FETCH: Find all potential breaches in a single pass with Rule JOIN
        # Optimized to destroy the N+1 query pattern observed in logs
        from sqlalchemy import cast, String
        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 == True
            )
        )
        result = await db.execute(stmt)
        breached_candidates = result.all()
        
        # Cache for managers to avoid N+1 queries during the escalation loop
        manager_cache = {}

        for ticket, rule in breached_candidates:
            # Handle potential offset-naive datetimes from DB
            threshold_time = ticket.created_at.replace(tzinfo=None)
            age_minutes = (now - threshold_time).total_seconds() / 60
            
            if age_minutes >= rule.threshold_minutes:
                logger.warning(f"SLA Breach: Ticket {ticket.id} (Age: {age_minutes:.1f}m) exceeds rule {rule.name}")
                
                if rule.action == "NOTIFY_LEAD":
                    # Check cache first to prevent N+1 query bottleneck
                    if ticket.workspace_id not in manager_cache:
                        from agents.utils import get_workspace_manager
                        manager_cache[ticket.workspace_id] = await get_workspace_manager(db, ticket.workspace_id)
                    
                    manager_user = manager_cache[ticket.workspace_id]
                    
                    if manager_user:
                        from models.escalation_rule import EscalationAction
                        await send_triple_notification(
                            ctx, 
                            manager_user.id, 
                            ticket.workspace_id, 
                            "🚨 SLA Escalation Alert",
                            f"Ticket '{ticket.title}' of priority {str(ticket.priority)} has exceeded its SLA threshold. This is an official system escalation.",
                            link=f"/dashboard?ticket={ticket.id}"
                        )
                        # MARK AS ESCALATED to avoid duplicates
                        ticket.is_escalated = now
                        db.add(ticket)
                        
                        # --- Observability: Record SLA Breach ---
                        from core.observability import record_workflow_step
                        await record_workflow_step(
                            db, ticket.id, ticket.workspace_id, "LIFECYCLE", 
                            "SLA_BREACH_ENFORCED", 
                            output_data={"rule": rule.name, "action": EscalationAction.NOTIFY_LEAD.value, "notify_user_id": str(manager_user.id)},
                            current_stage="ESCALATED_SLA"
                        )
                        
                        # --- Audit Log Update ---
                        audit = AuditLog(
                            workspace_id=ticket.workspace_id,
                            entity_type="ticket",
                            entity_id=ticket.id,
                            action="SLA_ESCALATION",
                            user_id=None, # System action
                            new_value={"rule_name": rule.name, "action_taken": "NOTIFY_LEAD"}
                        )
                        db.add(audit)
                        
                        logger.info(f"Ticket {ticket.id} marked as escalated at {now}")
                    else:
                        logger.warning(f"SLA Breach: No Lead/Admin found for workspace {ticket.workspace_id} to notify.")
                
                elif rule.action == "REASSIGN" or rule.action == "AUTO_RESOLVE":
                    # DEPRECATED/CONSOLIDATED Logic: Fallback to NOTIFY_LEAD per new requirements
                    logger.info(f"SLA Breach: Action '{rule.action}' consolidated to NOTIFY_LEAD for ticket {ticket.id}")
                    # Recursively handle as NOTIFY_LEAD would be cleaner but for simplicity we duplicate the notification parts 
                    # if needed, but per plan we are strictly focused on NOTIFY_LEAD now.
                    pass
                        
        await db.commit()

async def ai_dynamic_nudge_pulse(ctx):
    """
    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()
        from models.escalation_rule import EscalationAction
        
        # 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.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
                llm = get_llm()
                from core.tasks import auto_summarize_ticket # Use logic to get messages
                msg_stmt = select(Message).where(Message.ticket_id == ticket.id).order_by(Message.created_at.asc())
                msgs = (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 db.commit()

async def crystallize_memory(
    ctx, 
    workspace_id: UUID, 
    user_id: UUID, 
    thread_id: Optional[UUID], 
    history_str: str, 
    old_summary: str, 
    old_gist: Dict[str, Any]
):
    """
    Background AI Distillation Task. Takes pruned conversation history and distills
    it into an updated interaction summary and identity gist, then physically 
    commits both to the database and vector store so next query starts fresh.
    """
    from core.llm import get_llm, get_text_embeddings
    from langchain_core.prompts import ChatPromptTemplate
    from agents.prompts import get_prompt
    import json
    
    logger.info(f"Crystallizing memory for user {user_id} in thread {thread_id} via ARQ...")
    
    llm = get_llm()
    embedder = get_text_embeddings()
    
    try:
        # A) DISTILL SUMMARY
        prompt = ChatPromptTemplate.from_template(get_prompt("memory_distiller"))
        chain = prompt | llm
        new_summary_resp = await chain.ainvoke({"old_summary": old_summary, "new_history": history_str})
        new_thread_summary = new_summary_resp.content.strip()

        # B) EXTRACT GIST
        gist_prompt = ChatPromptTemplate.from_template(get_prompt("identity_architect"))
        gist_chain = gist_prompt | llm
        new_gist_resp = await gist_chain.ainvoke({
            "old_gist": json.dumps(old_gist), 
            "new_history": history_str
        })
        
        # Robust JSON extraction
        content = new_gist_resp.content.strip()
        start_idx = content.find('{')
        end_idx = content.rfind('}')
        if start_idx != -1 and end_idx != -1:
            clean_gist = content[start_idx:end_idx+1]
            new_gist = json.loads(clean_gist)
        else:
            raise ValueError("No viable JSON gist found in response.")

        # 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 sqlalchemy import update
            
            # --- Persist User Gist ---
            await db.execute(
                update(User)
                .where(User.id == user_id)
                .values(ai_gist=new_gist)
            )
            await db.commit()
            
            # --- Vectorize Semantic Facts ---
            gist_str = f"USER_FACTS: {json.dumps(new_gist)}"
            fact_vector = await embedder.aembed_query(gist_str)
            
            # Upsert into NexusMemory
            db.add(NexusMemory(
                workspace_id=workspace_id,
                user_id=user_id,
                thread_id=thread_id,
                content=gist_str,
                memory_type="fact",
                embedding=fact_vector
            ))
            
            # --- Vectorize Summarized Interaction ---
            interaction_vector = 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_vector
            ))
            
            # --- Link Summary to Current Interaction Thread ---
            if thread_id:
                await db.execute(
                    update(NexusInteraction)
                    .where(NexusInteraction.thread_id == thread_id)
                    .values(metadata_json={"internal_summary": new_thread_summary})
                )
            
            await db.commit()
            logger.info(f"Memory successfully crystallized and vectorized for {user_id}")
            
    except Exception as e:
        logger.error(f"Background Memory Crystallization Failed: {str(e)}")

async def execute_remediation_hook(ctx, ticket_id: str, hook_id: str):
    """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:
                # Replace placeholders in template
                payload = str(hook.payload_template).replace("{{ticket_id}}", str(ticket.id))
                try:
                    resp = await client.post(hook.target, json=payload)
                    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)}")
                    
        # Mark ticket as resolved after remediation if configured
        ticket.status = TicketStatus.RESOLVED
        db.add(ticket)
        await db.commit()
        logger.info(f"Remediation successful: Ticket {ticket_id} resolved via hook {hook_id}")

async def nexus_pulse_check(ctx):
    """
    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.
    """
    from sqlalchemy import func
    from datetime import datetime, timezone, timedelta
    from models.workspace import Workspace
    from core.websockets import manager
    import json
    
    logger.info("Executing Proactive AI Pulse Check...")
    
    async with async_session_factory() as db:
        # 1. Get all active workspaces
        workspaces = (await db.execute(select(Workspace.id))).scalars().all()
        
        fifteen_mins_ago = datetime.utcnow() - timedelta(minutes=15)
        
        for w_id in workspaces:
            # 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."
                }
                
                # Push WebSocket alert to Staff UI for this workspace
                try:
                    await manager.broadcast_to_workspace(str(w_id), json.dumps(alert_payload))
                    logger.info(f"Broadcasted Pulse Anomaly to workspace: {w_id}")
                except Exception as e:
                    logger.error(f"Failed to broadcast pulse alert: {e}")

async def generate_ticket_embedding(ctx, ticket_id: UUID):
    """
    Background task to generate vector embeddings for a ticket's content.
    Enables semantic search and similarity matching.
    """
    import time
    from core.llm import get_embeddings
    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
            )

            # --- 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
            )
            
            # --- 1.5 Duplicate Check (Threshold 0.7)
            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 == 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):
    """
    Periodic task to record infrastructure health snapshots.
    Runs every 5 minutes (configured in nexus_worker.py).
    """
    from core.config import get_settings
    from arq import create_pool
    from arq.connections import RedisSettings
    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
            job_keys = await pool.keys("arq:job:*")
            redis_status = ServiceStatus.UP
            redis_latency = (time.perf_counter() - redis_start) * 1000
            redis_metrics = {"pending_jobs": len(job_keys)}
        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"):
    """
    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}")

async def generate_global_insight(ctx):
    """
    Background task to generate a platform-wide strategic summary for Super Admins.
    Analyzes cross-tenant NexusMemory clusters identifying global patterns.
    """
    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, desc
    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):
    """
    Periodic task to physically delete semantic cache records older than 12 hours.
    Maintains a 6-hour functional TTL buffer for troubleshooting.
    """
    from models.nexus_semantic_cache import NexusSemanticCache
    from sqlalchemy import text, 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()