Spaces:
Paused

dushyantsingh0 Claude Sonnet 4.6 commited on
Commit
1181145
Β·
1 Parent(s): 7002df6

fix: CLARIFY misfires on explicit ticket IDs, add audit history to ticket details

Browse files

- Router: add CLARIFY guard (never CLARIFY when ticket ID present or active ticket in context)
- Router: add few-shot examples for 'activities/history/summary on ticket X' β†’ GET_TICKET_DETAILS
- Fast-track: new rule matching 'activities/history/timeline on ticket' β†’ GET_TICKET_DETAILS
with proper ticket_id extraction (not generic query arg)
- get_ticket_details_tool: fetch AuditLog events and include as ACTIVITY HISTORY section
so ticket history events (SLA breaches, escalations) are visible to the agent
- Responder prompt: do not ask for 'more context' when tool output contains ticket details
(empty conversation != empty data)
- Graph cache key bumped nexus_v2 β†’ nexus_v3

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

agents/nexus_master.py CHANGED
@@ -98,6 +98,8 @@ _FAST_TRACK_RULES = [
98
  # NOTE: "try again / retry / redo / re-run / previous / history" intentionally excluded β€”
99
  # these are conversational or ambiguous; the LLM router handles them via checkpointer context.
100
  (re.compile(r"\b(recall|memory|remember)\b", re.I), "RECALL_KNOWLEDGE"),
 
 
101
  # "get"/"give" excluded β€” too generic ("get this ticket resolved" β†’ wrong SEARCH); "show/list/find/search" are unambiguous
102
  (re.compile(r"\b(search|find|list|show|what is|status of)\b.*\btickets?\b", re.I), "SEARCH_TICKETS"),
103
  # "move"/"give" excluded β€” "give me a summary to read" / "move this forward to close" β†’ wrong ASSIGN
@@ -338,6 +340,11 @@ async def nexus_router(state: NexusState) -> Dict[str, Any]:
338
  f_id = f"fast_{uuid4().hex[:8]}"
339
  if fallback_tool == "CONVERSE":
340
  return {"current_tool_output": "CONVERSE"}
 
 
 
 
 
341
  elif fallback_tool == "CREATE_TICKET":
342
  # Extract a meaningful title instead of hardcoding "New Support Request"
343
  _words = [w for w in last_user_msg.split() if w.lower() not in {
@@ -1011,7 +1018,7 @@ async def get_nexus_app(is_agent: bool = False):
1011
  global _GRAPH_LOCK
1012
  if _GRAPH_LOCK is None:
1013
  _GRAPH_LOCK = asyncio.Lock()
1014
- cache_key = f"nexus_v2_{is_agent}"
1015
  async with _GRAPH_LOCK:
1016
  # Double-checked locking: re-check inside the lock to handle concurrent waiters
1017
  if cache_key in _GRAPH_CACHE:
 
98
  # NOTE: "try again / retry / redo / re-run / previous / history" intentionally excluded β€”
99
  # these are conversational or ambiguous; the LLM router handles them via checkpointer context.
100
  (re.compile(r"\b(recall|memory|remember)\b", re.I), "RECALL_KNOWLEDGE"),
101
+ # Ticket detail queries β€” "activities/history/timeline/events/summary" on a specific ticket
102
+ (re.compile(r"\b(activit|histor|timeline|events?|details?)\b.*\bticket\b|\bticket\b.*\b(activit|histor|timeline|events?|details?|summar)\b", re.I), "GET_TICKET_DETAILS"),
103
  # "get"/"give" excluded β€” too generic ("get this ticket resolved" β†’ wrong SEARCH); "show/list/find/search" are unambiguous
104
  (re.compile(r"\b(search|find|list|show|what is|status of)\b.*\btickets?\b", re.I), "SEARCH_TICKETS"),
105
  # "move"/"give" excluded β€” "give me a summary to read" / "move this forward to close" β†’ wrong ASSIGN
 
340
  f_id = f"fast_{uuid4().hex[:8]}"
341
  if fallback_tool == "CONVERSE":
342
  return {"current_tool_output": "CONVERSE"}
343
+ elif fallback_tool == "GET_TICKET_DETAILS":
344
+ # Extract ticket ID from the message, or fall back to the active ticket in state
345
+ _tid_match = re.search(r'\b([a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}|[A-Z0-9]{6,12})\b', last_user_msg)
346
+ _ticket_id = _tid_match.group(1) if _tid_match else str(state.get("ticket_id") or "")
347
+ args = {"ticket_id": _ticket_id} if _ticket_id else {"ticket_id": last_user_msg}
348
  elif fallback_tool == "CREATE_TICKET":
349
  # Extract a meaningful title instead of hardcoding "New Support Request"
350
  _words = [w for w in last_user_msg.split() if w.lower() not in {
 
1018
  global _GRAPH_LOCK
1019
  if _GRAPH_LOCK is None:
1020
  _GRAPH_LOCK = asyncio.Lock()
1021
+ cache_key = f"nexus_v3_{is_agent}"
1022
  async with _GRAPH_LOCK:
1023
  # Double-checked locking: re-check inside the lock to handle concurrent waiters
1024
  if cache_key in _GRAPH_CACHE:
agents/prompts.py CHANGED
@@ -62,6 +62,7 @@ CORE TOOLSET & PRIORITY:
62
  12. SLA_AUDIT: Use for "SLA Forensics" to find breached or near-breach tickets.
63
  13. CONVERSE: Use ONLY for pure greetings/acknowledgments ("hi", "thanks") OR queries that are 100% unrelated to the workspace (weather, sports scores, general trivia). CRITICAL: Vague workspace queries like "any updates?", "what's happening?", "give me a status", "latest updates", "retry", "try again" are IN-SCOPE β€” route them to the appropriate workspace tool, NOT CONVERSE. When in doubt, call a tool.
64
  14. CLARIFY: Use when the query is genuinely too ambiguous to route to any tool confidently β€” the agent will ask a focused clarifying question. Example: user says "what happened with that issue" with NO ticket context and NO prior conversation β†’ CLARIFY. Use sparingly; prefer routing to a tool over asking. Only use CLARIFY when calling any tool would produce meaningless results.
 
65
 
66
 
67
  STRATEGIC DIRECTIVES:
@@ -98,6 +99,15 @@ User: "What's happening?"
98
  User: "can you try again?" or "retry"
99
  β†’ {{"intent": "ANALYTICS", "tool_call": "SUMMARIZE_WORKSPACE", "tool_args": {{}}, "reasoning": "User asking to retry previous workspace query β€” default to workspace summary."}}
100
 
 
 
 
 
 
 
 
 
 
101
  User: "what happened?" (no ticket context, no prior conversation)
102
  β†’ {{"intent": "CLARIFY", "tool_call": null, "tool_args": null, "reasoning": "Query is too vague with no context β€” need to ask which incident or ticket they mean."}}
103
 
@@ -209,10 +219,14 @@ You are NOT a one-shot search engine. When you need more context, ASK β€” concis
209
 
210
  Ask a follow-up question when:
211
  - The query is ambiguous ("what happened?", "any updates?") and you have no tool data to anchor on
212
- - Tool results returned nothing β€” ask the user to narrow down (ticket ID, date range, keyword)
213
  - A write action needs clarification (which ticket? which user? what priority?)
214
  - Multiple valid interpretations exist β€” list them and let the user pick
215
 
 
 
 
 
216
  Good clarifying questions (natural, not robotic):
217
  - "Which ticket or incident are you referring to?"
218
  - "Are you looking at the last 7 days, or a specific period?"
 
62
  12. SLA_AUDIT: Use for "SLA Forensics" to find breached or near-breach tickets.
63
  13. CONVERSE: Use ONLY for pure greetings/acknowledgments ("hi", "thanks") OR queries that are 100% unrelated to the workspace (weather, sports scores, general trivia). CRITICAL: Vague workspace queries like "any updates?", "what's happening?", "give me a status", "latest updates", "retry", "try again" are IN-SCOPE β€” route them to the appropriate workspace tool, NOT CONVERSE. When in doubt, call a tool.
64
  14. CLARIFY: Use when the query is genuinely too ambiguous to route to any tool confidently β€” the agent will ask a focused clarifying question. Example: user says "what happened with that issue" with NO ticket context and NO prior conversation β†’ CLARIFY. Use sparingly; prefer routing to a tool over asking. Only use CLARIFY when calling any tool would produce meaningless results.
65
+ ⚠️ NEVER use CLARIFY when: (a) a ticket ID is present in the query (any 6–12 char alphanumeric token like "18607D57", "B42B9701"), or (b) an active ticket_id is in the Context, or (c) the user's prior message already mentioned a ticket and the follow-up is clearly about the same ticket. In all these cases, call GET_TICKET_DETAILS.
66
 
67
 
68
  STRATEGIC DIRECTIVES:
 
99
  User: "can you try again?" or "retry"
100
  β†’ {{"intent": "ANALYTICS", "tool_call": "SUMMARIZE_WORKSPACE", "tool_args": {{}}, "reasoning": "User asking to retry previous workspace query β€” default to workspace summary."}}
101
 
102
+ User: "Give me complete activities on this ticket 18607D57"
103
+ β†’ {{"intent": "TICKETS", "tool_call": "GET_TICKET_DETAILS", "tool_args": {{"ticket_id": "18607D57"}}, "reasoning": "Ticket ID is explicit β€” 'activities', 'history', 'events', 'timeline' all map to GET_TICKET_DETAILS. Never CLARIFY when a ticket ID is present."}}
104
+
105
+ User: "Ticket history" (prior conversation mentions ticket 18607D57)
106
+ β†’ {{"intent": "TICKETS", "tool_call": "GET_TICKET_DETAILS", "tool_args": {{"ticket_id": "18607D57"}}, "reasoning": "Follow-up about the same ticket β€” use context from prior message. Do not CLARIFY."}}
107
+
108
+ User: "give me its summary" (active ticket context is populated)
109
+ β†’ {{"intent": "TICKETS", "tool_call": "GET_TICKET_DETAILS", "tool_args": {{"ticket_id": "<active_ticket_id>"}}, "reasoning": "User refers to the active ticket β€” resolve from context, call GET_TICKET_DETAILS."}}
110
+
111
  User: "what happened?" (no ticket context, no prior conversation)
112
  β†’ {{"intent": "CLARIFY", "tool_call": null, "tool_args": null, "reasoning": "Query is too vague with no context β€” need to ask which incident or ticket they mean."}}
113
 
 
219
 
220
  Ask a follow-up question when:
221
  - The query is ambiguous ("what happened?", "any updates?") and you have no tool data to anchor on
222
+ - Tool results returned nothing AND no ticket context exists β€” ask the user to narrow down (ticket ID, date range, keyword)
223
  - A write action needs clarification (which ticket? which user? what priority?)
224
  - Multiple valid interpretations exist β€” list them and let the user pick
225
 
226
+ Do NOT ask for more context when:
227
+ - TOOL OUTPUT contains a ticket's title, status, description, or AI summary β€” present those details even if conversation history is empty. Empty conversation β‰  no data.
228
+ - The active ticket context (above) is populated β€” synthesize it directly.
229
+
230
  Good clarifying questions (natural, not robotic):
231
  - "Which ticket or incident are you referring to?"
232
  - "Are you looking at the last 7 days, or a specific period?"
agents/tools/nexus_tools.py CHANGED
@@ -20,6 +20,7 @@ from models.project import Project
20
  from models.nexus_memory import NexusMemory
21
  from models.remediation_audit import RemediationAudit
22
  from models.user_workspace import UserWorkspace
 
23
 
24
  from agents.security import mask_for_role, is_staff_role
25
  from agents.utils import safe_uuid
@@ -494,30 +495,52 @@ async def get_ticket_details_tool(ticket_id: str, workspace_id: UUID, role: str
494
  for m in msg_res.scalars().all():
495
  m_dict = {c.name: getattr(m, c.name) for c in m.__table__.columns}
496
  messages.append(m_dict)
497
-
 
 
 
 
 
 
 
 
 
 
498
  t_data = {c.name: getattr(t, c.name) for c in t.__table__.columns}
499
  t_data = mask_for_role(t_data, role)
500
-
501
- # Redundant Security: Strip internal messages explicitly for customer roles
502
  if not is_staff_role(role):
503
  messages = [m for m in messages if not m.get('is_internal')]
504
-
505
  masked_messages = mask_for_role(messages, role)
506
-
507
  # 4. Format Output
508
  meta = t_data.get("ai_metadata", {})
509
  summaries = meta.get("summaries", {})
510
  summary = summaries.get("internal_summary") or summaries.get("customer_summary") or "No recent summary."
511
-
512
- history = "\n".join([f"[{m['created_at'].isoformat()}] {m['sender_id']}: {m['content']}" for m in masked_messages])
513
-
 
 
 
 
 
 
 
 
 
 
 
514
  return (
515
  f"### TICKET DETAILS: {t.title}\n"
516
  f"**ID:** `{t.id}` | **Status:** {t.status.value.upper()} | "
517
- f"**Priority:** {t.priority.value.replace('P0', 'Critical').replace('P1', 'High').replace('P2', 'Medium').replace('P3', 'Low')}\n"
518
  f"**Description:** {t.description}\n\n"
519
  f"**AI SUMMARY:**\n{summary}\n\n"
520
- f"**RECENT CONVERSATION:**\n{history or 'No messages yet.'}"
 
521
  )
522
 
523
  async def nexus_analytics_tool(workspace_id: UUID, role: str = "customer_user", user_id: Optional[UUID] = None) -> str:
 
20
  from models.nexus_memory import NexusMemory
21
  from models.remediation_audit import RemediationAudit
22
  from models.user_workspace import UserWorkspace
23
+ from models.audit_log import AuditLog
24
 
25
  from agents.security import mask_for_role, is_staff_role
26
  from agents.utils import safe_uuid
 
495
  for m in msg_res.scalars().all():
496
  m_dict = {c.name: getattr(m, c.name) for c in m.__table__.columns}
497
  messages.append(m_dict)
498
+
499
+ # 3. Fetch Audit / Activity History
500
+ audit_stmt = (
501
+ select(AuditLog)
502
+ .where(AuditLog.entity_type == "ticket", AuditLog.entity_id == t_id)
503
+ .order_by(AuditLog.created_at.asc())
504
+ .limit(30)
505
+ )
506
+ audit_res = await db.execute(audit_stmt)
507
+ audit_events = audit_res.scalars().all()
508
+
509
  t_data = {c.name: getattr(t, c.name) for c in t.__table__.columns}
510
  t_data = mask_for_role(t_data, role)
511
+
512
+ # Strip internal messages for customer roles
513
  if not is_staff_role(role):
514
  messages = [m for m in messages if not m.get('is_internal')]
515
+
516
  masked_messages = mask_for_role(messages, role)
517
+
518
  # 4. Format Output
519
  meta = t_data.get("ai_metadata", {})
520
  summaries = meta.get("summaries", {})
521
  summary = summaries.get("internal_summary") or summaries.get("customer_summary") or "No recent summary."
522
+
523
+ convo = "\n".join([f"[{m['created_at'].isoformat()}] {m['sender_id']}: {m['content']}" for m in masked_messages])
524
+
525
+ activity_lines = []
526
+ for ev in audit_events:
527
+ ts = ev.created_at.isoformat() if ev.created_at else "?"
528
+ actor = f"user:{str(ev.user_id)[:8]}" if ev.user_id else "system"
529
+ old_v = json.dumps(ev.old_value) if ev.old_value else "-"
530
+ new_v = json.dumps(ev.new_value) if ev.new_value else "-"
531
+ activity_lines.append(f"[{ts}] {ev.action.upper()} by {actor} | {old_v} β†’ {new_v}")
532
+ activity_section = "\n".join(activity_lines) if activity_lines else "No recorded activity events."
533
+
534
+ priority_label = t.priority.value.replace('P0', 'Critical').replace('P1', 'High').replace('P2', 'Medium').replace('P3', 'Low') if t.priority else "Unknown"
535
+
536
  return (
537
  f"### TICKET DETAILS: {t.title}\n"
538
  f"**ID:** `{t.id}` | **Status:** {t.status.value.upper()} | "
539
+ f"**Priority:** {priority_label}\n"
540
  f"**Description:** {t.description}\n\n"
541
  f"**AI SUMMARY:**\n{summary}\n\n"
542
+ f"**ACTIVITY HISTORY ({len(audit_events)} events):**\n{activity_section}\n\n"
543
+ f"**CONVERSATION ({len(masked_messages)} messages):**\n{convo or 'No messages yet.'}"
544
  )
545
 
546
  async def nexus_analytics_tool(workspace_id: UUID, role: str = "customer_user", user_id: Optional[UUID] = None) -> str: