nexo-brain 5.3.20 → 5.3.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/package.json +1 -1
  3. package/src/auto_update.py +11 -8
  4. package/src/dashboard/static/favicon 2.svg +32 -0
  5. package/src/dashboard/static/nexo-logo 2.png +0 -0
  6. package/src/dashboard/static/nexo-logo 2.svg +40 -0
  7. package/src/dashboard/static/style 2.css +2458 -0
  8. package/src/dashboard/templates/adaptive 2.html +118 -0
  9. package/src/dashboard/templates/artifacts 2.html +133 -0
  10. package/src/dashboard/templates/backups 2.html +136 -0
  11. package/src/dashboard/templates/base 2.html +417 -0
  12. package/src/dashboard/templates/calendar 2.html +591 -0
  13. package/src/dashboard/templates/chat 2.html +356 -0
  14. package/src/dashboard/templates/claims 2.html +259 -0
  15. package/src/dashboard/templates/cortex 2.html +321 -0
  16. package/src/dashboard/templates/credentials 2.html +128 -0
  17. package/src/dashboard/templates/crons 2.html +370 -0
  18. package/src/dashboard/templates/dashboard 2.html +494 -0
  19. package/src/dashboard/templates/dreams 2.html +252 -0
  20. package/src/dashboard/templates/email 2.html +160 -0
  21. package/src/dashboard/templates/evolution 2.html +189 -0
  22. package/src/dashboard/templates/feed 2.html +249 -0
  23. package/src/dashboard/templates/followup_health 2.html +170 -0
  24. package/src/dashboard/templates/graph 2.html +201 -0
  25. package/src/dashboard/templates/guard 2.html +259 -0
  26. package/src/dashboard/templates/inbox 2.html +251 -0
  27. package/src/dashboard/templates/memory 2.html +420 -0
  28. package/src/dashboard/templates/operations 2.html +608 -0
  29. package/src/dashboard/templates/plugins 2.html +185 -0
  30. package/src/dashboard/templates/protocol 2.html +199 -0
  31. package/src/dashboard/templates/rules 2.html +246 -0
  32. package/src/dashboard/templates/sentiment 2.html +247 -0
  33. package/src/dashboard/templates/sessions 2.html +218 -0
  34. package/src/dashboard/templates/skills 2.html +329 -0
  35. package/src/dashboard/templates/somatic 2.html +73 -0
  36. package/src/dashboard/templates/triggers 2.html +133 -0
  37. package/src/dashboard/templates/trust 2.html +360 -0
  38. package/src/db/__init__ 2.py +259 -0
  39. package/src/db/_core 2.py +437 -0
  40. package/src/db/_credentials 2.py +124 -0
  41. package/src/db/_episodic 2.py +762 -0
  42. package/src/db/_evolution 2.py +54 -0
  43. package/src/db/_fts 2.py +406 -0
  44. package/src/db/_goal_profiles 2.py +376 -0
  45. package/src/db/_hot_context 2.py +660 -0
  46. package/src/db/_outcomes 2.py +800 -0
  47. package/src/db/_personal_scripts 2.py +582 -0
  48. package/src/db/_sessions 2.py +330 -0
  49. package/src/db/_tasks 2.py +91 -0
  50. package/src/db/_watchers 2.py +173 -0
  51. package/src/doctor/formatters 2.py +52 -0
  52. package/src/doctor/models 2.py +69 -0
  53. package/src/doctor/planes 2.py +87 -0
  54. package/src/doctor/providers/__init__ 2.py +1 -0
  55. package/src/doctor/providers/deep 2.py +367 -0
  56. package/src/evolution_cycle 2.py +519 -0
  57. package/src/hooks/auto_capture 2.py +208 -0
  58. package/src/hooks/caffeinate-guard 2.sh +8 -0
  59. package/src/hooks/capture-session 2.sh +21 -0
  60. package/src/hooks/capture-tool-logs 2.sh +158 -0
  61. package/src/hooks/daily-briefing-check 2.sh +33 -0
  62. package/src/hooks/heartbeat-enforcement 2.py +90 -0
  63. package/src/hooks/heartbeat-posttool 2.sh +18 -0
  64. package/src/hooks/inbox-hook 2.sh +76 -0
  65. package/src/hooks/post-compact 2.sh +152 -0
  66. package/src/hooks/pre-compact 2.sh +169 -0
  67. package/src/hooks/protocol-guardrail 2.sh +10 -0
  68. package/src/hooks/protocol-pretool-guardrail 2.sh +9 -0
  69. package/src/hooks/session-stop 2.sh +52 -0
  70. package/src/kg_populate 2.py +292 -0
  71. package/src/maintenance 2.py +53 -0
  72. package/src/memory_backends 2.py +71 -0
  73. package/src/migrate_embeddings 2.py +124 -0
  74. package/src/nexo_sdk 2.py +103 -0
  75. package/src/observability 2.py +199 -0
  76. package/src/plugin_loader 2.py +217 -0
  77. package/src/plugins/__init__ 2.py +0 -0
  78. package/src/plugins/artifact_registry 2.py +450 -0
  79. package/src/plugins/backup 2.py +127 -0
  80. package/src/plugins/claims_tools 2.py +119 -0
  81. package/src/plugins/cognitive_memory 2.py +609 -0
  82. package/src/plugins/core_rules 2.py +252 -0
  83. package/src/plugins/cortex 2.py +1155 -0
  84. package/src/plugins/entities 2.py +67 -0
  85. package/src/plugins/episodic_memory 2.py +560 -0
  86. package/src/plugins/evolution 2.py +167 -0
  87. package/src/plugins/goal_engine 2.py +142 -0
  88. package/src/plugins/guard 2.py +862 -0
  89. package/src/plugins/impact 2.py +29 -0
  90. package/src/plugins/knowledge_graph_tools 2.py +137 -0
  91. package/src/plugins/media_memory_tools 2.py +98 -0
  92. package/src/plugins/memory_export 2.py +196 -0
  93. package/src/plugins/outcomes 2.py +130 -0
  94. package/src/plugins/personal_scripts 2.py +117 -0
  95. package/src/plugins/preferences 2.py +47 -0
  96. package/src/plugins/protocol 2.py +1449 -0
  97. package/src/plugins/simple_api 2.py +106 -0
  98. package/src/plugins/skills 2.py +341 -0
  99. package/src/plugins/state_watchers 2.py +79 -0
  100. package/src/plugins/update 2.py +986 -0
  101. package/src/plugins/user_state_tools 2.py +43 -0
  102. package/src/plugins/workflow 2.py +588 -0
  103. package/src/protocol_settings 2.py +59 -0
  104. package/src/public_contribution 2.py +466 -0
  105. package/src/public_evolution_queue 2.py +241 -0
  106. package/src/requirements 2.txt +14 -0
  107. package/src/retroactive_learnings 2.py +373 -0
  108. package/src/rules/__init__ 2.py +0 -0
  109. package/src/rules/core-rules 2.json +331 -0
  110. package/src/rules/migrate 2.py +207 -0
  111. package/src/runtime_power 2.py +874 -0
  112. package/src/script_registry 2.py +1559 -0
  113. package/src/scripts/check-context 2.py +272 -0
  114. package/src/scripts/deep-sleep/apply_findings 2.py +2327 -0
  115. package/src/scripts/deep-sleep/collect 2.py +928 -0
  116. package/src/scripts/deep-sleep/extract 2.py +330 -0
  117. package/src/scripts/deep-sleep/extract-prompt 2.md +285 -0
  118. package/src/scripts/deep-sleep/synthesize 2.py +312 -0
  119. package/src/scripts/deep-sleep/synthesize-prompt 2.md +336 -0
  120. package/src/scripts/nexo-agent-run 2.py +75 -0
  121. package/src/scripts/nexo-auto-update 2.py +6 -0
  122. package/src/scripts/nexo-backup 2.sh +25 -0
  123. package/src/scripts/nexo-brain-activation 2.sh +140 -0
  124. package/src/scripts/nexo-catchup 2.py +300 -0
  125. package/src/scripts/nexo-cognitive-decay 2.py +257 -0
  126. package/src/scripts/nexo-cortex-cycle 2.py +293 -0
  127. package/src/scripts/nexo-cron-wrapper 2.sh +53 -0
  128. package/src/scripts/nexo-daily-self-audit 2.py +2161 -0
  129. package/src/scripts/nexo-dashboard 2.sh +29 -0
  130. package/src/scripts/nexo-deep-sleep 2.sh +86 -0
  131. package/src/scripts/nexo-evolution-run 2.py +1664 -0
  132. package/src/scripts/nexo-followup-hygiene 2.py +139 -0
  133. package/src/scripts/nexo-hook-record 2.py +42 -0
  134. package/src/scripts/nexo-immune 2.py +936 -0
  135. package/src/scripts/nexo-impact-scorer 2.py +117 -0
  136. package/src/scripts/nexo-inbox-hook 2.sh +74 -0
  137. package/src/scripts/nexo-install 2.py +6 -0
  138. package/src/scripts/nexo-learning-housekeep 2.py +401 -0
  139. package/src/scripts/nexo-learning-validator 2.py +266 -0
  140. package/src/scripts/nexo-migrate 2.py +260 -0
  141. package/src/scripts/nexo-outcome-checker 2.py +127 -0
  142. package/src/scripts/nexo-postmortem-consolidator 2.py +456 -0
  143. package/src/scripts/nexo-pre-commit 2.py +120 -0
  144. package/src/scripts/nexo-prevent-sleep 2.sh +35 -0
  145. package/src/scripts/nexo-proactive-dashboard 2.py +354 -0
  146. package/src/scripts/nexo-reflection 2.py +256 -0
  147. package/src/scripts/nexo-runtime-preflight 2.py +274 -0
  148. package/src/scripts/nexo-sleep 2.py +631 -0
  149. package/src/scripts/nexo-snapshot-restore 2.sh +35 -0
  150. package/src/scripts/nexo-sync-clients 2.py +16 -0
  151. package/src/scripts/nexo-synthesis 2.py +475 -0
  152. package/src/scripts/nexo-tcc-approve 2.sh +79 -0
  153. package/src/scripts/nexo-update 2.sh +306 -0
  154. package/src/scripts/nexo-watchdog 2.sh +1207 -0
  155. package/src/scripts/nexo-watchdog-smoke 2.py +119 -0
  156. package/src/scripts/rehydrate_learnings_from_archive 2.py +245 -0
  157. package/src/server 2.py +1296 -0
  158. package/src/skills/run-nexo-audit-phase/guide 2.md +43 -0
  159. package/src/skills/run-nexo-audit-phase/skill 2.json +59 -0
  160. package/src/skills/run-nexo-core-fix-cycle/guide 2.md +17 -0
  161. package/src/skills/run-nexo-core-fix-cycle/script 2.py +276 -0
  162. package/src/skills/run-nexo-core-fix-cycle/skill 2.json +58 -0
  163. package/src/skills/run-release-final-audit/guide 2.md +16 -0
  164. package/src/skills/run-release-final-audit/script 2.py +259 -0
  165. package/src/skills/run-release-final-audit/skill 2.json +77 -0
  166. package/src/skills/run-runtime-doctor/guide 2.md +12 -0
  167. package/src/skills/run-runtime-doctor/script 2.py +21 -0
  168. package/src/skills/run-runtime-doctor/skill 2.json +25 -0
  169. package/src/skills_runtime 2.py +932 -0
  170. package/src/state_watchers_runtime 2.py +475 -0
  171. package/src/storage_router 2.py +32 -0
  172. package/src/system_catalog 2.py +786 -0
  173. package/src/tools_coordination 2.py +103 -0
  174. package/src/tools_credentials 2.py +68 -0
  175. package/src/tools_drive 2.py +487 -0
  176. package/src/tools_hot_context 2.py +163 -0
  177. package/src/tools_learnings 2.py +612 -0
  178. package/src/tools_menu 2.py +229 -0
  179. package/src/tools_reminders 2.py +88 -0
  180. package/src/tools_reminders_crud 2.py +363 -0
  181. package/src/tools_sessions 2.py +1054 -0
  182. package/src/tools_system_catalog 2.py +19 -0
  183. package/src/tools_task_history 2.py +57 -0
  184. package/src/tools_transcripts 2.py +98 -0
  185. package/src/transcript_utils 2.py +412 -0
  186. package/src/user_context 2.py +46 -0
  187. package/src/user_data_portability 2.py +328 -0
  188. package/src/user_state_model 2.py +170 -0
  189. package/templates/CLAUDE.md 2.template +108 -0
  190. package/templates/CODEX.AGENTS.md 2.template +66 -0
  191. package/templates/launchagents/README 2.md +132 -0
  192. package/templates/launchagents/com.nexo.auto-close-sessions 2.plist +39 -0
  193. package/templates/launchagents/com.nexo.catchup 2.plist +39 -0
  194. package/templates/launchagents/com.nexo.cognitive-decay 2.plist +40 -0
  195. package/templates/launchagents/com.nexo.dashboard 2.plist +43 -0
  196. package/templates/launchagents/com.nexo.deep-sleep 2.plist +43 -0
  197. package/templates/launchagents/com.nexo.evolution 2.plist +44 -0
  198. package/templates/launchagents/com.nexo.followup-hygiene 2.plist +45 -0
  199. package/templates/launchagents/com.nexo.immune 2.plist +41 -0
  200. package/templates/launchagents/com.nexo.postmortem 2.plist +45 -0
  201. package/templates/launchagents/com.nexo.self-audit 2.plist +47 -0
  202. package/templates/launchagents/com.nexo.synthesis 2.plist +45 -0
  203. package/templates/launchagents/com.nexo.watchdog 2.plist +37 -0
  204. package/templates/nexo_helper 2.py +301 -0
  205. package/templates/openclaw 2.json +13 -0
  206. package/templates/plugin-template 2.py +40 -0
  207. package/templates/script-template 2.py +59 -0
  208. package/templates/script-template 2.sh +13 -0
  209. package/templates/skill-script-template 2.py +48 -0
  210. package/templates/skill-template 2.md +33 -0
@@ -0,0 +1,19 @@
1
+ """Public MCP tools for the live NEXO system catalog / ontology."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from system_catalog import build_system_catalog, explain_tool, format_catalog, format_tool_explanation
6
+
7
+
8
+ def handle_system_catalog(section: str = "", query: str = "", limit: int = 20) -> str:
9
+ catalog = build_system_catalog()
10
+ return format_catalog(
11
+ catalog,
12
+ section=(section or "").strip(),
13
+ query=(query or "").strip(),
14
+ limit=max(1, int(limit or 20)),
15
+ )
16
+
17
+
18
+ def handle_tool_explain(name: str) -> str:
19
+ return format_tool_explanation(explain_tool(name))
@@ -0,0 +1,57 @@
1
+ """Task history tools: log executions, list history, report overdue tasks."""
2
+
3
+ import datetime
4
+ from db import log_task, list_task_history, set_task_frequency, get_overdue_tasks, get_task_frequencies
5
+
6
+
7
+ def _epoch_to_date(epoch: float) -> str:
8
+ """Format epoch timestamp as readable date string."""
9
+ return datetime.datetime.fromtimestamp(epoch).strftime("%Y-%m-%d %H:%M")
10
+
11
+
12
+ def handle_task_log(task_num: str, task_name: str, notes: str = '', reasoning: str = '') -> str:
13
+ """Record a task execution in the history log.
14
+
15
+ Args:
16
+ task_num: Task number identifier
17
+ task_name: Task name
18
+ notes: Execution notes
19
+ reasoning: WHY this task was executed now — what triggered it, what data informed it
20
+ """
21
+ result = log_task(task_num, task_name, notes, reasoning)
22
+ if "error" in result:
23
+ return f"ERROR: {result['error']}"
24
+ return f"Task {task_num} ({task_name}) logged."
25
+
26
+
27
+ def handle_task_list(task_num: str = '', days: int = 30) -> str:
28
+ """Show execution history for all tasks or a specific task number."""
29
+ results = list_task_history(task_num if task_num else None, days)
30
+ if not results:
31
+ scope = f"task {task_num}" if task_num else "any task"
32
+ return f"HISTORY: No executions of {scope} in recent days."
33
+ lines = [f"HISTORY ({len(results)} executions, {days}d):"]
34
+ for r in results:
35
+ date_str = _epoch_to_date(r["executed_at"])
36
+ notes_str = f": {r['notes']}" if r.get("notes") else ""
37
+ lines.append(f" {date_str} — Task {r['task_num']} ({r['task_name']}){notes_str}")
38
+ return "\n".join(lines)
39
+
40
+
41
+ def handle_task_frequency() -> str:
42
+ """Report tasks that are overdue based on their configured frequency."""
43
+ overdue = get_overdue_tasks()
44
+ if not overdue:
45
+ return "All tasks up to date."
46
+ lines = ["TAREAS VENCIDAS:"]
47
+ for t in overdue:
48
+ days_since = t.get("days_since_last")
49
+ if days_since is not None:
50
+ since_str = f"last run {days_since:.1f} days ago"
51
+ else:
52
+ since_str = "never executed"
53
+ lines.append(
54
+ f" Task {t['task_num']} ({t['task_name']}): "
55
+ f"{since_str}, frequency every {t['frequency_days']} days"
56
+ )
57
+ return "\n".join(lines)
@@ -0,0 +1,98 @@
1
+ """Public MCP tools for transcript fallback access."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from transcript_utils import (
6
+ clamp_transcript_hours,
7
+ list_recent_transcripts,
8
+ load_transcript,
9
+ search_transcripts,
10
+ )
11
+
12
+
13
+ def handle_transcript_search(query: str = "", hours: int = 24, client: str = "", limit: int = 10) -> str:
14
+ """Search recent Claude Code / Codex transcripts as a fallback when memory is insufficient."""
15
+ window = clamp_transcript_hours(hours)
16
+ rows = search_transcripts(query or "", hours=window, client=(client or "").strip(), limit=limit)
17
+ if not rows:
18
+ scope = f"query='{query}'" if query else "recent transcripts"
19
+ return f"No transcript matches for {scope} in the last {window}h."
20
+
21
+ lines = [f"TRANSCRIPTS ({len(rows)}) — last {window}h"]
22
+ for item in rows:
23
+ lines.append(
24
+ f"- {item.get('session_file')}: [{item.get('client')}] {item.get('display_name')} "
25
+ f"(modified={item.get('modified')}, messages={item.get('message_count')}, user={item.get('user_message_count')})"
26
+ )
27
+ if item.get("cwd"):
28
+ lines.append(f" cwd: {item['cwd']}")
29
+ if item.get("session_uid"):
30
+ lines.append(f" session_uid: {item['session_uid']}")
31
+ for snippet in item.get("matched_messages") or []:
32
+ lines.append(
33
+ f" [{snippet.get('role')}#{snippet.get('index')}] {snippet.get('snippet')}"
34
+ )
35
+ return "\n".join(lines)
36
+
37
+
38
+ def handle_transcript_recent(hours: int = 24, client: str = "", limit: int = 10) -> str:
39
+ """List recent transcripts without searching full text."""
40
+ window = clamp_transcript_hours(hours)
41
+ rows = list_recent_transcripts(hours=window, client=(client or "").strip(), limit=limit)
42
+ if not rows:
43
+ return f"No transcripts found in the last {window}h."
44
+
45
+ lines = [f"RECENT TRANSCRIPTS ({len(rows)}) — last {window}h"]
46
+ for item in rows:
47
+ lines.append(
48
+ f"- {item.get('session_file')}: [{item.get('client')}] {item.get('display_name')} "
49
+ f"(modified={item.get('modified')}, messages={item.get('message_count')}, user={item.get('user_message_count')})"
50
+ )
51
+ return "\n".join(lines)
52
+
53
+
54
+ def handle_transcript_read(
55
+ session_ref: str = "",
56
+ transcript_path: str = "",
57
+ client: str = "",
58
+ max_messages: int = 80,
59
+ ) -> str:
60
+ """Read a transcript in fallback mode. Accepts session_file, display name, session_uid or exact path."""
61
+ transcript = load_transcript(
62
+ session_ref=(session_ref or "").strip(),
63
+ transcript_path=(transcript_path or "").strip(),
64
+ client=(client or "").strip(),
65
+ )
66
+ if not transcript:
67
+ target = session_ref or transcript_path or "(empty ref)"
68
+ return f"Transcript not found for {target}."
69
+
70
+ limit = max(1, min(int(max_messages or 80), 200))
71
+ messages = transcript.get("messages") or []
72
+ truncated = len(messages) > limit
73
+ visible = messages[-limit:] if truncated else messages
74
+
75
+ lines = [
76
+ f"TRANSCRIPT {transcript.get('session_file')}",
77
+ f"Client: {transcript.get('client')}",
78
+ f"Display: {transcript.get('display_name')}",
79
+ f"Path: {transcript.get('session_path')}",
80
+ f"Modified: {transcript.get('modified')}",
81
+ f"Messages: {transcript.get('message_count')} (user={transcript.get('user_message_count')}, tools={transcript.get('tool_use_count')})",
82
+ ]
83
+ if transcript.get("cwd"):
84
+ lines.append(f"CWD: {transcript.get('cwd')}")
85
+ if transcript.get("session_uid"):
86
+ lines.append(f"Session UID: {transcript.get('session_uid')}")
87
+ if truncated:
88
+ lines.append(f"Showing last {limit} messages.")
89
+
90
+ for message in visible:
91
+ role = str(message.get("role") or "?").upper()
92
+ index = message.get("index", "?")
93
+ text = str(message.get("text") or "").strip()
94
+ lines.append("")
95
+ lines.append(f"[{role} #{index}]")
96
+ lines.append(text)
97
+
98
+ return "\n".join(lines)
@@ -0,0 +1,412 @@
1
+ from __future__ import annotations
2
+ """Shared transcript helpers for Deep Sleep and public MCP fallback tools."""
3
+
4
+ import json
5
+ import os
6
+ import re
7
+ import unicodedata
8
+ from datetime import datetime, timedelta
9
+ from pathlib import Path
10
+
11
+ MIN_USER_MESSAGES = 3
12
+ DEFAULT_TRANSCRIPT_HOURS = 24
13
+ MAX_TRANSCRIPT_HOURS = 30 * 24
14
+
15
+ _SENSITIVE_PATTERNS = re.compile(
16
+ r'(?:'
17
+ r'sk-ant-[A-Za-z0-9_-]+'
18
+ r'|shpat_[A-Fa-f0-9]+'
19
+ r'|shpss_[A-Fa-f0-9]+'
20
+ r'|sk-[A-Za-z0-9]{20,}'
21
+ r'|ghp_[A-Za-z0-9]{36,}'
22
+ r'|gho_[A-Za-z0-9]{36,}'
23
+ r'|AIza[A-Za-z0-9_-]{35}'
24
+ r'|ya29\.[A-Za-z0-9_-]+'
25
+ r'|xox[bpsa]-[A-Za-z0-9-]+'
26
+ r'|EAAG[A-Za-z0-9]+'
27
+ r'|[Pp]assword\s*[:=]\s*\S+'
28
+ r'|[Ss]ecret\s*[:=]\s*\S+'
29
+ r'|[Tt]oken\s*[:=]\s*\S+'
30
+ r'|[Aa]pi[_-]?[Kk]ey\s*[:=]\s*\S+'
31
+ r')'
32
+ )
33
+
34
+
35
+ def _redact_sensitive(text: str) -> str:
36
+ return _SENSITIVE_PATTERNS.sub("[REDACTED]", text)
37
+
38
+
39
+ def _normalize_text(text: str | None) -> str:
40
+ if not text:
41
+ return ""
42
+ normalized = unicodedata.normalize("NFKD", str(text))
43
+ ascii_text = normalized.encode("ascii", "ignore").decode("ascii")
44
+ return ascii_text.lower()
45
+
46
+
47
+ def _tokenize(text: str | None) -> set[str]:
48
+ normalized = _normalize_text(text)
49
+ return {
50
+ token
51
+ for token in re.findall(r"[a-z0-9][a-z0-9._:-]{1,}", normalized)
52
+ if len(token) >= 3
53
+ }
54
+
55
+
56
+ def _score_text_match(query_tokens: set[str], haystack: str) -> float:
57
+ if not query_tokens:
58
+ return 0.0
59
+ haystack_tokens = _tokenize(haystack)
60
+ if not haystack_tokens:
61
+ return 0.0
62
+ intersection = query_tokens & haystack_tokens
63
+ if not intersection:
64
+ return 0.0
65
+ smaller = min(len(query_tokens), len(haystack_tokens))
66
+ return len(intersection) / max(1, smaller)
67
+
68
+
69
+ def _truncate(text: str | None, limit: int = 240) -> str:
70
+ if not text:
71
+ return ""
72
+ clean = str(text).strip()
73
+ return clean if len(clean) <= limit else clean[: limit - 3] + "..."
74
+
75
+
76
+ def _session_identifier(client: str, session_file: str) -> str:
77
+ return f"{client}:{session_file}"
78
+
79
+
80
+ def _claude_root() -> Path:
81
+ return Path.home() / ".claude" / "projects"
82
+
83
+
84
+ def _codex_roots() -> list[Path]:
85
+ return [
86
+ Path.home() / ".codex" / "sessions",
87
+ Path.home() / ".codex" / "archived_sessions",
88
+ ]
89
+
90
+
91
+ def clamp_transcript_hours(hours: int | float | str | None) -> int:
92
+ try:
93
+ value = int(float(hours or DEFAULT_TRANSCRIPT_HOURS))
94
+ except Exception:
95
+ value = DEFAULT_TRANSCRIPT_HOURS
96
+ return max(1, min(value, MAX_TRANSCRIPT_HOURS))
97
+
98
+
99
+ def find_claude_session_files() -> list[Path]:
100
+ claude_dir = _claude_root()
101
+ if not claude_dir.exists():
102
+ return []
103
+ return sorted(claude_dir.rglob("*.jsonl"))
104
+
105
+
106
+ def find_codex_session_files() -> list[Path]:
107
+ files: list[Path] = []
108
+ seen: set[str] = set()
109
+ for root in _codex_roots():
110
+ if not root.exists():
111
+ continue
112
+ for jsonl in sorted(root.rglob("*.jsonl")):
113
+ key = jsonl.name
114
+ if key in seen:
115
+ continue
116
+ seen.add(key)
117
+ files.append(jsonl)
118
+ return files
119
+
120
+
121
+ def extract_claude_session(jsonl_path: Path) -> dict | None:
122
+ messages = []
123
+ tool_uses = []
124
+ user_msg_count = 0
125
+
126
+ try:
127
+ with open(jsonl_path, "r") as f:
128
+ for line_no, line in enumerate(f, 1):
129
+ line = line.strip()
130
+ if not line:
131
+ continue
132
+ try:
133
+ payload = json.loads(line)
134
+ except json.JSONDecodeError:
135
+ continue
136
+
137
+ msg_type = payload.get("type")
138
+ if msg_type == "user":
139
+ content = payload.get("message", {}).get("content", "")
140
+ if isinstance(content, str) and content.strip():
141
+ if content.startswith("<system-reminder>"):
142
+ continue
143
+ messages.append(
144
+ {
145
+ "role": "user",
146
+ "index": line_no,
147
+ "text": _redact_sensitive(content[:5000]),
148
+ "uuid": payload.get("uuid", ""),
149
+ }
150
+ )
151
+ user_msg_count += 1
152
+ elif msg_type in ("message", "assistant"):
153
+ msg = payload.get("message", {})
154
+ content_blocks = msg.get("content", [])
155
+ text_parts = []
156
+ for block in content_blocks:
157
+ if not isinstance(block, dict):
158
+ continue
159
+ if block.get("type") == "text":
160
+ text_parts.append(block.get("text", ""))
161
+ elif block.get("type") == "tool_use":
162
+ tool_input = block.get("input", {})
163
+ raw_file = (
164
+ tool_input.get("file_path", "")
165
+ or str(tool_input.get("command", ""))[:100]
166
+ ) if isinstance(tool_input, dict) else ""
167
+ tool_uses.append(
168
+ {
169
+ "tool": block.get("name", ""),
170
+ "input_keys": list(tool_input.keys()) if isinstance(tool_input, dict) else [],
171
+ "file": _redact_sensitive(raw_file),
172
+ }
173
+ )
174
+ combined = "\n".join(part for part in text_parts if part).strip()
175
+ if combined:
176
+ messages.append(
177
+ {
178
+ "role": "assistant",
179
+ "index": line_no,
180
+ "text": _redact_sensitive(combined[:5000]),
181
+ }
182
+ )
183
+ except Exception:
184
+ return None
185
+
186
+ if user_msg_count < MIN_USER_MESSAGES:
187
+ return None
188
+
189
+ return {
190
+ "client": "claude_code",
191
+ "session_file": _session_identifier("claude_code", jsonl_path.name),
192
+ "display_name": jsonl_path.name,
193
+ "session_path": str(jsonl_path),
194
+ "message_count": len(messages),
195
+ "user_message_count": user_msg_count,
196
+ "tool_use_count": len(tool_uses),
197
+ "messages": messages,
198
+ "tool_uses": tool_uses,
199
+ "source": "claude_projects",
200
+ }
201
+
202
+
203
+ def extract_codex_session(jsonl_path: Path) -> dict | None:
204
+ messages = []
205
+ tool_uses = []
206
+ user_msg_count = 0
207
+ session_meta: dict = {}
208
+
209
+ try:
210
+ with open(jsonl_path, "r") as f:
211
+ for line_no, line in enumerate(f, 1):
212
+ line = line.strip()
213
+ if not line:
214
+ continue
215
+ try:
216
+ payload = json.loads(line)
217
+ except json.JSONDecodeError:
218
+ continue
219
+
220
+ item_type = payload.get("type")
221
+ data = payload.get("payload", {})
222
+
223
+ if item_type == "session_meta" and isinstance(data, dict):
224
+ session_meta = data
225
+ continue
226
+
227
+ if item_type == "event_msg" and isinstance(data, dict) and data.get("type") == "user_message":
228
+ content = str(data.get("message", "") or "").strip()
229
+ if not content or content.startswith("<environment_context>"):
230
+ continue
231
+ messages.append(
232
+ {
233
+ "role": "user",
234
+ "index": line_no,
235
+ "text": _redact_sensitive(content[:5000]),
236
+ }
237
+ )
238
+ user_msg_count += 1
239
+ continue
240
+
241
+ if item_type == "response_item" and isinstance(data, dict):
242
+ response_type = data.get("type")
243
+ role = data.get("role")
244
+ if response_type == "message" and role == "assistant":
245
+ text_parts = []
246
+ for block in data.get("content", []) or []:
247
+ if isinstance(block, dict) and block.get("type") == "output_text":
248
+ text_parts.append(str(block.get("text", "")))
249
+ combined = "\n".join(part for part in text_parts if part).strip()
250
+ if combined:
251
+ messages.append(
252
+ {
253
+ "role": "assistant",
254
+ "index": line_no,
255
+ "text": _redact_sensitive(combined[:5000]),
256
+ }
257
+ )
258
+ elif response_type == "function_call":
259
+ tool_uses.append(
260
+ {
261
+ "tool": data.get("name", ""),
262
+ "input_keys": [],
263
+ "file": _redact_sensitive(str(data.get("arguments", ""))[:100]),
264
+ }
265
+ )
266
+ except Exception:
267
+ return None
268
+
269
+ if user_msg_count < MIN_USER_MESSAGES:
270
+ return None
271
+
272
+ return {
273
+ "client": "codex",
274
+ "session_file": _session_identifier("codex", jsonl_path.name),
275
+ "display_name": jsonl_path.name,
276
+ "session_path": str(jsonl_path),
277
+ "message_count": len(messages),
278
+ "user_message_count": user_msg_count,
279
+ "tool_use_count": len(tool_uses),
280
+ "messages": messages,
281
+ "tool_uses": tool_uses,
282
+ "source": session_meta.get("source", "codex"),
283
+ "cwd": session_meta.get("cwd", ""),
284
+ "originator": session_meta.get("originator", ""),
285
+ "session_uid": session_meta.get("id", ""),
286
+ }
287
+
288
+
289
+ def collect_transcripts_since(since_iso: str, until_iso: str = "") -> list[dict]:
290
+ since_dt = datetime.fromisoformat(since_iso)
291
+ until_dt = datetime.fromisoformat(until_iso) if until_iso else datetime.now()
292
+ sessions = []
293
+ transcript_files: list[tuple[str, Path]] = [
294
+ ("claude_code", path) for path in find_claude_session_files()
295
+ ] + [
296
+ ("codex", path) for path in find_codex_session_files()
297
+ ]
298
+ for client, session_file in transcript_files:
299
+ try:
300
+ mtime = datetime.fromtimestamp(session_file.stat().st_mtime)
301
+ except OSError:
302
+ continue
303
+ if not (since_dt < mtime <= until_dt):
304
+ continue
305
+ session = extract_codex_session(session_file) if client == "codex" else extract_claude_session(session_file)
306
+ if session:
307
+ session["modified"] = mtime.isoformat()
308
+ sessions.append(session)
309
+ sessions.sort(key=lambda row: row["modified"])
310
+ return sessions
311
+
312
+
313
+ def list_recent_transcripts(hours: int = DEFAULT_TRANSCRIPT_HOURS, client: str = "", limit: int = 10) -> list[dict]:
314
+ window = clamp_transcript_hours(hours)
315
+ since = datetime.now() - timedelta(hours=window)
316
+ sessions = collect_transcripts_since(since.isoformat())
317
+ filtered = []
318
+ for item in sessions:
319
+ if client and item.get("client") != client:
320
+ continue
321
+ filtered.append(item)
322
+ filtered.sort(key=lambda row: row.get("modified", ""), reverse=True)
323
+ return filtered[: max(1, int(limit or 10))]
324
+
325
+
326
+ def search_transcripts(query: str, *, hours: int = DEFAULT_TRANSCRIPT_HOURS, client: str = "", limit: int = 10) -> list[dict]:
327
+ rows = list_recent_transcripts(hours=hours, client=client, limit=200)
328
+ query_tokens = _tokenize(query)
329
+ if not query_tokens:
330
+ return rows[: max(1, int(limit or 10))]
331
+
332
+ matches: list[dict] = []
333
+ cutoff_seconds = clamp_transcript_hours(hours) * 3600
334
+ now = datetime.now().timestamp()
335
+ for item in rows:
336
+ snippets = []
337
+ best_score = 0.0
338
+ for message in item.get("messages") or []:
339
+ text = str(message.get("text", "") or "")
340
+ score = _score_text_match(query_tokens, text)
341
+ if score <= 0:
342
+ continue
343
+ best_score = max(best_score, score)
344
+ snippets.append(
345
+ {
346
+ "role": message.get("role", ""),
347
+ "index": message.get("index", 0),
348
+ "snippet": _truncate(text, 220),
349
+ "score": round(score, 4),
350
+ }
351
+ )
352
+ meta_text = " ".join(
353
+ [
354
+ str(item.get("display_name", "") or ""),
355
+ str(item.get("session_file", "") or ""),
356
+ str(item.get("source", "") or ""),
357
+ str(item.get("cwd", "") or ""),
358
+ ]
359
+ )
360
+ meta_score = _score_text_match(query_tokens, meta_text)
361
+ best_score = max(best_score, meta_score)
362
+ if best_score <= 0:
363
+ continue
364
+ modified = item.get("modified", "")
365
+ try:
366
+ modified_ts = datetime.fromisoformat(modified).timestamp()
367
+ except Exception:
368
+ modified_ts = now
369
+ recency = max(0.0, 1.0 - ((now - modified_ts) / max(1, cutoff_seconds)))
370
+ item["_score"] = round(best_score + recency * 0.35, 4)
371
+ item["matched_messages"] = sorted(snippets, key=lambda row: row["score"], reverse=True)[:3]
372
+ matches.append(item)
373
+
374
+ matches.sort(key=lambda row: (row.get("_score", 0), row.get("modified", "")), reverse=True)
375
+ return matches[: max(1, int(limit or 10))]
376
+
377
+
378
+ def load_transcript(session_ref: str = "", transcript_path: str = "", client: str = "") -> dict | None:
379
+ ref = str(session_ref or "").strip()
380
+ path_ref = str(transcript_path or "").strip()
381
+
382
+ transcript_files: list[tuple[str, Path]] = [
383
+ ("claude_code", path) for path in find_claude_session_files()
384
+ ] + [
385
+ ("codex", path) for path in find_codex_session_files()
386
+ ]
387
+ for detected_client, path in transcript_files:
388
+ if client and detected_client != client:
389
+ continue
390
+ if path_ref:
391
+ try:
392
+ if Path(path_ref).expanduser().resolve() != path.resolve():
393
+ continue
394
+ except Exception:
395
+ continue
396
+ session = extract_codex_session(path) if detected_client == "codex" else extract_claude_session(path)
397
+ if not session:
398
+ continue
399
+ if ref:
400
+ if ref not in {
401
+ str(session.get("session_file", "")),
402
+ str(session.get("display_name", "")),
403
+ str(session.get("session_uid", "")),
404
+ str(path),
405
+ }:
406
+ continue
407
+ try:
408
+ session["modified"] = datetime.fromtimestamp(path.stat().st_mtime).isoformat()
409
+ except OSError:
410
+ session["modified"] = ""
411
+ return session
412
+ return None
@@ -0,0 +1,46 @@
1
+ """User context singleton — loads operator/user identity from calibration.json."""
2
+ from __future__ import annotations
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+
7
+ _ctx = None
8
+
9
+ class UserContext:
10
+ """Cached user/operator identity loaded once from calibration.json."""
11
+
12
+ def __init__(self):
13
+ nexo_home = Path(os.environ.get("NEXO_HOME", str(Path.home() / ".nexo")))
14
+ cal_path = nexo_home / "brain" / "calibration.json"
15
+ ver_path = nexo_home / "version.json"
16
+
17
+ self.assistant_name = "NEXO"
18
+ self.user_name = ""
19
+ self.user_language = "en"
20
+
21
+ # calibration.json has operator_name + user info
22
+ if cal_path.exists():
23
+ try:
24
+ cal = json.loads(cal_path.read_text())
25
+ self.assistant_name = cal.get("operator_name", "") or \
26
+ cal.get("user", {}).get("assistant_name", "") or "NEXO"
27
+ self.user_name = cal.get("user", {}).get("name", "")
28
+ self.user_language = cal.get("user", {}).get("language", "en")
29
+ except Exception:
30
+ pass
31
+
32
+ # Fallback: version.json also has operator_name
33
+ if self.assistant_name == "NEXO" and ver_path.exists():
34
+ try:
35
+ ver = json.loads(ver_path.read_text())
36
+ self.assistant_name = ver.get("operator_name", "") or "NEXO"
37
+ except Exception:
38
+ pass
39
+
40
+
41
+ def get_context() -> UserContext:
42
+ """Get or create the singleton UserContext."""
43
+ global _ctx
44
+ if _ctx is None:
45
+ _ctx = UserContext()
46
+ return _ctx