Spaces:
Paused

File size: 12,191 Bytes
5eb4857
6130eba
5eb4857
 
 
 
 
 
b7980f7
5eb4857
 
 
 
 
 
 
a27a4ab
01dccd3
5eb4857
a27a4ab
d050df5
b7980f7
a27a4ab
2b83560
5eb4857
186d110
 
 
5eb4857
 
d050df5
 
 
 
 
a27a4ab
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4401584
5eb4857
 
 
 
4401584
 
5eb4857
4401584
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
4401584
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4401584
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
186d110
 
 
b7980f7
 
 
5eb4857
 
 
 
 
b7980f7
 
 
 
 
 
 
 
186d110
 
 
b7980f7
 
 
 
 
 
 
 
2b83560
 
5eb4857
 
 
 
 
d050df5
 
 
 
 
 
5eb4857
 
 
 
 
 
0dcb0b7
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6130eba
 
 
 
8c5af7e
 
6130eba
8c5af7e
6130eba
 
 
8c5af7e
 
 
 
 
 
6130eba
 
 
ea4e72d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import Any, Dict, List, Optional
import uuid
from uuid import UUID
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, desc
from core.logging import get_logger
from models.user import User, UserRole
from models.user_workspace import UserWorkspace
from models.kb_article import KBArticle
from models.kb_article_chunk import KBArticleChunk

logger = get_logger(__name__)

async def get_available_agents(db: AsyncSession, workspace_id: UUID) -> List[User]:
    """
    Fetch all active INTERNAL staff members for the given workspace context.
    Strictly restricted to users with a direct UserWorkspace relationship.
    """
    # 1. Standard approach: Join with UserWorkspace and strictly whitelist staff roles
    stmt = select(User, UserWorkspace.role).join(UserWorkspace).where(
        UserWorkspace.workspace_id == workspace_id,
        UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), # INTERNAL ONLY
        User.global_role.is_distinct_from(UserRole.SUPERADMIN), # Exclude Global HQ from allocation
        User.is_active == True,
        User.deleted_at.is_(None),
        UserWorkspace.is_active == True,
        UserWorkspace.deleted_at.is_(None)
    )
    result = await db.execute(stmt)
    
    verified_staff = []
    for user, role in result.all():
        user.role = role
        verified_staff.append(user)
    
    logger.debug(f"Fetched {len(verified_staff)} verified staff agents for workspace {workspace_id}")
    return verified_staff

async def update_ticket_ai_metadata(db: AsyncSession, ticket_id: UUID, metadata: Dict[str, Any]):
    """
    Utility to update ticket AI metadata in the DB.
    """
    from models.ticket import Ticket
    stmt = select(Ticket).where(Ticket.id == ticket_id)
    result = await db.execute(stmt)
    ticket = result.scalar_one_or_none()
    if ticket:
        # Merge new metadata
        existing = ticket.ai_metadata or {}
        existing.update(metadata)
        ticket.ai_metadata = existing
        db.add(ticket)

async def semantic_search_kb(db: AsyncSession, workspace_id: UUID, query_embedding: List[float], limit: int = 3) -> List[Any]:
    """
    Search KBArticles by embedding.
    """
    from models.kb_article import KBArticle
    stmt = select(KBArticle).where(
        KBArticle.workspace_id == workspace_id,
        KBArticle.deleted_at.is_(None),
        KBArticle.duplicate_of_id.is_(None)
    ).order_by(
        KBArticle.embedding.cosine_distance(query_embedding)
    ).limit(limit)
    logger.info(f"AI: Semantic search KB for workspace {workspace_id}")
    result = await db.execute(stmt)
    return list(result.scalars().all())

async def semantic_search_past_tickets(db: AsyncSession, workspace_id: UUID, query_embedding: List[float], limit: int = 3) -> List[Any]:
    """
    Search resolved Tickets by embedding.
    """
    from models.ticket import Ticket, TicketStatus
    stmt = select(Ticket).where(
        Ticket.workspace_id == workspace_id,
        Ticket.status == TicketStatus.RESOLVED,
        Ticket.embedding.isnot(None),
        Ticket.deleted_at.is_(None)
    ).order_by(
        Ticket.embedding.cosine_distance(query_embedding)
    ).limit(limit)
    logger.info(f"AI: Semantic search past tickets for workspace {workspace_id}")
    result = await db.execute(stmt)
    return list(result.scalars().all())

async def hybrid_search_kb_internal(
    db: AsyncSession, 
    workspace_id: UUID, 
    query_text: str, 
    query_embedding: Optional[List[float]] = None,
    threshold: float = 0.2,
    limit: int = 5
) -> List[Dict[str, Any]]:
    """
    Internal utility for hybrid search (FTS + Vector).
    If query_embedding is None, it degrades to high-speed keyword FTS only.
    """
    # 1. Semantic Chunk Search (Gated by vector presence)
    semantic_results = []
    if query_embedding:
        semantic_stmt = (
            select(
                KBArticle,
                (1 - KBArticleChunk.embedding.cosine_distance(query_embedding)).label("sim_score")
            )
            .join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id)
            .where(
                KBArticle.workspace_id == workspace_id,
                KBArticle.deleted_at.is_(None),
                KBArticle.is_published == True,
                KBArticle.duplicate_of_id.is_(None)
            )
            .order_by(desc("sim_score"))
            .limit(20)
        )
        semantic_res = await db.execute(semantic_stmt)
        semantic_results = semantic_res.all()
    
    # 2. Keyword FTS Search
    fts_stmt = (
        select(
            KBArticle,
            func.ts_rank(
                func.to_tsvector('english', KBArticle.title + " " + KBArticle.content),
                func.plainto_tsquery('english', query_text)
            ).label("fts_rank")
        )
        .where(
            KBArticle.workspace_id == workspace_id,
            KBArticle.deleted_at.is_(None),
            KBArticle.is_published == True,
            KBArticle.duplicate_of_id.is_(None),
            func.to_tsvector('english', KBArticle.title + " " + KBArticle.content).op("@@")(func.plainto_tsquery('english', query_text))
        )
        .order_by(desc("fts_rank"))
        .limit(20)
    )
    fts_res = await db.execute(fts_stmt)

    # 3. Score Fusion
    article_scores = {}
    for article, sim in semantic_results:
        if article.id not in article_scores:
            article_scores[article.id] = {"obj": article, "semantic": sim, "fts": 0.0}
        else:
            article_scores[article.id]["semantic"] = max(article_scores[article.id]["semantic"], sim)

    for article, rank in fts_res.all():
        if article.id not in article_scores:
            article_scores[article.id] = {"obj": article, "semantic": 0.0, "fts": rank}
        else:
            article_scores[article.id]["fts"] = rank

    final_results = []
    for art_id, data in article_scores.items():
        score = (data["semantic"] * 0.7) + (min(data["fts"], 1.0) * 0.3)
        if score >= threshold:
            final_results.append({"article": data["obj"], "score": score})

    final_results.sort(key=lambda x: x["score"], reverse=True)
    return final_results[:limit]


async def get_workspace_manager(db: AsyncSession, workspace_id: UUID) -> Optional[User]:
    """Find the best person to notify in a workspace (Lead first, then Admin)."""
    # 1. Try to find a Lead within this workspace
    stmt = (
        select(User)
        .join(UserWorkspace)
        .where(
            UserWorkspace.workspace_id == workspace_id,
            UserWorkspace.role == UserRole.SC_LEAD,
            User.is_active == True,
            User.deleted_at.is_(None),
            UserWorkspace.is_active == True,
            UserWorkspace.deleted_at.is_(None)
        )
        .limit(1)
    )
    res = await db.execute(stmt)
    manager = res.scalar_one_or_none()
    if manager:
        return manager
        
    # 2. Fallback to an Admin associated with this workspace
    admin_stmt = (
        select(User)
        .join(UserWorkspace)
        .where(
            UserWorkspace.workspace_id == workspace_id,
            UserWorkspace.role == UserRole.SC_ADMIN,
            User.is_active == True,
            User.deleted_at.is_(None),
            UserWorkspace.is_active == True,
            UserWorkspace.deleted_at.is_(None)
        )
        .limit(1)
    )
    res = await db.execute(admin_stmt)
    manager = res.scalar_one_or_none()
    if manager:
        return manager

    # 3. Final Fallback: No Global HQ fallback per policy
    return None


import json
class CustomEncoder(json.JSONEncoder):
    """JSON encoder that handles UUID objects by converting them to strings."""
    def default(self, o):
        if isinstance(o, UUID):
            return str(o)
        if isinstance(o, datetime):
            return o.isoformat()
        return super().default(o)


