Spaces:
Paused

File size: 30,292 Bytes
5eb4857
 
 
 
 
 
 
 
b7980f7
5eb4857
 
 
 
b7980f7
5eb4857
 
 
428a35c
5eb4857
 
 
 
 
 
ca7df66
dfcbb7c
5eb4857
 
 
 
 
b7980f7
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
b7980f7
5eb4857
 
 
 
 
 
b7980f7
5eb4857
 
 
b7980f7
 
 
 
5eb4857
 
 
 
b7980f7
 
ca7df66
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
 
 
 
 
b7980f7
5eb4857
 
 
e58f87e
5eb4857
b7980f7
5eb4857
 
 
b7980f7
 
 
 
5eb4857
 
 
b7980f7
 
ca7df66
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
 
 
 
 
 
 
b7980f7
 
 
 
 
5eb4857
 
b7980f7
5eb4857
b7980f7
 
5eb4857
 
b7980f7
 
 
5eb4857
b7980f7
 
5eb4857
4e16b54
ad4fe35
4e16b54
 
 
 
 
 
ad4fe35
 
 
 
4e16b54
 
 
 
 
 
ca7df66
 
 
 
 
 
235f8ef
ca7df66
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235f8ef
5eb4857
 
 
 
 
 
ca7df66
 
5eb4857
 
 
 
235f8ef
5eb4857
 
428a35c
5eb4857
 
 
 
428a35c
 
 
5eb4857
 
 
 
 
 
428a35c
 
2d0e9e3
428a35c
 
ca7df66
b7980f7
 
 
 
06f7381
 
 
b7980f7
 
 
 
06f7381
 
 
b7980f7
 
 
 
 
2d0e9e3
ca7df66
5eb4857
 
b7980f7
 
 
5eb4857
4e16b54
b7980f7
 
 
 
 
4e16b54
 
 
 
5eb4857
4e16b54
b7980f7
5eb4857
 
b7980f7
235f8ef
 
b7980f7
 
235f8ef
 
 
 
4e16b54
b7980f7
5eb4857
b7980f7
837cc5f
b7980f7
 
 
837cc5f
 
dfcbb7c
 
b7980f7
 
 
 
5eb4857
 
 
b7980f7
4e16b54
 
 
b7980f7
 
4e16b54
b7980f7
 
 
4e16b54
 
837cc5f
b7980f7
 
 
5eb4857
b7980f7
5eb4857
e58f87e
5eb4857
 
 
 
ca7df66
5eb4857
 
 
 
 
 
ca7df66
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
ca7df66
b7980f7
 
 
 
5eb4857
2d0e9e3
06f7381
 
 
 
 
 
 
2d0e9e3
 
 
 
 
 
 
 
 
 
 
 
dfcbb7c
235f8ef
 
 
 
 
b7980f7
5eb4857
235f8ef
 
 
 
 
 
 
 
 
b7980f7
235f8ef
b7980f7
 
235f8ef
b7980f7
 
ca7df66
b7980f7
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e16b54
dfcbb7c
837cc5f
4e16b54
 
5eb4857
 
 
 
 
235f8ef
2d0e9e3
 
 
235f8ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d0e9e3
5eb4857
 
 
b7980f7
5eb4857
06f7381
 
2d0e9e3
 
06f7381
5eb4857
 
b7980f7
 
 
 
 
5eb4857
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
b7980f7
 
5eb4857
 
 
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
b7980f7
5eb4857
 
 
 
 
b7980f7
 
 
 
5eb4857
 
 
b7980f7
 
 
5eb4857
b7980f7
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
5eb4857
 
b7980f7
5eb4857
 
b7980f7
 
 
 
 
 
5eb4857
 
b7980f7
5eb4857
 
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import asyncio
import time
from datetime import datetime
from typing import Any, List, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, text, desc, update
from core.database import async_session_factory

