Spaces:
Paused

dushyantsingh0 commited on
Commit
ea4e72d
·
1 Parent(s): 9f4dea0

backend stabilization

Browse files
agents/kb_node.py CHANGED
@@ -5,7 +5,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
5
  from langchain_core.runnables import RunnableConfig
6
 
7
  from agents.state import AgentState
8
- from agents.utils import hybrid_search_kb_internal
9
  from core.llm import get_text_embeddings
10
  from models.knowledge_insight import KnowledgeInsight, InsightType, InsightStatus
11
  from core.logging import get_logger
@@ -216,19 +216,20 @@ async def _perform_high_fidelity_gap_analysis(t_title: str, t_desc: str, a_title
216
  """Uses LLM to perform side-by-side gap analysis between ticket and existing article."""
217
  from core.llm import get_llm
218
  from langchain_core.prompts import ChatPromptTemplate
219
- from langchain_core.output_parsers import JsonOutputParser
220
-
221
  llm = get_llm()
222
  prompt = ChatPromptTemplate.from_template(GAP_ANALYSIS_PROMPT)
223
- chain = prompt | llm | JsonOutputParser()
224
 
225
  try:
226
- res = await chain.ainvoke({
227
  "ticket_title": t_title,
228
  "ticket_description": t_desc,
229
  "article_title": a_title,
230
  "article_content": a_content
231
  })
 
 
 
232
  return res if isinstance(res, dict) else {}
233
  except Exception as e:
234
  logger.error(f"Gap Analysis Failed: {str(e)}")
 
5
  from langchain_core.runnables import RunnableConfig
6
 
7
  from agents.state import AgentState
8
+ from agents.utils import hybrid_search_kb_internal, parse_json_garbage
9
  from core.llm import get_text_embeddings
10
  from models.knowledge_insight import KnowledgeInsight, InsightType, InsightStatus
11
  from core.logging import get_logger
 
216
  """Uses LLM to perform side-by-side gap analysis between ticket and existing article."""
217
  from core.llm import get_llm
218
  from langchain_core.prompts import ChatPromptTemplate
 
 
219
  llm = get_llm()
220
  prompt = ChatPromptTemplate.from_template(GAP_ANALYSIS_PROMPT)
221
+ chain = prompt | llm
222
 
223
  try:
224
+ raw_res = await chain.ainvoke({
225
  "ticket_title": t_title,
226
  "ticket_description": t_desc,
227
  "article_title": a_title,
228
  "article_content": a_content
229
  })
230
+
231
+ content = raw_res.content if hasattr(raw_res, 'content') else str(raw_res)
232
+ res = parse_json_garbage(content)
233
  return res if isinstance(res, dict) else {}
234
  except Exception as e:
235
  logger.error(f"Gap Analysis Failed: {str(e)}")
agents/triage.py CHANGED
@@ -7,6 +7,7 @@ import asyncio
7
 
8
  from core.llm import get_llm
9
  from agents.state import AgentState
 
10
  from models.ticket import TicketPriority
11
  from core.logging import get_logger
12
 
@@ -154,48 +155,12 @@ async def triage_node(state: AgentState, config: RunnableConfig) -> Dict[str, An
154
  else:
155
  raise ValueError("LLM returned empty responses after max attempts.")
156
 
157
- # Clean extraction logic
158
- import json
159
- import re
160
-
161
- def repair_json(raw: str) -> str:
162
- """Attempt to fix common LLM JSON hallucinations."""
163
- # 1. Fix European-style or hallucinated decimals: 156,50 -> 156.50
164
- # Matches "key": 123,45 and converts to "key": 123.45
165
- raw = re.sub(r'(:\s*)(\d+),(\d+)(\s*[,\}])', r'\1\2.\3\4', raw)
166
-
167
- # 2. Strip non-numeric/non-float garbage from estimated_effort_hours
168
- # Handle cases like "对待1.0"
169
- raw = re.sub(r'("estimated_effort_hours"\s*:\s*)([^\d\.]+)([\d\.]+)', r'\1\3', raw)
170
-
171
- # 3. Handle truncated JSON (missing closing braces)
172
- # Count open/close braces
173
- open_braces = raw.count('{')
174
- close_braces = raw.count('}')
175
- if open_braces > close_braces:
176
- raw += '}' * (open_braces - close_braces)
177
-
178
- # 4. Remove trailing commas before closing braces
179
- raw = re.sub(r',\s*\}', '}', raw)
180
-
181
- return raw
182
-
183
- # Robust JSON Locator
184
- extracted_json = content
185
  try:
186
- # Find the first { and the last }
187
- start_idx = content.find('{')
188
- end_idx = content.rfind('}')
189
-
190
- if start_idx != -1:
191
- if end_idx != -1 and end_idx > start_idx:
192
- extracted_json = content[start_idx:end_idx+1]
193
- else:
194
- extracted_json = content[start_idx:] # Truncated
195
-
196
- extracted_json = repair_json(extracted_json)
197
-
198
- clean_data = json.loads(extracted_json)
199
  # Resilience: Use .get() with defaults instead of strict constructor
200
  result_cat = clean_data.get("category", "OTHER")
201
  result_priority = clean_data.get("priority", "P2")
@@ -207,7 +172,10 @@ async def triage_node(state: AgentState, config: RunnableConfig) -> Dict[str, An
207
  try:
208
  result_effort = float(raw_effort)
209
  except (ValueError, TypeError):
210
- result_effort = 1.0
 
 
 
211
 
212
  result_complexity = clean_data.get("complexity", "low")
213
  result_reasoning = clean_data.get("reasoning", "Analysis synthesized via fallback parser.")
 
7
 
8
  from core.llm import get_llm
9
  from agents.state import AgentState
10
+ from agents.utils import parse_json_garbage
11
  from models.ticket import TicketPriority
12
  from core.logging import get_logger
13
 
 
155
  else:
156
  raise ValueError("LLM returned empty responses after max attempts.")
157
 
158
+ # Robust JSON Parsing
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  try:
160
+ clean_data = parse_json_garbage(content)
161
+ if not clean_data:
162
+ raise ValueError("Parser returned empty object")
163
+
 
 
 
 
 
 
 
 
 
164
  # Resilience: Use .get() with defaults instead of strict constructor
165
  result_cat = clean_data.get("category", "OTHER")
166
  result_priority = clean_data.get("priority", "P2")
 
172
  try:
173
  result_effort = float(raw_effort)
174
  except (ValueError, TypeError):
175
+ # Manual numeric extraction if parse_json_garbage missed a weird edge case
176
+ import re
177
+ nums = re.findall(r'\d+\.?\d*', str(raw_effort))
178
+ result_effort = float(nums[0]) if nums else 1.0
179
 
180
  result_complexity = clean_data.get("complexity", "low")
181
  result_reasoning = clean_data.get("reasoning", "Analysis synthesized via fallback parser.")
agents/utils.py CHANGED
@@ -252,3 +252,66 @@ def get_deterministic_uuid(val: Any) -> UUID:
252
  # Use a dedicated namespace for Nexus Worker jobs
253
  NEXUS_NAMESPACE = uuid.UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') # DNS Namespace as base
254
  return uuid.uuid5(NEXUS_NAMESPACE, str(val))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
  # Use a dedicated namespace for Nexus Worker jobs
253
  NEXUS_NAMESPACE = uuid.UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') # DNS Namespace as base
254
  return uuid.uuid5(NEXUS_NAMESPACE, str(val))
255
+
256
+
257
+ def parse_json_garbage(text: str) -> Dict[str, Any]:
258
+ """
259
+ Robustly extract and parse JSON from a string that may contain markdown,
260
+ hallucinations, or descriptive garbage.
261
+ """
262
+ import re
263
+ import json
264
+
265
+ if not text:
266
+ return {}
267
+
268
+ # 1. Strip Markdown Blocks
269
+ # Find everything between ```json and ``` or just ``` and ```
270
+ text = re.sub(r'```json\s*(.*?)\s*```', r'\1', text, flags=re.DOTALL)
271
+ text = re.sub(r'```\s*(.*?)\s*```', r'\1', text, flags=re.DOTALL)
272
+
273
+ # 2. Locate the first { and last }
274
+ start_idx = text.find('{')
275
+ end_idx = text.rfind('}')
276
+
277
+ if start_idx == -1 or end_idx == -1 or end_idx < start_idx:
278
+ # Check for single values or simple lists if needed, but here we expect objects
279
+ return {}
280
+
281
+ clean_json = text[start_idx:end_idx+1]
282
+
283
+ # 3. Repair common hallucinations
284
+ # - Trailing commas: {"a": 1,} -> {"a": 1}
285
+ clean_json = re.sub(r',\s*\}', '}', clean_json)
286
+ clean_json = re.sub(r',\s*\]', ']', clean_json)
287
+
288
+ # - Improper decimals: 123,45 -> 123.45 (European style)
289
+ clean_json = re.sub(r'(\d+),(\d+)', r'\1.\2', clean_json)
290
+
291
+ # 4. Attempt Parsing
292
+ try:
293
+ return json.loads(clean_json)
294
+ except json.JSONDecodeError:
295
+ # 5. Advanced Recovery: Strip descriptive garbage from numeric fields
296
+ # Look for "key": ... and try to fix values
297
+ # Specifically targeting "estimated_effort_hours" as seen in logs
298
+ def numeric_repair(match):
299
+ key_part = match.group(1)
300
+ val_part = match.group(2)
301
+ # Find first occurrence of a number (int or float) in the garbage
302
+ nums = re.findall(r'\d+\.?\d*', val_part)
303
+ if nums:
304
+ return f'{key_part}{nums[0]}'
305
+ return f'{key_part}1.0' # Default fallback for the field
306
+
307
+ # This regex looks for specific numeric keys and tries to isolate the number
308
+ clean_json = re.sub(r'("estimated_effort_hours"\s*:\s*)([^,}\]]+)', numeric_repair, clean_json)
309
+ clean_json = re.sub(r'("confidence"\s*:\s*)([^,}\]]+)', numeric_repair, clean_json)
310
+
311
+ try:
312
+ return json.loads(clean_json)
313
+ except Exception:
314
+ # Last ditch: remove all non-ASCII if LLM hallucinated Russian/Chinese in keys/values
315
+ # (risky but better than total failure in some cases)
316
+ # Actually, let's just log and fail for now to avoid side effects
317
+ return {}
docs/BACKEND_DIAGRAMS.md CHANGED
@@ -38,7 +38,7 @@ graph TB
38
  SU[Staff Browser]
39
  end
40
 
41
- subgraph "FastAPI Process (Gunicorn × 4 workers)"
42
  API[REST API\napi/v1/*]
43
  WS[WebSocket Manager\ncore/websockets.py]
44
  SSE[SSE Streaming\nnexus_stream.py]
@@ -628,7 +628,7 @@ sequenceDiagram
628
  participant DB as PostgreSQL
629
  participant Redis as Redis Local
630
 
631
- C->>API: POST /auth/login {email, password}
632
  API->>DB: SELECT user WHERE email=?
633
  DB-->>API: User record
634
  API->>API: bcrypt.verify(plain, hashed)
@@ -639,7 +639,7 @@ sequenceDiagram
639
  DB-->>API: workspace + role
640
  API->>API: create_access_token(sub, workspace_id, role, jti)
641
  API->>API: create_refresh_token(sub, jti)
642
- API-->>C: {access_token, refresh_token, expires_in}
643
  ```
644
 
645
  ### 5b. Request Authorization
@@ -652,7 +652,7 @@ flowchart TD
652
  VALID -- No --> R401[401 Unauthorized]
653
  VALID -- Yes --> BLOCKLIST{Token JTI\nin Redis blocklist?}
654
  BLOCKLIST -- Yes --> R401
655
- BLOCKLIST -- No --> TYPE{Token type\n== 'access'?}
656
  TYPE -- No --> R401
657
  TYPE -- Yes --> LOAD[Load User from DB]
658
  LOAD --> ACTIVE{user.is_active?}
@@ -672,18 +672,18 @@ sequenceDiagram
672
  participant Redis as Redis Local
673
 
674
  Note over C,Redis: Token Refresh
675
- C->>API: POST /auth/token/refresh {refresh_token}
676
- API->>API: decode refresh_token, verify type=="refresh"
677
- API->>Redis: GET token:blocklist:{jti}
678
  Redis-->>API: nil (not revoked)
679
  API->>API: issue new access_token
680
- API-->>C: {access_token}
681
 
682
  Note over C,Redis: Logout / Password Change
683
  C->>API: POST /auth/password/change or logout
684
- API->>Redis: SET token:blocklist:{jti} 1 EX {ttl}
685
  API-->>C: 200 OK
686
- Note right of Redis: Token is now permanently revoked\nfor remaining TTL
687
  ```
688
 
689
  ### 5d. WebSocket Authentication
@@ -694,16 +694,16 @@ sequenceDiagram
694
  participant WS as WebSocket Endpoint
695
  participant Redis as Redis Local
696
 
697
- B->>WS: WSS /ws/{workspace_id}?token={access_token}
698
  WS->>WS: decode_access_token(token)
699
- WS->>Redis: GET token:blocklist:{jti}
700
  Redis-->>WS: nil
701
  alt Token invalid / expired / revoked
702
  WS-->>B: Close 1008 Policy Violation
703
  end
704
  WS->>WS: Verify workspace_id matches token claim
705
  WS->>WS: Register connection in ConnectionManager
706
- WS->>Redis: SUBSCRIBE nexus:ws:workspace:{workspace_id}
707
  loop Keep-alive
708
  WS-->>B: Events from pub/sub
709
  B-->>WS: ping
@@ -780,29 +780,29 @@ sequenceDiagram
780
  participant ARQ as ARQ Job Queue (Redis Cloud)
781
  participant W as ARQ Worker
782
  participant LG as LangGraph Agent
783
- participant RS as Redis Stream\nnexus:stream:{job_id}
784
 
785
- B->>HTTP: POST /nexus/stream {query, workspace_id, thread_id}
786
  HTTP->>HTTP: Auth + rate limit check
787
  HTTP->>ARQ: enqueue nexus_stream_task(job_id, query, ...)
788
- HTTP-->>B: StreamingResponse (SSE headers, 200 OK)
789
 
790
- Note over HTTP,RS: HTTP worker now reads Redis Stream while streaming to browser
791
 
792
  W->>ARQ: dequeue nexus_stream_task
793
  W->>LG: invoke LangGraph with stream=True
794
  loop LangGraph execution
795
- LG-->>W: event (tool_called | tool_result | response_chunk)
796
- W->>RS: XADD nexus:stream:{job_id} event_data
797
  HTTP->>RS: XREAD BLOCK 3000ms
798
  RS-->>HTTP: event data
799
- HTTP-->>B: data: {event_type, content}\n\n
800
  end
801
  LG-->>W: complete
802
- W->>RS: XADD nexus:stream:{job_id} {type:complete}
803
- HTTP->>RS: XREAD → complete event
804
- HTTP-->>B: data: {type:complete}\n\n
805
- HTTP-->>B: [close stream]
806
  ```
807
 
808
  ---
@@ -813,17 +813,17 @@ sequenceDiagram
813
 
814
  ```mermaid
815
  stateDiagram-v2
816
- [*] --> OPEN : POST /tickets\n(customer creates)
817
 
818
- OPEN --> ACKNOWLEDGED : Staff claims ticket\nPATCH status=ACKNOWLEDGED
819
 
820
- ACKNOWLEDGED --> IN_PROGRESS : Staff begins work\nPATCH status=IN_PROGRESS
821
 
822
- IN_PROGRESS --> RESOLVED : Staff provides solution\nPATCH status=RESOLVED
823
 
824
- RESOLVED --> CLOSED : Customer confirms\nPATCH status=CLOSED
825
 
826
- OPEN --> IN_PROGRESS : Direct escalation\n(admin bypass)
827
 
828
  CLOSED --> [*] : Terminal state
829
 
@@ -838,7 +838,8 @@ stateDiagram-v2
838
  end note
839
 
840
  note right of IN_PROGRESS
841
- SLA breach monitored\nevery 5 minutes
 
842
  end note
843
 
844
  note right of RESOLVED
@@ -851,10 +852,10 @@ stateDiagram-v2
851
 
852
  ```mermaid
853
  graph LR
854
- P0[P0 — Critical\nImmediate response\nSLA: 1h] --> P1
855
- P1[P1 — High\nUrgent\nSLA: 4h] --> P2
856
- P2[P2 — Medium\nStandard\nSLA: 24h] --> P3
857
- P3[P3 — Low\nBest effort\nSLA: 72h]
858
 
859
  style P0 fill:#ff4444,color:#fff
860
  style P1 fill:#ff8800,color:#fff
@@ -877,7 +878,7 @@ sequenceDiagram
877
  participant ARQ as ARQ Queue
878
  participant WS as WebSocket Broadcast
879
 
880
- C->>API: POST /tickets {title, description, category, priority}
881
  API->>API: Validate auth + RBAC
882
  API->>SVC: create_ticket(payload, user, workspace)
883
  SVC->>DB: INSERT ticket (status=OPEN, priority, workspace_id)
@@ -888,7 +889,7 @@ sequenceDiagram
888
  SVC->>ARQ: enqueue generate_ticket_embedding(ticket_id)
889
  SVC->>WS: broadcast_to_workspace(workspace_id, ticket_created_event)
890
  SVC-->>API: TicketResponse
891
- API-->>C: 201 {ticket_id, status: OPEN, ...}
892
  ```
893
 
894
  ### 8b. AI Triage LangGraph Pipeline
@@ -937,7 +938,7 @@ flowchart TD
937
 
938
  LOGWF[Update ai_workflow.status=SUCCESS\nLog AI interactions to ai_interactions\nUpdate WorkerJob record] --> NOTIFY
939
 
940
- NOTIFY[send_triple_notification:\nassigned staff + customer] --> END([Done])
941
  ```
942
 
943
  ---
@@ -962,37 +963,36 @@ flowchart TD
962
  CHECK -- Yes --> ACTION{rule.action}
963
 
964
  ACTION -- NOTIFY_LEAD --> NOTIF[Find SC_LEAD users\nin workspace\nSend notification + email]
965
- ACTION -- REASSIGN --> REASSIGN[Find available agent\nUpdate ticket.assigned_to\nBroadcast reassignment]
966
  ACTION -- AUTO_RESOLVE --> AUTORES[Set ticket status=RESOLVED\nAdd system message]
967
 
968
- NOTIF & REASSIGN & AUTORES --> AUDIT
969
 
970
- AUDIT[INSERT escalation_audit_log\n{ticket_id, rule_id, action_taken}] --> BROADCAST
971
 
972
- BROADCAST[broadcast_to_workspace:\nescalation_triggered event] --> NEXTTICKET
973
  ```
974
 
975
  ### 9b. SLA Breach Timeline
976
 
977
  ```mermaid
978
  gantt
979
- title SLA Breach Timeline Example (P1 Ticket — 4h SLA)
980
  dateFormat HH:mm
981
  axisFormat %H:%M
982
 
983
  section Ticket Lifecycle
984
- Created (OPEN) :milestone, 00:00, 0m
985
  AI Triage completes :active, 00:00, 5m
986
- Assigned (ACKNOWLEDGED) :milestone, 00:05, 0m
987
- SLA deadline :crit, milestone, 04:00, 0m
988
 
989
  section SLA Monitoring
990
- Monitor run 1 :05:00, 1m
991
- Monitor run 2 :10:00, 1m
992
- Monitor run 3 (3h mark) :03:00, 1m
993
  NOTIFY_LEAD at 3h 30m :crit, 03:30, 1m
994
  REASSIGN at 4h :crit, 04:00, 1m
995
- Monitor run at breach :crit, 04:00, 1m
996
  ```
997
 
998
  ---
@@ -1008,29 +1008,29 @@ sequenceDiagram
1008
  participant DB as PostgreSQL
1009
  participant ARQ as ARQ Queue
1010
  participant W as ARQ Worker
1011
- participant EMB as Embedding Model\nnomic-embed-text-1.5
1012
  participant Cache as Redis Cache
1013
 
1014
- A->>API: POST /kb {title, content, category, project_id}
1015
  API->>DB: INSERT kb_articles (version=1)
1016
  API->>DB: INSERT kb_article_versions (version_number=1)
1017
  DB-->>API: article_id
1018
  API->>ARQ: enqueue index_kb_article(article_id)
1019
- API->>Cache: DEL kb:list:{workspace_id}:*
1020
- API->>Cache: DEL kb:categories:{workspace_id}
1021
- API->>Cache: DEL cache:search:kb:{workspace_id}:*
1022
  API-->>A: 201 KBArticleResponse
1023
 
1024
  W->>ARQ: dequeue index_kb_article
1025
  W->>DB: SELECT kb_article WHERE id=article_id
1026
  W->>W: chunk_content(content, size=1200, overlap=200)
1027
  loop For each chunk
1028
- W->>EMB: embed(chunk_text) → 768-dim vector
1029
  W->>DB: UPSERT kb_article_chunks (chunk_index, content, embedding)
1030
  end
1031
  W->>W: compute centroid embedding (avg of all chunks)
1032
  W->>DB: UPDATE kb_articles SET embedding=centroid, version+=1
1033
- W->>DB: UPDATE kb_articles SET search_vector=to_tsvector(title||content)
1034
  W->>W: sync_images_to_storage(article_id)
1035
  W->>DB: UPDATE worker_jobs SET status=SUCCESS
1036
  ```
@@ -1039,7 +1039,7 @@ sequenceDiagram
1039
 
1040
  ```mermaid
1041
  flowchart TD
1042
- UPDATE[PATCH /kb/:id\n{title?, content?, category?}] --> FETCH[Fetch current article]
1043
  FETCH --> NEWVER[INSERT kb_article_versions\nversion_number = current + 1]
1044
  NEWVER --> UPDARTICLE[UPDATE kb_articles\ncontent, title, category\nincrement version]
1045
  UPDARTICLE --> REINDEX[Enqueue index_kb_article\nre-embed all chunks]
@@ -1074,7 +1074,7 @@ flowchart TD
1074
 
1075
  ```mermaid
1076
  flowchart TD
1077
- QUERY[Search Query\nGET /kb/search?q=...] --> CACHE{Redis semantic\ncache hit?\ncache:search:kb:ws:hash}
1078
 
1079
  CACHE -- Hit --> RETURN_CACHE[Return cached results\nTTL: 300s]
1080
 
@@ -1089,7 +1089,7 @@ flowchart TD
1089
  end
1090
 
1091
  subgraph "Branch 2: Semantic Search"
1092
- B2[Generate query embedding\nnomic-embed-text-1.5\n768-dim vector\nHNSW index: idx_kb_embedding_hnsw\nQuery: embedding <=> query_vector\nReturns: distance + article_id]
1093
  end
1094
 
1095
  subgraph "Branch 3: Multimodal Search"
@@ -1098,13 +1098,13 @@ flowchart TD
1098
 
1099
  B1 & B2 & B3 --> MERGE[Merge results by article_id]
1100
 
1101
- MERGE --> SCORE[Score each article:\ntext_score = ts_rank × 0.40\nsemantic_score = 1 - distance/2 × 0.60\nimage_bonus = caption_score × 0.10\nfinal = text + semantic + image]
1102
 
1103
  SCORE --> SORT[Sort by final score DESC\nDedup by article_id\nLimit: top N results]
1104
 
1105
  SORT --> STORE_CACHE[SETEX cache:search:kb:ws:hash\nTTL: 300s]
1106
 
1107
- STORE_CACHE --> RESPONSE[Return {articles, scores, match_types}]
1108
  ```
1109
 
1110
  ### 11b. Ticket Search Flow
@@ -1137,11 +1137,11 @@ flowchart TD
1137
  AGENT[Agent: kb_search_tool\nquery + workspace_id] --> SEMCACHE{Semantic cache hit?\nnexus:semantic_cache:ws:hash}
1138
  SEMCACHE -- Yes --> CACHED[Return cached answer\nTTL: 3600s]
1139
  SEMCACHE -- No --> EMBED[Generate query embedding]
1140
- EMBED --> CHUNKS[Query kb_article_chunks:\nSELECT * ORDER BY\nembedding <=> query_vector\nLIMIT 5]
1141
  CHUNKS --> CONTEXT[Build RAG context:\nchunk_1 + chunk_2 + ... + chunk_5]
1142
  CONTEXT --> LLM[Claude: synthesize answer\nusing chunks as context]
1143
  LLM --> STORECACHE[Store in semantic cache\nnexus:semantic_cache:ws:hash\nTTL: 3600s]
1144
- STORECACHE --> RETURN[Return {answer, sources, chunks}]
1145
  ```
1146
 
1147
  ---
@@ -1152,7 +1152,7 @@ flowchart TD
1152
 
1153
  ```mermaid
1154
  graph TD
1155
- subgraph "ARQ Queue (Redis Cloud — Upstash)"
1156
  Q[arq:regular\njob queue]
1157
  CRON_Q[cron schedule\nstored in Redis]
1158
  end
@@ -1192,22 +1192,22 @@ gantt
1192
  axisFormat %H:%M
1193
 
1194
  section System
1195
- record_system_heartbeat (every 1 min) :active, 00:00, 1440m
1196
- monitor_sla_thresholds (every 5 min) :active, 00:00, 1440m
1197
- nexus_pulse_check (every 5 min) :active, 00:00, 1440m
1198
 
1199
  section Cache
1200
- purge_stale_semantic_cache (every 1 hr) :00:00, 60m
1201
- purge_stale_semantic_cache :01:00, 60m
1202
- purge_stale_semantic_cache :02:00, 60m
1203
 
1204
  section Insights
1205
- refresh_active_workspace_insights (30min):00:00, 30m
1206
- refresh_active_workspace_insights :00:30, 30m
1207
- refresh_active_workspace_insights :01:00, 30m
1208
 
1209
  section Analytics
1210
- generate_nightly_analytics (2am daily) :crit, 02:00, 30m
1211
  ```
1212
 
1213
  ### 12c. On-Demand Task Catalog
@@ -1230,7 +1230,7 @@ graph LR
1230
 
1231
  subgraph "Triggered by Cron"
1232
  OD9[generate_global_insight\nworkspace nightly]
1233
- OD10[crystallize_memory\nold interactions → memory]
1234
  OD11[generate_workspace_insights\ndashboard refresh]
1235
  OD12[ai_dynamic_nudge_pulse\nproactive suggestions]
1236
  end
@@ -1269,13 +1269,11 @@ flowchart TD
1269
 
1270
  CT_INTENT & KB_INTENT & AN_INTENT & AS_INTENT --> INTENT
1271
 
1272
- LLM_CLASSIFY --> INTENT
1273
-
1274
  INTENT[Resolved intent] --> SEMCACHE
1275
 
1276
- SEMCACHE{Semantic cache\nhit?\nnexus:semantic_cache:ws:hash} -- Hit --> RETURN_CACHED[Return cached answer]
1277
 
1278
- SEMCACHE -- Miss --> TOOL_SELECT[tool_selector node\nMap intent → tool function]
1279
 
1280
  TOOL_SELECT --> TOOL_EXEC[execute_tool node\nRun selected tool\nfrom tool registry]
1281
 
@@ -1283,7 +1281,7 @@ flowchart TD
1283
 
1284
  VERIFY{Risky action?\ncreate_ticket\nchange_status} -- Yes + not approved --> APPROVAL[Request human approval\naction_approved: false]
1285
 
1286
- VERIFY -- No risk\nor approved --> RESPOND
1287
 
1288
  APPROVAL --> INPUT
1289
 
@@ -1296,26 +1294,26 @@ flowchart TD
1296
 
1297
  ```mermaid
1298
  mindmap
1299
- root((Nexus Tools\nagents/tools/nexus_tools.py))
1300
  Knowledge Base
1301
- kb_search_tool\nquery + workspace_id + role
1302
- recall_knowledge\nquery from memory
1303
  Tickets
1304
- create_ticket_tool\ntitle + description + priority
1305
- search_tickets_tool\nquery + status + priority
1306
- get_ticket_details_tool\nticket_id
1307
- add_ticket_comment_tool\nticket_id + content + is_internal
1308
- change_ticket_status_tool\nticket_id + new_status
1309
- assign_ticket_tool\nticket_id + user_id
1310
- update_ticket_attributes_tool\nticket_id + attributes dict
1311
- similar_incident_finder\nticket_id
1312
  Analytics
1313
- nexus_analytics_tool\nworkspace_id + metric
1314
- sla_audit_tool\nworkspace_id
1315
- summarize_workspace_tool\nworkspace_id
1316
- sentiment_pulse_tool\nticket_id
1317
  Projects
1318
- project_pulse_tool\nproject_id
1319
  ```
1320
 
1321
  ### 13c. RBAC Tool Enforcement
@@ -1355,7 +1353,7 @@ flowchart LR
1355
  end
1356
 
1357
  subgraph "Semantic Cache"
1358
- SCACHE[nexus_semantic_cache\nDB + Redis\nworkspace:hash → answer\nTTL: 1h]
1359
  end
1360
 
1361
  INTER -- crystallize_memory\ncron task --> MEM
@@ -1379,17 +1377,17 @@ sequenceDiagram
1379
  participant Q as ARQ Queue (Redis Cloud)
1380
  participant W as ARQ Worker
1381
  participant G as LangGraph
1382
- participant T as Tool (e.g. kb_search)
1383
- participant RS as Redis Stream\nnexus:stream:{job_id}
1384
 
1385
- B->>API: POST /nexus/stream\n{query, workspace_id, thread_id}
1386
  API->>API: Generate job_id = uuid4()
1387
  API->>Q: LPUSH arq:regular nexus_stream_task(job_id, ...)
1388
- API-->>B: HTTP 200 + SSE headers\nContent-Type: text/event-stream
1389
 
1390
  par HTTP worker reads stream
1391
  loop until complete
1392
- API->>RS: XREAD BLOCK 3000ms STREAMS nexus:stream:{job_id} $
1393
  RS-->>API: events if any
1394
  API-->>B: SSE data frames
1395
  end
@@ -1397,17 +1395,17 @@ sequenceDiagram
1397
  W->>Q: BRPOP arq:regular
1398
  Q-->>W: nexus_stream_task job
1399
  W->>G: compile_graph().stream(state)
1400
- G->>RS: XADD {type:thinking, content:"Classifying intent..."}
1401
  G->>G: fast-track / classify intent
1402
- G->>RS: XADD {type:tool_called, tool:"kb_search_tool", args:{...}}
1403
  G->>T: execute kb_search_tool(query)
1404
- T-->>G: {articles, chunks, answer}
1405
- G->>RS: XADD {type:tool_result, tool:"kb_search_tool", result:{...}}
1406
- G->>G: respond node — stream Claude response
1407
  loop Response tokens
1408
- G->>RS: XADD {type:response_chunk, content:"token"}
1409
  end
1410
- G->>RS: XADD {type:complete, thread_id:"...", interaction_id:"..."}
1411
  W->>W: save NexusInteraction to DB
1412
  W->>W: enqueue vectorize_nexus_interaction
1413
  end
@@ -1434,26 +1432,26 @@ data: {"type":"complete","thread_id":"...","interaction_id":"..."}
1434
  mindmap
1435
  root((Redis Local\nlocalhost:6379))
1436
  Pub/Sub Channels
1437
- nexus:ws:workspace:uuid\nAll users in workspace
1438
- nexus:ws:user:uuid\nSingle user cross-process
1439
- nexus:ws:role:ws_uuid:role\nRole-targeted broadcast
1440
- nexus:ws:ticket:uuid\nTicket thread participants
1441
  Streams
1442
- nexus:stream:job_id\nSSE event pipeline\nXADD by worker\nXREAD by HTTP
1443
  Cache Keys
1444
- kb:list:ws_id:filter_hash\nKB article list\nTTL: 300s
1445
- kb:categories:ws_id\nCategory list\nTTL: 300s
1446
- cache:search:kb:ws_id:query_hash\nKB search results\nTTL: 300s
1447
- cache:search:ticket:ws_id:query_hash\nTicket search results\nTTL: 300s
1448
- dashboard:insights:ws_id:date\nDashboard AI insights\nTTL: 3600s
1449
- nexus:semantic_cache:ws:hash\nAgent query→answer\nTTL: 3600s
1450
  Rate Limiting
1451
- rl:user:user_id\nSliding window counter\nCUSTOMER: 10/min\nAGENT: 60/min\nADMIN: 120/min
1452
  Token Blocklist
1453
- token:blocklist:jti\nRevoked JWT tokens\nTTL = token expiry
1454
  Distributed Locks
1455
- nexus:latch:cron:job_name\nPrevents duplicate cron runs\nTTL: job duration
1456
- nexus:latch:job:job_id\nJob execution lock
1457
  ```
1458
 
1459
  ---
@@ -1468,13 +1466,11 @@ flowchart TD
1468
 
1469
  ENQUEUE[ARQ: enqueue\nsend_triple_notification\nuser_id + type + payload] --> W
1470
 
1471
- W[ARQ Worker\ntasks/notifications.py] --> PARALLEL
1472
-
1473
- PARALLEL --> N1 & N2 & N3
1474
 
1475
  subgraph "In-App Notification"
1476
- N1[INSERT notifications\n{workspace_id, user_id, type,\ntitle, content, is_read=false}]
1477
- N1 --> WS_NOTIF[PUBLISH\nnexus:ws:user:user_id\n{type: notification, ...}]
1478
  end
1479
 
1480
  subgraph "Email Notification"
@@ -1483,11 +1479,11 @@ flowchart TD
1483
 
1484
  subgraph "Webhook"
1485
  N3{Workspace has\nwebhook URL?}
1486
- N3 -- Yes --> WEBHOOK[HTTP POST to webhook URL\n{event_type, payload, workspace_id}]
1487
  N3 -- No --> SKIP[Skip]
1488
  end
1489
 
1490
- N1 & N2 & N3 --> DONE([Done])
1491
  ```
1492
 
1493
  ### 16b. @Mention Notification
@@ -1501,16 +1497,16 @@ sequenceDiagram
1501
  participant W as Worker
1502
  participant WS as WebSocket
1503
 
1504
- U->>API: POST /tickets/:id/messages\n{content: "Hey @alice can you check this?"}
1505
- API->>DB: INSERT message {content, mentions: ["alice_id"]}
1506
- API->>ARQ: enqueue notify_mentions(message_id, ["alice_id"])
1507
  API-->>U: 201 MessageResponse
1508
 
1509
  W->>ARQ: dequeue notify_mentions
1510
  W->>DB: SELECT users WHERE id IN mentions
1511
  loop For each mentioned user
1512
- W->>DB: INSERT notification (type=MENTION)
1513
- W->>WS: PUBLISH nexus:ws:user:{mentioned_id}\n{type: mention, ticket_id, message_snippet}
1514
  end
1515
  ```
1516
 
@@ -1529,11 +1525,11 @@ sequenceDiagram
1529
  participant DB as PostgreSQL
1530
  participant ARQ as ARQ Queue
1531
 
1532
- U->>API: POST multipart/form-data {file, ticket_id}
1533
- API->>API: Validate: size, content_type whitelist
1534
  API->>FS: store(file_bytes, path=workspace/ticket/filename)
1535
- FS-->>API: storage_path, storage_backend
1536
- API->>DB: INSERT attachments\n{ticket_id, filename, storage_path,\ncontent_type, file_size}
1537
  DB-->>API: attachment_id
1538
 
1539
  alt Image attachment (image/*)
@@ -1541,7 +1537,7 @@ sequenceDiagram
1541
  Note right of ARQ: Worker calls Claude Vision API\nUpdates attachment.ai_caption\nUsed in multimodal search
1542
  end
1543
 
1544
- API-->>U: 201 AttachmentResponse {id, filename, url}
1545
  ```
1546
 
1547
  ### 17b. Download
@@ -1579,7 +1575,7 @@ flowchart TD
1579
 
1580
  GAPS[Identify recurring topics\nnot covered by existing KB articles\nCompare via semantic search] --> INSIGHTS
1581
 
1582
- INSIGHTS[For each gap:\n- Generate suggested_title\n- Generate draft suggested_content\n- Assign confidence score 0-1] --> STORE
1583
 
1584
  STORE[UPSERT knowledge_insights\nlink to source tickets\nvia knowledge_insight_tickets] --> CACHE
1585
 
 
38
  SU[Staff Browser]
39
  end
40
 
41
+ subgraph "FastAPI Process (Gunicorn x4 workers)"
42
  API[REST API\napi/v1/*]
43
  WS[WebSocket Manager\ncore/websockets.py]
44
  SSE[SSE Streaming\nnexus_stream.py]
 
628
  participant DB as PostgreSQL
629
  participant Redis as Redis Local
630
 
631
+ C->>API: POST /auth/login email + password
632
  API->>DB: SELECT user WHERE email=?
633
  DB-->>API: User record
634
  API->>API: bcrypt.verify(plain, hashed)
 
639
  DB-->>API: workspace + role
640
  API->>API: create_access_token(sub, workspace_id, role, jti)
641
  API->>API: create_refresh_token(sub, jti)
642
+ API-->>C: access_token + refresh_token + expires_in
643
  ```
644
 
645
  ### 5b. Request Authorization
 
652
  VALID -- No --> R401[401 Unauthorized]
653
  VALID -- Yes --> BLOCKLIST{Token JTI\nin Redis blocklist?}
654
  BLOCKLIST -- Yes --> R401
655
+ BLOCKLIST -- No --> TYPE{Token type\n== access?}
656
  TYPE -- No --> R401
657
  TYPE -- Yes --> LOAD[Load User from DB]
658
  LOAD --> ACTIVE{user.is_active?}
 
672
  participant Redis as Redis Local
673
 
674
  Note over C,Redis: Token Refresh
675
+ C->>API: POST /auth/token/refresh with refresh_token
676
+ API->>API: decode refresh_token, verify type==refresh
677
+ API->>Redis: GET token:blocklist:JTI
678
  Redis-->>API: nil (not revoked)
679
  API->>API: issue new access_token
680
+ API-->>C: new access_token
681
 
682
  Note over C,Redis: Logout / Password Change
683
  C->>API: POST /auth/password/change or logout
684
+ API->>Redis: SET token:blocklist:JTI 1 EX TTL_SECS
685
  API-->>C: 200 OK
686
+ Note right of Redis: Token revoked for remaining TTL
687
  ```
688
 
689
  ### 5d. WebSocket Authentication
 
694
  participant WS as WebSocket Endpoint
695
  participant Redis as Redis Local
696
 
697
+ B->>WS: WSS /ws/WORKSPACE_ID?token=ACCESS_TOKEN
698
  WS->>WS: decode_access_token(token)
699
+ WS->>Redis: GET token:blocklist:JTI
700
  Redis-->>WS: nil
701
  alt Token invalid / expired / revoked
702
  WS-->>B: Close 1008 Policy Violation
703
  end
704
  WS->>WS: Verify workspace_id matches token claim
705
  WS->>WS: Register connection in ConnectionManager
706
+ WS->>Redis: SUBSCRIBE nexus:ws:workspace:WORKSPACE_ID
707
  loop Keep-alive
708
  WS-->>B: Events from pub/sub
709
  B-->>WS: ping
 
780
  participant ARQ as ARQ Job Queue (Redis Cloud)
781
  participant W as ARQ Worker
782
  participant LG as LangGraph Agent
783
+ participant RS as Redis Stream
784
 
785
+ B->>HTTP: POST /nexus/stream query + workspace_id + thread_id
786
  HTTP->>HTTP: Auth + rate limit check
787
  HTTP->>ARQ: enqueue nexus_stream_task(job_id, query, ...)
788
+ HTTP-->>B: StreamingResponse SSE headers 200 OK
789
 
790
+ Note over HTTP,RS: HTTP worker reads Redis Stream while streaming to browser
791
 
792
  W->>ARQ: dequeue nexus_stream_task
793
  W->>LG: invoke LangGraph with stream=True
794
  loop LangGraph execution
795
+ LG-->>W: event tool_called or tool_result or response_chunk
796
+ W->>RS: XADD nexus:stream:JOB_ID event_data
797
  HTTP->>RS: XREAD BLOCK 3000ms
798
  RS-->>HTTP: event data
799
+ HTTP-->>B: SSE data frame
800
  end
801
  LG-->>W: complete
802
+ W->>RS: XADD nexus:stream:JOB_ID type=complete
803
+ HTTP->>RS: XREAD complete event
804
+ HTTP-->>B: SSE complete event
805
+ HTTP-->>B: close stream
806
  ```
807
 
808
  ---
 
813
 
814
  ```mermaid
815
  stateDiagram-v2
816
+ [*] --> OPEN : POST /tickets (customer creates)
817
 
818
+ OPEN --> ACKNOWLEDGED : Staff claims ticket
819
 
820
+ ACKNOWLEDGED --> IN_PROGRESS : Staff begins work
821
 
822
+ IN_PROGRESS --> RESOLVED : Staff provides solution
823
 
824
+ RESOLVED --> CLOSED : Customer confirms
825
 
826
+ OPEN --> IN_PROGRESS : Direct escalation (admin bypass)
827
 
828
  CLOSED --> [*] : Terminal state
829
 
 
838
  end note
839
 
840
  note right of IN_PROGRESS
841
+ SLA breach monitored
842
+ every 5 minutes
843
  end note
844
 
845
  note right of RESOLVED
 
852
 
853
  ```mermaid
854
  graph LR
855
+ P0[P0 - Critical\nImmediate response\nSLA: 1h] --> P1
856
+ P1[P1 - High\nUrgent\nSLA: 4h] --> P2
857
+ P2[P2 - Medium\nStandard\nSLA: 24h] --> P3
858
+ P3[P3 - Low\nBest effort\nSLA: 72h]
859
 
860
  style P0 fill:#ff4444,color:#fff
861
  style P1 fill:#ff8800,color:#fff
 
878
  participant ARQ as ARQ Queue
879
  participant WS as WebSocket Broadcast
880
 
881
+ C->>API: POST /tickets title + description + category + priority
882
  API->>API: Validate auth + RBAC
883
  API->>SVC: create_ticket(payload, user, workspace)
884
  SVC->>DB: INSERT ticket (status=OPEN, priority, workspace_id)
 
889
  SVC->>ARQ: enqueue generate_ticket_embedding(ticket_id)
890
  SVC->>WS: broadcast_to_workspace(workspace_id, ticket_created_event)
891
  SVC-->>API: TicketResponse
892
+ API-->>C: 201 ticket_id + status OPEN
893
  ```
894
 
895
  ### 8b. AI Triage LangGraph Pipeline
 
938
 
939
  LOGWF[Update ai_workflow.status=SUCCESS\nLog AI interactions to ai_interactions\nUpdate WorkerJob record] --> NOTIFY
940
 
941
+ NOTIFY[send_triple_notification\nassigned staff + customer] --> END([Done])
942
  ```
943
 
944
  ---
 
963
  CHECK -- Yes --> ACTION{rule.action}
964
 
965
  ACTION -- NOTIFY_LEAD --> NOTIF[Find SC_LEAD users\nin workspace\nSend notification + email]
966
+ ACTION -- REASSIGN --> DO_REASSIGN[Find available agent\nUpdate ticket.assigned_to\nBroadcast reassignment]
967
  ACTION -- AUTO_RESOLVE --> AUTORES[Set ticket status=RESOLVED\nAdd system message]
968
 
969
+ NOTIF & DO_REASSIGN & AUTORES --> AUDIT
970
 
971
+ AUDIT[INSERT escalation_audit_log\nticket_id + rule_id + action_taken] --> BROADCAST
972
 
973
+ BROADCAST[broadcast_to_workspace\nescalation_triggered event] --> NEXTTICKET
974
  ```
975
 
976
  ### 9b. SLA Breach Timeline
977
 
978
  ```mermaid
979
  gantt
980
+ title SLA Breach Timeline Example (P1 Ticket - 4h SLA)
981
  dateFormat HH:mm
982
  axisFormat %H:%M
983
 
984
  section Ticket Lifecycle
985
+ Created OPEN :milestone, m1, 00:00, 1m
986
  AI Triage completes :active, 00:00, 5m
987
+ Assigned ACKNOWLEDGED :milestone, m2, 00:05, 1m
988
+ SLA deadline :crit, milestone, m3, 04:00, 1m
989
 
990
  section SLA Monitoring
991
+ Monitor run 1 :active, 00:05, 1m
992
+ Monitor run 2 :active, 00:10, 1m
993
+ Monitor run at 3h mark :active, 03:00, 1m
994
  NOTIFY_LEAD at 3h 30m :crit, 03:30, 1m
995
  REASSIGN at 4h :crit, 04:00, 1m
 
996
  ```
997
 
998
  ---
 
1008
  participant DB as PostgreSQL
1009
  participant ARQ as ARQ Queue
1010
  participant W as ARQ Worker
1011
+ participant EMB as Embedding Model
1012
  participant Cache as Redis Cache
1013
 
1014
+ A->>API: POST /kb title + content + category + project_id
1015
  API->>DB: INSERT kb_articles (version=1)
1016
  API->>DB: INSERT kb_article_versions (version_number=1)
1017
  DB-->>API: article_id
1018
  API->>ARQ: enqueue index_kb_article(article_id)
1019
+ API->>Cache: DEL kb:list:WORKSPACE_ID:*
1020
+ API->>Cache: DEL kb:categories:WORKSPACE_ID
1021
+ API->>Cache: DEL cache:search:kb:WORKSPACE_ID:*
1022
  API-->>A: 201 KBArticleResponse
1023
 
1024
  W->>ARQ: dequeue index_kb_article
1025
  W->>DB: SELECT kb_article WHERE id=article_id
1026
  W->>W: chunk_content(content, size=1200, overlap=200)
1027
  loop For each chunk
1028
+ W->>EMB: embed(chunk_text) returns 768-dim vector
1029
  W->>DB: UPSERT kb_article_chunks (chunk_index, content, embedding)
1030
  end
1031
  W->>W: compute centroid embedding (avg of all chunks)
1032
  W->>DB: UPDATE kb_articles SET embedding=centroid, version+=1
1033
+ W->>DB: UPDATE kb_articles SET search_vector=to_tsvector(title+content)
1034
  W->>W: sync_images_to_storage(article_id)
1035
  W->>DB: UPDATE worker_jobs SET status=SUCCESS
1036
  ```
 
1039
 
1040
  ```mermaid
1041
  flowchart TD
1042
+ UPDATE[PATCH /kb/:id\ntitle? + content? + category?] --> FETCH[Fetch current article]
1043
  FETCH --> NEWVER[INSERT kb_article_versions\nversion_number = current + 1]
1044
  NEWVER --> UPDARTICLE[UPDATE kb_articles\ncontent, title, category\nincrement version]
1045
  UPDARTICLE --> REINDEX[Enqueue index_kb_article\nre-embed all chunks]
 
1074
 
1075
  ```mermaid
1076
  flowchart TD
1077
+ QUERY[Search Query\nGET /kb/search?q=...] --> CACHE{Redis cache hit?\ncache:search:kb:ws:hash}
1078
 
1079
  CACHE -- Hit --> RETURN_CACHE[Return cached results\nTTL: 300s]
1080
 
 
1089
  end
1090
 
1091
  subgraph "Branch 2: Semantic Search"
1092
+ B2[Generate query embedding\nnomic-embed-text-1.5\n768-dim vector\nHNSW index: idx_kb_embedding_hnsw\nQuery: embedding cosine distance\nReturns: distance + article_id]
1093
  end
1094
 
1095
  subgraph "Branch 3: Multimodal Search"
 
1098
 
1099
  B1 & B2 & B3 --> MERGE[Merge results by article_id]
1100
 
1101
+ MERGE --> SCORE[Score each article:\ntext_score = ts_rank x 0.40\nsemantic_score = 1 - distance/2 x 0.60\nimage_bonus = caption_score x 0.10\nfinal = text + semantic + image]
1102
 
1103
  SCORE --> SORT[Sort by final score DESC\nDedup by article_id\nLimit: top N results]
1104
 
1105
  SORT --> STORE_CACHE[SETEX cache:search:kb:ws:hash\nTTL: 300s]
1106
 
1107
+ STORE_CACHE --> RESPONSE[Return articles + scores + match_types]
1108
  ```
1109
 
1110
  ### 11b. Ticket Search Flow
 
1137
  AGENT[Agent: kb_search_tool\nquery + workspace_id] --> SEMCACHE{Semantic cache hit?\nnexus:semantic_cache:ws:hash}
1138
  SEMCACHE -- Yes --> CACHED[Return cached answer\nTTL: 3600s]
1139
  SEMCACHE -- No --> EMBED[Generate query embedding]
1140
+ EMBED --> CHUNKS[Query kb_article_chunks:\nSELECT ordered by\nembedding cosine distance\nLIMIT 5]
1141
  CHUNKS --> CONTEXT[Build RAG context:\nchunk_1 + chunk_2 + ... + chunk_5]
1142
  CONTEXT --> LLM[Claude: synthesize answer\nusing chunks as context]
1143
  LLM --> STORECACHE[Store in semantic cache\nnexus:semantic_cache:ws:hash\nTTL: 3600s]
1144
+ STORECACHE --> RETURN[Return answer + sources + chunks]
1145
  ```
1146
 
1147
  ---
 
1152
 
1153
  ```mermaid
1154
  graph TD
1155
+ subgraph "ARQ Queue (Redis Cloud - Upstash)"
1156
  Q[arq:regular\njob queue]
1157
  CRON_Q[cron schedule\nstored in Redis]
1158
  end
 
1192
  axisFormat %H:%M
1193
 
1194
  section System
1195
+ record_system_heartbeat every 1 min :active, 00:00, 1440m
1196
+ monitor_sla_thresholds every 5 min :active, 00:00, 1440m
1197
+ nexus_pulse_check every 5 min :active, 00:00, 1440m
1198
 
1199
  section Cache
1200
+ purge_stale_semantic_cache run 1 :00:00, 60m
1201
+ purge_stale_semantic_cache run 2 :01:00, 60m
1202
+ purge_stale_semantic_cache run 3 :02:00, 60m
1203
 
1204
  section Insights
1205
+ refresh_workspace_insights run 1 :00:00, 30m
1206
+ refresh_workspace_insights run 2 :00:30, 30m
1207
+ refresh_workspace_insights run 3 :01:00, 30m
1208
 
1209
  section Analytics
1210
+ generate_nightly_analytics 2am daily :crit, 02:00, 30m
1211
  ```
1212
 
1213
  ### 12c. On-Demand Task Catalog
 
1230
 
1231
  subgraph "Triggered by Cron"
1232
  OD9[generate_global_insight\nworkspace nightly]
1233
+ OD10[crystallize_memory\nold interactions to memory]
1234
  OD11[generate_workspace_insights\ndashboard refresh]
1235
  OD12[ai_dynamic_nudge_pulse\nproactive suggestions]
1236
  end
 
1269
 
1270
  CT_INTENT & KB_INTENT & AN_INTENT & AS_INTENT --> INTENT
1271
 
 
 
1272
  INTENT[Resolved intent] --> SEMCACHE
1273
 
1274
+ SEMCACHE{Semantic cache hit?} -- Hit --> RETURN_CACHED[Return cached answer]
1275
 
1276
+ SEMCACHE -- Miss --> TOOL_SELECT[tool_selector node\nMap intent to tool function]
1277
 
1278
  TOOL_SELECT --> TOOL_EXEC[execute_tool node\nRun selected tool\nfrom tool registry]
1279
 
 
1281
 
1282
  VERIFY{Risky action?\ncreate_ticket\nchange_status} -- Yes + not approved --> APPROVAL[Request human approval\naction_approved: false]
1283
 
1284
+ VERIFY -- No risk or approved --> RESPOND
1285
 
1286
  APPROVAL --> INPUT
1287
 
 
1294
 
1295
  ```mermaid
1296
  mindmap
1297
+ root((Nexus Tools))
1298
  Knowledge Base
1299
+ kb_search_tool
1300
+ recall_knowledge
1301
  Tickets
1302
+ create_ticket_tool
1303
+ search_tickets_tool
1304
+ get_ticket_details_tool
1305
+ add_ticket_comment_tool
1306
+ change_ticket_status_tool
1307
+ assign_ticket_tool
1308
+ update_ticket_attributes_tool
1309
+ similar_incident_finder
1310
  Analytics
1311
+ nexus_analytics_tool
1312
+ sla_audit_tool
1313
+ summarize_workspace_tool
1314
+ sentiment_pulse_tool
1315
  Projects
1316
+ project_pulse_tool
1317
  ```
1318
 
1319
  ### 13c. RBAC Tool Enforcement
 
1353
  end
1354
 
1355
  subgraph "Semantic Cache"
1356
+ SCACHE[nexus_semantic_cache\nDB + Redis\nworkspace:hash to answer\nTTL: 1h]
1357
  end
1358
 
1359
  INTER -- crystallize_memory\ncron task --> MEM
 
1377
  participant Q as ARQ Queue (Redis Cloud)
1378
  participant W as ARQ Worker
1379
  participant G as LangGraph
1380
+ participant T as Tool e.g. kb_search
1381
+ participant RS as Redis Stream
1382
 
1383
+ B->>API: POST /nexus/stream query + workspace_id + thread_id
1384
  API->>API: Generate job_id = uuid4()
1385
  API->>Q: LPUSH arq:regular nexus_stream_task(job_id, ...)
1386
+ API-->>B: HTTP 200 + SSE headers Content-Type: text/event-stream
1387
 
1388
  par HTTP worker reads stream
1389
  loop until complete
1390
+ API->>RS: XREAD BLOCK 3000ms STREAMS nexus:stream:JOB_ID
1391
  RS-->>API: events if any
1392
  API-->>B: SSE data frames
1393
  end
 
1395
  W->>Q: BRPOP arq:regular
1396
  Q-->>W: nexus_stream_task job
1397
  W->>G: compile_graph().stream(state)
1398
+ G->>RS: XADD type=thinking content=Classifying intent
1399
  G->>G: fast-track / classify intent
1400
+ G->>RS: XADD type=tool_called tool=kb_search_tool
1401
  G->>T: execute kb_search_tool(query)
1402
+ T-->>G: articles + chunks + answer
1403
+ G->>RS: XADD type=tool_result tool=kb_search_tool
1404
+ G->>G: respond node stream Claude response
1405
  loop Response tokens
1406
+ G->>RS: XADD type=response_chunk content=token
1407
  end
1408
+ G->>RS: XADD type=complete thread_id=ID interaction_id=ID
1409
  W->>W: save NexusInteraction to DB
1410
  W->>W: enqueue vectorize_nexus_interaction
1411
  end
 
1432
  mindmap
1433
  root((Redis Local\nlocalhost:6379))
1434
  Pub/Sub Channels
1435
+ nexus:ws:workspace:uuid
1436
+ nexus:ws:user:uuid
1437
+ nexus:ws:role:ws_uuid:role
1438
+ nexus:ws:ticket:uuid
1439
  Streams
1440
+ nexus:stream:job_id
1441
  Cache Keys
1442
+ kb:list:ws_id:filter_hash
1443
+ kb:categories:ws_id
1444
+ cache:search:kb:ws_id:query_hash
1445
+ cache:search:ticket:ws_id:query_hash
1446
+ dashboard:insights:ws_id:date
1447
+ nexus:semantic_cache:ws:hash
1448
  Rate Limiting
1449
+ rl:user:user_id
1450
  Token Blocklist
1451
+ token:blocklist:jti
1452
  Distributed Locks
1453
+ nexus:latch:cron:job_name
1454
+ nexus:latch:job:job_id
1455
  ```
1456
 
1457
  ---
 
1466
 
1467
  ENQUEUE[ARQ: enqueue\nsend_triple_notification\nuser_id + type + payload] --> W
1468
 
1469
+ W[ARQ Worker\ntasks/notifications.py] --> N1 & N2 & N3
 
 
1470
 
1471
  subgraph "In-App Notification"
1472
+ N1[INSERT notifications\nworkspace_id + user_id + type\ntitle + content + is_read=false]
1473
+ N1 --> WS_NOTIF[PUBLISH\nnexus:ws:user:USER_ID\ntype=notification]
1474
  end
1475
 
1476
  subgraph "Email Notification"
 
1479
 
1480
  subgraph "Webhook"
1481
  N3{Workspace has\nwebhook URL?}
1482
+ N3 -- Yes --> WEBHOOK[HTTP POST to webhook URL\nevent_type + payload + workspace_id]
1483
  N3 -- No --> SKIP[Skip]
1484
  end
1485
 
1486
+ WS_NOTIF & N2 & WEBHOOK & SKIP --> DONE([Done])
1487
  ```
1488
 
1489
  ### 16b. @Mention Notification
 
1497
  participant W as Worker
1498
  participant WS as WebSocket
1499
 
1500
+ U->>API: POST /tickets/:id/messages content with @alice mention
1501
+ API->>DB: INSERT message content + mentions list
1502
+ API->>ARQ: enqueue notify_mentions(message_id, user_ids)
1503
  API-->>U: 201 MessageResponse
1504
 
1505
  W->>ARQ: dequeue notify_mentions
1506
  W->>DB: SELECT users WHERE id IN mentions
1507
  loop For each mentioned user
1508
+ W->>DB: INSERT notification type=MENTION
1509
+ W->>WS: PUBLISH nexus:ws:user:MENTIONED_USER_ID type=mention + ticket_id
1510
  end
1511
  ```
1512
 
 
1525
  participant DB as PostgreSQL
1526
  participant ARQ as ARQ Queue
1527
 
1528
+ U->>API: POST multipart/form-data file + ticket_id
1529
+ API->>API: Validate size + content_type whitelist
1530
  API->>FS: store(file_bytes, path=workspace/ticket/filename)
1531
+ FS-->>API: storage_path + storage_backend
1532
+ API->>DB: INSERT attachments\nticket_id + filename + storage_path\ncontent_type + file_size
1533
  DB-->>API: attachment_id
1534
 
1535
  alt Image attachment (image/*)
 
1537
  Note right of ARQ: Worker calls Claude Vision API\nUpdates attachment.ai_caption\nUsed in multimodal search
1538
  end
1539
 
1540
+ API-->>U: 201 AttachmentResponse id + filename + url
1541
  ```
1542
 
1543
  ### 17b. Download
 
1575
 
1576
  GAPS[Identify recurring topics\nnot covered by existing KB articles\nCompare via semantic search] --> INSIGHTS
1577
 
1578
+ INSIGHTS[For each gap:\nGenerate suggested_title\nGenerate draft suggested_content\nAssign confidence score 0-1] --> STORE
1579
 
1580
  STORE[UPSERT knowledge_insights\nlink to source tickets\nvia knowledge_insight_tickets] --> CACHE
1581
 
frontend/apps/customer/src/components/NewTicketView.tsx CHANGED
@@ -381,54 +381,94 @@ export const NewTicketView: React.FC<NewTicketViewProps> = ({ onBack, onCreate }
381
  {loading && (
382
  <div style={{
383
  position: "fixed", inset: 0,
384
- background: "var(--bg-glass)",
385
- backdropFilter: "blur(24px) saturate(180%)", zIndex: 1000,
386
  display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
387
- animation: "loadingFadeIn 0.5s cubic-bezier(0.16, 1, 0.3, 1)"
388
  }}>
389
- {/* Neural Mesh Background */}
390
- <div className="mesh-bg" style={{ opacity: 0.15, zIndex: -1 }} />
391
- <div className="tactical-grid" style={{ opacity: 0.05, zIndex: -1 }} />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
 
393
- <div style={{ position: 'relative', width: 160, height: 160, marginBottom: 40 }}>
394
- {/* Spinning Outer Ring */}
395
- <div style={{
396
- position: 'absolute', inset: 0, borderRadius: '50%',
397
- border: '3px solid var(--primary-glow)',
398
- borderTop: '3px solid var(--primary)',
399
- animation: 'spin 1.2s linear infinite'
400
- }} />
401
-
402
- {/* Pulsing Inner Core */}
403
  <div style={{
404
- position: 'absolute', inset: 20, borderRadius: '50%',
405
- background: 'radial-gradient(circle, var(--primary-glow) 0%, transparent 70%)',
406
- opacity: 0.6,
407
- animation: 'pulse 1.8s ease-in-out infinite'
408
- }} />
409
-
410
- {/* Shield Icon */}
411
- <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
412
- <ShieldCheck size={56} style={{ color: 'var(--primary)', filter: 'drop-shadow(0 0 12px var(--primary-glow))' }} />
 
 
 
 
 
 
 
413
  </div>
414
  </div>
415
 
416
- <div style={{ textAlign: "center", maxWidth: 420 }}>
417
- <div className="metadata" style={{ color: "var(--primary)", letterSpacing: "0.4em", fontWeight: 900, marginBottom: 16 }}>NEXUS PROTOCOL ACTIVE</div>
418
- <h2 style={{ color: "var(--text-main)", fontSize: 32, fontWeight: 800, fontFamily: "var(--font-heading)", marginBottom: 12, letterSpacing: '-0.02em' }}>Synchronizing Request...</h2>
419
- <div style={{ width: 260, height: 6, background: 'rgba(0,0,0,0.05)', borderRadius: 10, marginInline: 'auto', overflow: 'hidden' }}>
420
- <div className="loading-bar-progress" style={{ width: '40%', height: '100%', background: 'var(--primary)', borderRadius: 10, animation: 'loadingSlide 2s infinite ease-in-out', boxShadow: '0 0 15px var(--primary-glow)' }} />
 
 
 
 
421
  </div>
422
- <p style={{ marginTop: 24, fontSize: 13, color: 'var(--text-muted)', fontWeight: 600, letterSpacing: '0.05em' }}>PREPARING SECURE NEURAL HANDSHAKE</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
  </div>
424
  </div>
425
  )}
426
 
427
  <style>{`
428
  @keyframes spin { to { transform: rotate(360deg); } }
429
- @keyframes pulse { 0%, 100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.1); opacity: 0.7; } }
430
- @keyframes loadingFadeIn { from { opacity: 0; } to { opacity: 1; } }
431
- @keyframes loadingSlide { 0% { transform: translateX(-100%); width: 20%; } 50% { width: 60%; } 100% { transform: translateX(200%); width: 20%; } }
 
432
  .select-wrapper select:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 4px var(--primary-glow) !important; }
433
  .input-focus::placeholder { color: rgba(255,255,255,0.2); }
434
  .input-focus:focus::placeholder { opacity: 0.5; }
 
381
  {loading && (
382
  <div style={{
383
  position: "fixed", inset: 0,
384
+ background: "rgba(10, 10, 18, 0.92)",
385
+ backdropFilter: "blur(40px) saturate(200%)", zIndex: 9999,
386
  display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
387
+ animation: "loadingFadeIn 0.8s cubic-bezier(0.16, 1, 0.3, 1)"
388
  }}>
389
+ {/* Decorative Elements */}
390
+ <div style={{
391
+ position: 'absolute', width: '100%', height: '100%',
392
+ backgroundImage: 'radial-gradient(circle at 50% 50%, rgba(124, 58, 237, 0.15) 0%, transparent 50%)',
393
+ pointerEvents: 'none'
394
+ }} />
395
+
396
+ <div className="neural-container" style={{ position: 'relative', width: 240, height: 240, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
397
+ {/* Pulsing Outer Rings */}
398
+ {[...Array(3)].map((_, i) => (
399
+ <div key={i} style={{
400
+ position: 'absolute',
401
+ inset: i * 20,
402
+ borderRadius: '50%',
403
+ border: `1px solid rgba(124, 58, 237, ${0.3 - i * 0.1})`,
404
+ animation: `neuralPulse ${3 + i}s ease-in-out infinite`
405
+ }} />
406
+ ))}
407
 
408
+ {/* Main Animated Loader */}
 
 
 
 
 
 
 
 
 
409
  <div style={{
410
+ position: 'relative', width: 120, height: 120,
411
+ display: 'flex', alignItems: 'center', justifyContent: 'center'
412
+ }}>
413
+ <div style={{
414
+ position: 'absolute', inset: 0, borderRadius: '50%',
415
+ border: '4px solid transparent',
416
+ borderTop: '4px solid var(--primary)',
417
+ borderRight: '4px solid var(--primary)',
418
+ filter: 'drop-shadow(0 0 15px var(--primary))',
419
+ animation: 'spin 1.5s cubic-bezier(0.5, 0, 0.5, 1) infinite'
420
+ }} />
421
+ <ShieldCheck size={48} style={{
422
+ color: 'var(--primary)',
423
+ filter: 'drop-shadow(0 0 20px var(--primary))',
424
+ animation: 'pulse 2s ease-in-out infinite'
425
+ }} />
426
  </div>
427
  </div>
428
 
429
+ <div style={{ textAlign: "center", maxWidth: 480, marginTop: 40, zIndex: 10 }}>
430
+ <div style={{
431
+ display: 'inline-flex', alignItems: 'center', gap: 12,
432
+ padding: '8px 20px', background: 'rgba(124, 58, 237, 0.1)',
433
+ borderRadius: 99, border: '1px solid rgba(124, 58, 237, 0.2)',
434
+ marginBottom: 24, animation: 'loadingFadeIn 1s'
435
+ }}>
436
+ <span style={{ width: 6, height: 6, background: 'var(--primary)', borderRadius: '50%', animation: 'pulse 1s infinite' }} />
437
+ <span style={{ color: "var(--primary)", letterSpacing: "0.2em", fontSize: 11, fontWeight: 900 }}>NEXUS PROTOCOL ACTIVE</span>
438
  </div>
439
+
440
+ <h2 style={{
441
+ color: "#ffffff", fontSize: 36, fontWeight: 800,
442
+ fontFamily: "var(--font-heading)", marginBottom: 16,
443
+ letterSpacing: '-0.03em', textShadow: '0 4px 12px rgba(0,0,0,0.3)'
444
+ }}>
445
+ Synchronizing Request...
446
+ </h2>
447
+
448
+ <div style={{ width: 300, height: 4, background: 'rgba(255,255,255,0.05)', borderRadius: 10, marginInline: 'auto', overflow: 'hidden', position: 'relative' }}>
449
+ <div className="premium-progress" style={{
450
+ width: '60%', height: '100%',
451
+ background: 'linear-gradient(90deg, transparent, var(--primary), transparent)',
452
+ animation: 'premiumSlide 2s infinite ease-in-out'
453
+ }} />
454
+ </div>
455
+
456
+ <p style={{
457
+ marginTop: 32, fontSize: 14, color: 'rgba(255,255,255,0.5)',
458
+ fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase'
459
+ }}>
460
+ Preparing Secure Neural Handshake
461
+ </p>
462
  </div>
463
  </div>
464
  )}
465
 
466
  <style>{`
467
  @keyframes spin { to { transform: rotate(360deg); } }
468
+ @keyframes pulse { 0%, 100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.1); opacity: 0.8; } }
469
+ @keyframes neuralPulse { 0%, 100% { transform: scale(1); opacity: 0.3; } 50% { transform: scale(1.05); opacity: 0.1; } }
470
+ @keyframes loadingFadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
471
+ @keyframes premiumSlide { 0% { transform: translateX(-150%); } 100% { transform: translateX(150%); } }
472
  .select-wrapper select:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 4px var(--primary-glow) !important; }
473
  .input-focus::placeholder { color: rgba(255,255,255,0.2); }
474
  .input-focus:focus::placeholder { opacity: 0.5; }