def sanitize_for_db(data: Any) -> Any:
    """Recursively converts UUIDs and datetimes to strings for DB storage."""
    if isinstance(data, dict):
        return {k: sanitize_for_db(v) for k, v in data.items()}
    elif isinstance(data, (list, tuple, set)):
        return [sanitize_for_db(i) for i in data]
    elif isinstance(data, UUID):
        return str(data)
    elif isinstance(data, datetime):
        return data.isoformat()
    return data

def safe_uuid(val: Any) -> Optional[UUID]:
    """Safely attempts to cast a value to UUID. Returns None on failure."""
    if not val:
        return None
    if isinstance(val, UUID):
        return val
    try:
        # Check for common short-codes or hex strings that are not UUIDs
        s_val = str(val).strip()
        if len(s_val) < 32:
            return None
        return UUID(s_val)
    except (ValueError, TypeError, AttributeError):
        return None

def get_deterministic_uuid(val: Any) -> UUID:
    """
    Deterministically maps any input (string, int, etc) to a valid UUID v5.
    Ensures that arq string IDs (like cron tasks) can be stored in our UUID-based DB.
    If the input is already a valid UUID or UUID string, it returns it as-is to 
    prevent redundant hashing across system boundaries.
    """
    # 1. Direct object check
    if isinstance(val, UUID):
        return val
        
    # 2. String UUID check (crucial for API -> Worker synchronization)
    parsed = safe_uuid(val)
    if parsed:
        return parsed
        
    # 3. Deterministic Hash (Namespace v5)
    # Use a dedicated namespace for Nexus Worker jobs
    NEXUS_NAMESPACE = uuid.UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') # DNS Namespace as base
    return uuid.uuid5(NEXUS_NAMESPACE, str(val))


def parse_json_garbage(text: str) -> Dict[str, Any]:
    """
    Robustly extract and parse JSON from a string that may contain markdown,
    hallucinations, or descriptive garbage.
    """
    import re
    import json
    
    if not text:
        return {}

    # 1. Strip Markdown Blocks
    # Find everything between ```json and ``` or just ``` and ```
    text = re.sub(r'```json\s*(.*?)\s*```', r'\1', text, flags=re.DOTALL)
    text = re.sub(r'```\s*(.*?)\s*```', r'\1', text, flags=re.DOTALL)

    # 2. Locate the first { and last }
    start_idx = text.find('{')
    end_idx = text.rfind('}')
    
    if start_idx == -1 or end_idx == -1 or end_idx < start_idx:
        # Check for single values or simple lists if needed, but here we expect objects
        return {}
    
    clean_json = text[start_idx:end_idx+1]

    # 3. Repair common hallucinations
    # - Trailing commas: {"a": 1,} -> {"a": 1}
    clean_json = re.sub(r',\s*\}', '}', clean_json)
    clean_json = re.sub(r',\s*\]', ']', clean_json)
    
    # - Improper decimals: 123,45 -> 123.45 (European style)
    clean_json = re.sub(r'(\d+),(\d+)', r'\1.\2', clean_json)

    # 4. Attempt Parsing
    try:
        return json.loads(clean_json)
    except json.JSONDecodeError:
        # 5. Advanced Recovery: Strip descriptive garbage from numeric fields
        # Look for "key": ... and try to fix values
        # Specifically targeting "estimated_effort_hours" as seen in logs
        def numeric_repair(match):
            key_part = match.group(1)
            val_part = match.group(2)
            # Find first occurrence of a number (int or float) in the garbage
            nums = re.findall(r'\d+\.?\d*', val_part)
            if nums:
                return f'{key_part}{nums[0]}'
            return f'{key_part}1.0' # Default fallback for the field

        # This regex looks for specific numeric keys and tries to isolate the number
        clean_json = re.sub(r'("estimated_effort_hours"\s*:\s*)([^,}\]]+)', numeric_repair, clean_json)
        clean_json = re.sub(r'("confidence"\s*:\s*)([^,}\]]+)', numeric_repair, clean_json)

        try:
            return json.loads(clean_json)
        except Exception:
            # Last ditch: remove all non-ASCII if LLM hallucinated Russian/Chinese in keys/values
            # (risky but better than total failure in some cases)
            # Actually, let's just log and fail for now to avoid side effects
            return {}