from core.deps import get_db, get_current_user, get_arq_pool
from core.permissions import require_roles, ALL_SC_ROLES
from core.logging import get_logger
from models.user import User, UserRole
from models.kb_article import KBArticle
from models.kb_article_chunk import KBArticleChunk
from models.project import Project
from core.llm import get_embeddings, get_llm, get_text_embeddings
from core.vision import resolve_image
from langchain.schema import HumanMessage, SystemMessage
from models.attachment import Attachment
from core.search import chunk_text
from core.vision import extract_visual_context
from core.sync import sync_markdown_images
from models.user_workspace import UserWorkspace
from core.cache import generate_cache_key, get_cached_search, set_cached_search, SemanticCacheManager
from schemas.kb import KBArticleCreate, KBArticleResponse, KBArticleUpdate, KBSearchResponse, KBBulkActionRequest, KBBulkSyncRequest

router = APIRouter()
logger = get_logger(__name__)

# AI Lifecycle is now handled by arq worker task: index_kb_article

@router.post("/", response_model=KBArticleResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def create_kb_article(
    payload: KBArticleCreate,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
    arq_pool: Any = Depends(get_arq_pool)
) -> Any:
    """Agents/Admin only: create a KB article."""
    # 1. Validate project_id if provided
    if payload.project_id:
        proj_stmt = select(Project).where(
            Project.id == payload.project_id,
            Project.workspace_id == current_user.workspace_id,
            Project.deleted_at.is_(None)
        )
        proj_res = (await db.execute(proj_stmt)).scalar_one_or_none()
        if not proj_res:
            raise HTTPException(
                status_code=400, 
                detail=f"Project {payload.project_id} not found in your workspace"
            )

    new_article = KBArticle(
        title=payload.title,
        content=payload.content,
        category=payload.category,
        project_id=payload.project_id,
        workspace_id=current_user.workspace_id,
        author_id=current_user.id
    )
    db.add(new_article)
    await db.commit()
    await db.refresh(new_article)
    
    # Unified ARQ Indexing Lifecycle (Categorization, Embedding, Chunking, Summary)
    await arq_pool.enqueue_job("index_kb_article", new_article.id)
        
    logger.info(f"KB Article created and enqueued: {new_article.id} by user {current_user.id}")
    
    return new_article

@router.get("/", response_model=List[KBArticleResponse])
async def list_kb_articles(
    category: str = None,
    workspace_id: Optional[str] = None,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """List KB articles (Many-to-Many)."""
    # 1. Global Visibility for Super Admin
    is_global = (workspace_id == "all" and current_user.role == UserRole.SC_ADMIN)
    
    stmt = select(KBArticle).where(
        KBArticle.deleted_at.is_(None),
        KBArticle.duplicate_of_id.is_(None)
    )
    
    if not is_global:
        target_ws = current_user.workspace_id
        if workspace_id and current_user.role in ALL_SC_ROLES:
            if current_user.role == UserRole.SC_ADMIN:
                target_ws = workspace_id
            else:
                ws_check = await db.execute(
                    select(UserWorkspace).where(
                        UserWorkspace.user_id == current_user.id,
                        UserWorkspace.workspace_id == workspace_id
                    )
                )
                if ws_check.scalar_one_or_none():
                    target_ws = workspace_id
        stmt = stmt.where(KBArticle.workspace_id == target_ws)
        
    if category:
        if category == "N/A":
            stmt = stmt.where(KBArticle.category.is_(None))
        else:
            stmt = stmt.where(KBArticle.category == category)
            
    result = await db.execute(stmt)
    return result.scalars().all()

@router.get("/categories/", response_model=List[str])
async def list_kb_categories(
    workspace_id: Optional[str] = None,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """Retrieve all unique categories in use (Many-to-Many)."""
    # 1. Global Visibility for Super Admin
    is_global = (workspace_id == "all" and current_user.role == UserRole.SC_ADMIN)
    
    stmt = select(func.distinct(KBArticle.category)).where(
        KBArticle.deleted_at.is_(None)
    )
    
    if not is_global:
        target_ws = current_user.workspace_id
        if workspace_id and current_user.role in ALL_SC_ROLES:
            if current_user.role == UserRole.SC_ADMIN:
                target_ws = workspace_id
            else:
                ws_check = await db.execute(
                    select(UserWorkspace).where(
                        UserWorkspace.user_id == current_user.id,
                        UserWorkspace.workspace_id == workspace_id
                    )
                )
                if ws_check.scalar_one_or_none():
                    target_ws = workspace_id
        stmt = stmt.where(KBArticle.workspace_id == target_ws)
        
    result = await db.execute(stmt)
    categories = [c for c in result.scalars().all()]
    # Normalize nulls to "N/A"
    normalized = sorted([c if c else "N/A" for c in categories])
    return normalized

async def generate_query_variations(query: str) -> List[str]:
    """Uses LLM to generate variations of the search query for better hit coverage."""
    # Fast-path for extremely short queries
    if len(query.strip()) < 3:
        return []
        
    try:
        llm = get_llm()
        # Slimmed prompt for faster Ollama generation
        prompt = (
            f"Generate 3 short search variations for: '{query}'. "
            f"Return ONLY the variations, one per line, no numbering."
        )
        resp = await llm.ainvoke(prompt)
        text = resp.content if hasattr(resp, "content") else str(resp)
        vars = [v.strip() for v in text.split("\n") if v.strip() and v.strip() != query]
        return vars[:3]
    except Exception as e:
        logger.error(f"Query expansion failed: {e}")
        return []

def strip_markdown(text: str | None) -> str:
    """Removes code blocks, bold, italics, tables, and headers for a clean search snippet."""
    if not text: return ""
    import re
    # Remove code blocks
    text = re.sub(r'```[\s\S]*?```', '', text)
    # Remove inline code
    text = re.sub(r'`.*?`', '', text)
    # Remove markdown table structure (pipes and continuous dashes)
    text = re.sub(r'\|', ' ', text)
    text = re.sub(r'^-{3,}$', ' ', text, flags=re.MULTILINE)
    text = re.sub(r'^\s*[-:]{3,}\s*$', ' ', text, flags=re.MULTILINE)
    # Remove headings, bold, italics
    text = re.sub(r'[#*>]', '', text)
    # Normalize whitespace
    text = re.sub(r'\s+', ' ', text).strip()
    return text

async def execute_multimodal_search(
    db: AsyncSession, 
    q: str, 
    current_user: User, 
    category: Optional[str], 
    project_id: Optional[UUID],
    workspace_id: UUID
):
    """Internal helper to execute factual hybrid search + visual attachment search."""
    import uuid
    import time
    from core.observability import record_workflow_step
    search_id = uuid.uuid4()
    start_time = time.perf_counter()

    # 1. Get Text Embedding for the query (Nomic-768)
    embed_start = time.perf_counter()
    query_vector = await get_text_embeddings().aembed_query(q)
    await record_workflow_step(
        db, search_id, current_user.workspace_id, "SEARCH", 
        "QUERY_EMBEDDING", 
        input_data={"q": q},
        duration_ms=(time.perf_counter() - embed_start) * 1000
    )
    
    # 2. SEACH A: Text Semantic Match (Articles)
    sem_start = time.perf_counter()
    semantic_stmt = (
        select(
            KBArticle,
            KBArticleChunk.content,
            (1 - KBArticleChunk.embedding.cosine_distance(query_vector)).label("sim_score")
        )
        .join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id)
        .where(
            KBArticle.deleted_at.is_(None),
            KBArticle.is_published == True,
            KBArticle.duplicate_of_id.is_(None),
            KBArticle.workspace_id == workspace_id
        )
    )
    if category: semantic_stmt = semantic_stmt.where(KBArticle.category == category)
    if project_id: semantic_stmt = semantic_stmt.where(KBArticle.project_id == project_id)
    semantic_stmt = semantic_stmt.order_by(desc("sim_score")).limit(20)
    
    # 3. SEARCH B: Visual Caption Match (Attachments)
    # Uses pg_trgm for fuzzy similarity + search_vector for keyword relevance
    vis_start = time.perf_counter()
    visual_stmt = (
        select(
            KBArticle,
            (
                func.ts_rank(Attachment.search_vector, func.plainto_tsquery('english', q)) +
                func.similarity(Attachment.ai_caption, q)
            ).label("vis_score")
        )
        .join(Attachment, KBArticle.id == Attachment.article_id)
        .where(
            KBArticle.deleted_at.is_(None),
            KBArticle.is_published == True,
            # Broaden: Match if either the keywords hit OR similarity is decent
            (
                Attachment.search_vector.op("@@")(func.websearch_to_tsquery('english', q)) |
                (func.similarity(Attachment.ai_caption, q) > 0.3)
            ),
            KBArticle.workspace_id == workspace_id
        )
    )
    visual_stmt = visual_stmt.order_by(desc("vis_score")).limit(10)
    
    # 4. SEARCH C: Keyword Match (FTS with Title Boost)
    # Optimized for short queries: Uses ts_rank_cd + Head-of-Document boost
    from sqlalchemy import case
    kw_start = time.perf_counter()
    keyword_stmt = (
        select(
            KBArticle,
            (
                func.ts_rank_cd(KBArticle.search_vector, func.websearch_to_tsquery('english', q)) +
                case((KBArticle.title.ilike(f"%{q}%"), 0.5), else_=0.0)
            ).label("kw_score")
        )
        .where(
            KBArticle.deleted_at.is_(None),
            KBArticle.is_published == True,
            KBArticle.search_vector.op("@@")(func.websearch_to_tsquery('english', q)),
            KBArticle.workspace_id == workspace_id
        )
    )
    if category: keyword_stmt = keyword_stmt.where(KBArticle.category == category)
    if project_id: keyword_stmt = keyword_stmt.where(KBArticle.project_id == project_id)
    keyword_stmt = keyword_stmt.order_by(desc("kw_score")).limit(15)
    
    # --- Parallel Execution ---
    async def run_query(stmt):
        async with async_session_factory() as session:
            res = await session.execute(stmt)
            return res.all()

    hits, v_hits, kw_hits = await asyncio.gather(
        run_query(semantic_stmt),
        run_query(visual_stmt),
        run_query(keyword_stmt)
    )
    
    # 4. Hybrid Fusion (Weighted Reciprocal Rank Fusion)
    results_map = {}
    
    def apply_fusion(list_hits, weight, score_attr):
        # Best-Hit Deduplication: Ensure an article only scores once per search branch
        seen_in_branch = set()
        for rank, row in enumerate(list_hits):
            art = row[0]
            if art.id in seen_in_branch:
                continue
            seen_in_branch.add(art.id)
            
            chunk_txt = row[1] if len(row) > 1 and isinstance(row[1], str) else None
            rrf_score = weight * (1.0 / (60 + rank + 1))
            
            if art.id not in results_map:
                results_map[art.id] = {"obj": art, "score": rrf_score, "types": {score_attr}, "chunk": chunk_txt, "raw_chunk": chunk_txt}
            else:
                results_map[art.id]["score"] += rrf_score
                results_map[art.id]["types"].add(score_attr)
                if not results_map[art.id]["raw_chunk"] and chunk_txt:
                    results_map[art.id]["raw_chunk"] = chunk_txt
                if not results_map[art.id]["chunk"] and chunk_txt:
                    results_map[art.id]["chunk"] = chunk_txt

    apply_fusion(hits, 0.5, "sim_score")
    apply_fusion(kw_hits, 0.3, "kw_score")
    apply_fusion(v_hits, 0.2, "vis_score")

    sorted_results = sorted(results_map.values(), key=lambda x: x["score"], reverse=True)[:10]
    
    final_output = {}
    # MAX_POSSIBLE_SCORE = sum(weights) * (1/61) = 1.0 * (1/61) = 0.0163934426
    MAX_RRF = 0.0163934426
    
    for r in sorted_results:
        art = r["obj"]
        norm_score = min(((r["score"] / MAX_RRF) * 100), 100.0)
        final_output[art.id] = {
            "obj": art, 
            "score": round(norm_score, 1), 
            "type": "hybrid" if len(r["types"]) > 1 else list(r["types"])[0].replace("_score", ""), 
            "snippet": strip_markdown(r["chunk"]),
            "raw_chunk": r.get("raw_chunk"),
            "search_id": str(search_id)
        }

    await db.commit()
    return final_output

@router.get("/search/", response_model=KBSearchResponse)
async def search_kb_articles(
    q: str,
    category: Optional[str] = None,
    project_id: Optional[UUID] = None,
    workspace_id: Optional[UUID] = None,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """Advanced Search with LLM Multi-Query Expansion for maximum reliability."""
    start_time = time.perf_counter()
    
    target_ws = current_user.workspace_id
    if workspace_id and current_user.role in ALL_SC_ROLES:
        if current_user.role == UserRole.SC_ADMIN:
            target_ws = workspace_id
        else:
            ws_check = await db.execute(
                select(UserWorkspace).where(
                    UserWorkspace.user_id == current_user.id,
                    UserWorkspace.workspace_id == workspace_id
                )
            )
            if ws_check.scalar_one_or_none():
                target_ws = workspace_id

    # 0. Local Search Cache Lookup (Dual-Redis Architecture)
    cache_filters = {"category": category, "project_id": str(project_id) if project_id else None}
    cache_key = generate_cache_key("kb", str(target_ws), q, cache_filters)
    cached_res = await get_cached_search(cache_key)
    if cached_res:
        logger.info(f"⚡ Search Cache HIT [KB]: {q}")
        return cached_res
    
    # 0.5 Semantic Cache Check (Unified Workspace Knowledge)
    sem_answer = await SemanticCacheManager.check_cache(
        workspace_id=str(target_ws), 
        query=q,
        is_agent=current_user.role in ALL_SC_ROLES,
        user_role=str(current_user.role),
        user_id=str(current_user.id)
    )
    if sem_answer:
        logger.info(f"🧠 Semantic Cache HIT [KB]: {q}")
        # Process and return immediately with cache marker
        # We still run a minimal doc retrieval in background if needed (skipped for now for speed)
        return {
            "aiAnswer": sem_answer,
            "results": [], # Or could fetch top docs if UI requires
            "isSynthetic": True,
            "cacheHit": True,
            "confidence": 1.0,
            "durationMs": (time.perf_counter() - start_time) * 1000
        }
    
    # 1. Execute Original Search
    orig_res = await execute_multimodal_search(
        db, q, current_user, category, project_id, target_ws
    )
    all_local_results = [orig_res]
    expanded_queries = []
    
    # 2. Performance Optimization: High Confidence Early Exit
    # If original search has a near-perfect match (>80%), skip expensive LLM variations
    max_orig_score = max([r["score"] for r in orig_res.values()]) if orig_res else 0.0
    is_high_confidence = max_orig_score > 80.0
    
    # Check if query is complex enough to warrant expansion (e.g., >3 words or technical)
    is_complex = len(q.split()) >= 3 or any(w in q.lower() for w in ["how", "why", "steps", "explain"])
    
    if not is_high_confidence and is_complex and len(q.strip()) >= 5:
        # Launch AI expansion task
        expanded_queries = await generate_query_variations(q)
        
        if expanded_queries:
            # Launch searches for variations in parallel
            async def run_variation_search(v):
                async with async_session_factory() as session:
                    return await execute_multimodal_search(session, v, current_user, category, project_id, workspace_id=target_ws)
            
            var_tasks = [run_variation_search(v) for v in expanded_queries if v != q]
            if var_tasks:
                var_results = await asyncio.gather(*var_tasks)
                all_local_results.extend(var_results)
    
    # 3. Global Fusion (RRF across all branches and variations)
    global_merged = {}
    for local_res in all_local_results:
        for art_id, data in local_res.items():
            score = float(data.get("score") or 0.0)
            if art_id not in global_merged:
                global_merged[art_id] = data
                global_merged[art_id]["score"] = score # ensure it exists
            else:
                global_merged[art_id]["score"] = max(float(global_merged[art_id].get("score") or 0.0), score)

    # 4. Final Scoring & Thresholding
    THRESHOLD = 0.2
    final_results = []
    for art_id, data in global_merged.items():
        score = float(data.get("score") or 0.0)
        if score >= THRESHOLD:
            article_obj = data["obj"]
            res_dict = KBArticleResponse.model_validate(article_obj).model_dump()
            res_dict["score"] = score
            res_dict["match_type"] = data.get("type", "semantic")
            res_dict["snippet"] = data.get("snippet")
            res_dict["raw_chunk"] = data.get("raw_chunk")
            # Defensive Cleanup: Strip markdown from historical summaries
            res_dict["summary"] = strip_markdown(article_obj.summary)
            final_results.append(res_dict)

    final_results.sort(key=lambda x: float(x.get("score") or 0.0), reverse=True)
    top_results = final_results[:5]

    # 4.5 Synthesis Branch (The "Direct Answer" Engine)
    direct_answer = None
    is_ai_synthetic = False

    # Trigger synthesis if it's a complex query or we have high confidence hits
    # This provides a quick "Direct Answer" summary of the top documentation
    if is_complex and top_results:
        try:
            from core.llm import get_llm
            from langchain_core.messages import SystemMessage, HumanMessage
            
            # Construct context from TOP CHUNKS
            context_txt = "\n\n".join([
                f"DOC {i+1} [{r['title']}]:\n---\n{r.get('raw_chunk') or r.get('snippet') or r['content'][:500]}\n---" 
                for i, r in enumerate(top_results)
            ])
            
            llm = get_llm()
            prompt = [
                SystemMessage(content=(
                    "You are a technical support expert. Provide a concise, highly structured direct answer. "
                    "Use MARKDOWN for the following:\n"
                    "- Use **Bold** for key facts and product names.\n"
                    "- Use `inline code` for technical terms, database names, or variables.\n"
                    "- Use bulleted lists to cite evidence from provided documentation.\n"
                    "If the answer is not in the context, be honest. Keep it under 150 words."
                )),
                HumanMessage(content=f"Question: {q}\n\nDocumentation Context:\n{context_txt}")
            ]
            synth_resp = await llm.ainvoke(prompt)
            direct_answer = synth_resp.content
            is_ai_synthetic = True
            
            # Asynchronously Cache to Semantic Cache
            await SemanticCacheManager.set_cache(
                workspace_id=str(target_ws), 
                user_id=str(current_user.id), 
                query=q, 
                response_text=direct_answer,
                is_agent=current_user.role in ALL_SC_ROLES,
                user_role=str(current_user.role)
            )
        except Exception as e:
            logger.error(f"Synthesis failed: {e}")

    # 5. Final Response Payload
    end_time = time.perf_counter()
    search_time_s = end_time - start_time

    res_data = {
        "results": top_results,
        "answer": direct_answer,
        "is_ai_synthetic": is_ai_synthetic,
        "confidence": top_results[0].get("score") if top_results else 0.0,
        "suggestion": expanded_queries[0] if expanded_queries and expanded_queries[0].lower() != q.lower() and not top_results else None,
        "expanded_queries": expanded_queries if expanded_queries else [],
        "search_time_s": round(search_time_s, 3)
    }
    
    # Save to Local Search Cache before returning (1 hour TTL)
    await set_cached_search(cache_key, res_data)
    
    return res_data

@router.get("/{article_id}/", response_model=KBArticleResponse)
async def get_kb_article(
    article_id: UUID,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """Get a specific KB article."""
    stmt = select(KBArticle).where(
        KBArticle.id == article_id, 
        KBArticle.workspace_id == current_user.workspace_id,
        KBArticle.deleted_at.is_(None)
    )
    result = await db.execute(stmt)
    article = result.scalar_one_or_none()
    if not article:
        raise HTTPException(status_code=404, detail="Article not found")
    return article

@router.patch("/{article_id}/", response_model=KBArticleResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def update_kb_article(
    article_id: UUID,
    payload: KBArticleUpdate,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
    arq_pool: Any = Depends(get_arq_pool)
) -> Any:
    """Agents/Admin only: update KB article details."""
    stmt = select(KBArticle).where(
        KBArticle.id == article_id, 
        KBArticle.workspace_id == current_user.workspace_id,
        KBArticle.deleted_at.is_(None)
    )
    result = await db.execute(stmt)
    article = result.scalar_one_or_none()
    if not article:
        raise HTTPException(status_code=404, detail="Article not found")

    update_data = payload.model_dump(exclude_unset=True)
    
    # Validate project_id if it's being updated
    if "project_id" in update_data and update_data["project_id"] is not None:
        proj_stmt = select(Project).where(
            Project.id == update_data["project_id"],
            Project.deleted_at.is_(None)
        )
        if current_user.role != UserRole.SC_ADMIN:
            proj_stmt = proj_stmt.where(Project.workspace_id == current_user.workspace_id)
        proj_res = (await db.execute(proj_stmt)).scalar_one_or_none()
        if not proj_res:
             raise HTTPException(
                status_code=400, 
                detail=f"Project {update_data['project_id']} not found in your workspace"
            )

    # Sync images if content is updated
    if "content" in update_data:
        # Corrected signature: (db, entity_id, workspace_id, content, entity_type, uploader_id)
        await sync_markdown_images(db, article.id, article.workspace_id, update_data["content"], entity_type="article", uploader_id=current_user.id)

    for field, value in update_data.items():
        setattr(article, field, value)

    db.add(article)
    await db.commit()
    await db.refresh(article)
    
    # Unified ARQ Indexing Lifecycle (Re-index if content/title changed)
    if "content" in update_data or "title" in update_data:
        await arq_pool.enqueue_job("index_kb_article", article.id)
        logger.info(f"KB Article {article_id} updated, re-indexing enqueued...")

    return article

@router.delete("/{article_id}/", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def delete_kb_article(
    article_id: UUID,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """Agents/Admin only: Soft Delete a KB article."""
    # Redundant Role Hardening: Capture any leakage from require_roles decorator
    if current_user.role not in ALL_SC_ROLES:
        raise HTTPException(status_code=403, detail="Only SC staff can manage the knowledge base")

    stmt = select(KBArticle).where(
        KBArticle.id == article_id, 
        KBArticle.workspace_id == current_user.workspace_id,
        KBArticle.deleted_at.is_(None)
    )
    result = await db.execute(stmt)
    article = result.scalar_one_or_none()
    if not article:
        raise HTTPException(status_code=404, detail="Article not found")
        
    from sqlalchemy import delete
    article.deleted_at = datetime.utcnow()
    article.deleted_by_id = current_user.id
    article.is_published = False
    
    # Cascade inactivation to attachments
    att_stmt = (
        update(Attachment)
        .where(Attachment.article_id == article_id)
        .values(deleted_at=article.deleted_at)
    )
    await db.execute(att_stmt)
    
    # Purge chunks
    await db.execute(delete(KBArticleChunk).where(KBArticleChunk.article_id == article_id))
    
    db.add(article)
    await db.commit()
    logger.info(f"KB Article and children inactivated: {article_id} by user {current_user.id}")
    return {"status": "deleted"}

@router.post("/bulk-publish/", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def bulk_publish_articles(
    payload: KBBulkSyncRequest,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
    arq_pool: Any = Depends(get_arq_pool)
) -> Any:
    """Agents/Admin only: Bulk process (Create/Update) and Publish KB articles."""
    results = {"created": 0, "updated": 0, "ids": []}
    
    processed_article_ids = set()
    
    for art_def in payload.articles:
        # Check for existing by title in this workspace, excluding what we've already processed in this batch
        stmt = select(KBArticle).where(
            KBArticle.title == art_def.title,
            KBArticle.workspace_id == current_user.workspace_id,
            KBArticle.deleted_at.is_(None)
        )
        if processed_article_ids:
            # Cast to list for SQLAlchemy 2.0 cache-key compatibility
            stmt = stmt.where(KBArticle.id.not_in(list(processed_article_ids)))
            
        res = await db.execute(stmt)
        article = res.scalar_one_or_none()
        
        # Optimization: Only re-index if content/title actually changed OR it's a new article
        should_index = False
        
        if article:
            # Check if content-related fields changed
            if article.content != art_def.content or article.title != art_def.title:
                should_index = True
                
            article.content = art_def.content
            article.category = art_def.category
            article.project_id = art_def.project_id
            article.is_published = True
            results["updated"] += 1
        else:
            article = KBArticle(
                title=art_def.title,
                content=art_def.content,
                category=art_def.category,
                project_id=art_def.project_id,
                workspace_id=current_user.workspace_id,
                author_id=current_user.id,
                is_published=True
            )
            db.add(article)
            results["created"] += 1
            should_index = True
            
        await db.flush() # ensure ID is available
        processed_article_ids.add(article.id)
        results["ids"].append(str(article.id))
        
        # Trigger Unified ARQ Indexing Lifecycle ONLY if needed
        if should_index:
            await arq_pool.enqueue_job("index_kb_article", article.id)
            logger.info(f"KB Bulk: Indexing enqueued for {article.id}")
        else:
            logger.info(f"KB Bulk: Indexing skipped for {article.id} (no content changes)")
        
    await db.commit()
    logger.info(f"Bulk Sync & Publish (Isolated): {results['created']} created, {results['updated']} updated for workspace {current_user.workspace_id}")
    return {"status": "success", "summary": results}

@router.post("/bulk-unpublish/", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def bulk_unpublish_articles(
    payload: KBBulkActionRequest,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """Agents/Admin only: Bulk inactivate (Soft Delete) KB articles and their chunks."""
    from sqlalchemy import delete
    ids = payload.article_ids
    
    # 1. Soft Delete the Articles
    stmt = (
        update(KBArticle)
        .where(
            KBArticle.id.in_(ids),
            KBArticle.workspace_id == current_user.workspace_id,
            KBArticle.deleted_at.is_(None)
        )
        .values(
            deleted_at=datetime.utcnow(),
            deleted_by_id=current_user.id,
            is_published=False
        )
    )
    res = await db.execute(stmt)
    count = res.rowcount
    
    # 2. Hard Delete the Chunks (to deactivate search)
    chunk_del = delete(KBArticleChunk).where(KBArticleChunk.article_id.in_(ids))
    await db.execute(chunk_del)
    
    # 3. Soft Delete the Attachments
    att_del = (
        update(Attachment)
        .where(Attachment.article_id.in_(ids))
        .values(deleted_at=datetime.utcnow())
    )
    await db.execute(att_del)
    
    await db.commit()
    logger.info(f"Bulk Inactivation: {count} articles and their children deactivated by user {current_user.id}")
    return {"status": "success", "inactivated_count": count}