nexo-brain 5.3.13 → 5.3.15

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 (230) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/bin/nexo-brain.js +52 -1
  3. package/package.json +1 -1
  4. package/src/crons/sync.py +18 -4
  5. package/src/dashboard/static/favicon 2.svg +32 -0
  6. package/src/dashboard/static/nexo-logo 2.png +0 -0
  7. package/src/dashboard/static/nexo-logo 2.svg +40 -0
  8. package/src/dashboard/static/style 2.css +2458 -0
  9. package/src/dashboard/templates/adaptive 2.html +118 -0
  10. package/src/dashboard/templates/artifacts 2.html +133 -0
  11. package/src/dashboard/templates/backups 2.html +136 -0
  12. package/src/dashboard/templates/base 2.html +417 -0
  13. package/src/dashboard/templates/calendar 2.html +591 -0
  14. package/src/dashboard/templates/chat 2.html +356 -0
  15. package/src/dashboard/templates/claims 2.html +259 -0
  16. package/src/dashboard/templates/cortex 2.html +321 -0
  17. package/src/dashboard/templates/credentials 2.html +128 -0
  18. package/src/dashboard/templates/crons 2.html +370 -0
  19. package/src/dashboard/templates/dashboard 2.html +494 -0
  20. package/src/dashboard/templates/dreams 2.html +252 -0
  21. package/src/dashboard/templates/email 2.html +160 -0
  22. package/src/dashboard/templates/evolution 2.html +189 -0
  23. package/src/dashboard/templates/feed 2.html +249 -0
  24. package/src/dashboard/templates/followup_health 2.html +170 -0
  25. package/src/dashboard/templates/graph 2.html +201 -0
  26. package/src/dashboard/templates/guard 2.html +259 -0
  27. package/src/dashboard/templates/inbox 2.html +251 -0
  28. package/src/dashboard/templates/memory 2.html +420 -0
  29. package/src/dashboard/templates/operations 2.html +608 -0
  30. package/src/dashboard/templates/plugins 2.html +185 -0
  31. package/src/dashboard/templates/protocol 2.html +199 -0
  32. package/src/dashboard/templates/rules 2.html +246 -0
  33. package/src/dashboard/templates/sentiment 2.html +247 -0
  34. package/src/dashboard/templates/sessions 2.html +218 -0
  35. package/src/dashboard/templates/skills 2.html +329 -0
  36. package/src/dashboard/templates/somatic 2.html +73 -0
  37. package/src/dashboard/templates/triggers 2.html +133 -0
  38. package/src/dashboard/templates/trust 2.html +360 -0
  39. package/src/db/__init__ 2.py +259 -0
  40. package/src/db/_core 2.py +437 -0
  41. package/src/db/_credentials 2.py +124 -0
  42. package/src/db/_entities.py +1 -1
  43. package/src/db/_episodic 2.py +762 -0
  44. package/src/db/_evolution 2.py +54 -0
  45. package/src/db/_fts 2.py +406 -0
  46. package/src/db/_goal_profiles 2.py +376 -0
  47. package/src/db/_hot_context 2.py +660 -0
  48. package/src/db/_outcomes 2.py +800 -0
  49. package/src/db/_personal_scripts 2.py +582 -0
  50. package/src/db/_sessions 2.py +330 -0
  51. package/src/db/_tasks 2.py +91 -0
  52. package/src/db/_watchers 2.py +173 -0
  53. package/src/doctor/formatters 2.py +52 -0
  54. package/src/doctor/models 2.py +69 -0
  55. package/src/doctor/planes 2.py +87 -0
  56. package/src/doctor/providers/__init__ 2.py +1 -0
  57. package/src/doctor/providers/deep 2.py +367 -0
  58. package/src/evolution_cycle 2.py +519 -0
  59. package/src/hooks/auto_capture 2.py +208 -0
  60. package/src/hooks/caffeinate-guard 2.sh +8 -0
  61. package/src/hooks/capture-session 2.sh +21 -0
  62. package/src/hooks/capture-tool-logs 2.sh +158 -0
  63. package/src/hooks/daily-briefing-check 2.sh +33 -0
  64. package/src/hooks/heartbeat-enforcement 2.py +90 -0
  65. package/src/hooks/heartbeat-posttool 2.sh +18 -0
  66. package/src/hooks/inbox-hook 2.sh +76 -0
  67. package/src/hooks/post-compact 2.sh +152 -0
  68. package/src/hooks/pre-compact 2.sh +169 -0
  69. package/src/hooks/protocol-guardrail 2.sh +10 -0
  70. package/src/hooks/protocol-pretool-guardrail 2.sh +9 -0
  71. package/src/hooks/session-stop 2.sh +52 -0
  72. package/src/kg_populate 2.py +292 -0
  73. package/src/maintenance 2.py +53 -0
  74. package/src/memory_backends 2.py +71 -0
  75. package/src/migrate_embeddings 2.py +124 -0
  76. package/src/nexo_sdk 2.py +103 -0
  77. package/src/observability 2.py +199 -0
  78. package/src/plugin_loader 2.py +217 -0
  79. package/src/plugins/__init__ 2.py +0 -0
  80. package/src/plugins/agents.py +10 -3
  81. package/src/plugins/artifact_registry 2.py +450 -0
  82. package/src/plugins/backup 2.py +127 -0
  83. package/src/plugins/claims_tools 2.py +119 -0
  84. package/src/plugins/cognitive_memory 2.py +609 -0
  85. package/src/plugins/core_rules 2.py +252 -0
  86. package/src/plugins/cortex 2.py +1155 -0
  87. package/src/plugins/entities 2.py +67 -0
  88. package/src/plugins/episodic_memory 2.py +560 -0
  89. package/src/plugins/evolution 2.py +167 -0
  90. package/src/plugins/goal_engine 2.py +142 -0
  91. package/src/plugins/guard 2.py +862 -0
  92. package/src/plugins/impact 2.py +29 -0
  93. package/src/plugins/knowledge_graph_tools 2.py +137 -0
  94. package/src/plugins/media_memory_tools 2.py +98 -0
  95. package/src/plugins/memory_export 2.py +196 -0
  96. package/src/plugins/outcomes 2.py +130 -0
  97. package/src/plugins/personal_scripts 2.py +117 -0
  98. package/src/plugins/preferences 2.py +47 -0
  99. package/src/plugins/protocol 2.py +1449 -0
  100. package/src/plugins/schedule.py +2 -1
  101. package/src/plugins/simple_api 2.py +106 -0
  102. package/src/plugins/skills 2.py +341 -0
  103. package/src/plugins/state_watchers 2.py +79 -0
  104. package/src/plugins/update 2.py +986 -0
  105. package/src/plugins/user_state_tools 2.py +43 -0
  106. package/src/plugins/workflow 2.py +588 -0
  107. package/src/protocol_settings 2.py +59 -0
  108. package/src/public_contribution 2.py +466 -0
  109. package/src/public_evolution_queue 2.py +241 -0
  110. package/src/requirements 2.txt +14 -0
  111. package/src/requirements.txt +1 -1
  112. package/src/retroactive_learnings 2.py +373 -0
  113. package/src/rules/__init__ 2.py +0 -0
  114. package/src/rules/core-rules 2.json +331 -0
  115. package/src/rules/migrate 2.py +207 -0
  116. package/src/runtime_power 2.py +874 -0
  117. package/src/runtime_power.py +18 -1
  118. package/src/script_registry 2.py +1559 -0
  119. package/src/scripts/check-context 2.py +272 -0
  120. package/src/scripts/deep-sleep/apply_findings 2.py +2327 -0
  121. package/src/scripts/deep-sleep/collect 2.py +928 -0
  122. package/src/scripts/deep-sleep/extract 2.py +330 -0
  123. package/src/scripts/deep-sleep/extract-prompt 2.md +285 -0
  124. package/src/scripts/deep-sleep/synthesize 2.py +312 -0
  125. package/src/scripts/deep-sleep/synthesize-prompt 2.md +336 -0
  126. package/src/scripts/nexo-agent-run 2.py +75 -0
  127. package/src/scripts/nexo-auto-update 2.py +6 -0
  128. package/src/scripts/nexo-backup 2.sh +25 -0
  129. package/src/scripts/nexo-brain-activation 2.sh +140 -0
  130. package/src/scripts/nexo-catchup 2.py +300 -0
  131. package/src/scripts/nexo-cognitive-decay 2.py +257 -0
  132. package/src/scripts/nexo-cortex-cycle 2.py +293 -0
  133. package/src/scripts/nexo-cron-wrapper 2.sh +53 -0
  134. package/src/scripts/nexo-cron-wrapper.sh +7 -0
  135. package/src/scripts/nexo-daily-self-audit 2.py +2161 -0
  136. package/src/scripts/nexo-dashboard 2.sh +29 -0
  137. package/src/scripts/nexo-deep-sleep 2.sh +86 -0
  138. package/src/scripts/nexo-evolution-run 2.py +1664 -0
  139. package/src/scripts/nexo-followup-hygiene 2.py +139 -0
  140. package/src/scripts/nexo-hook-record 2.py +42 -0
  141. package/src/scripts/nexo-immune 2.py +936 -0
  142. package/src/scripts/nexo-impact-scorer 2.py +117 -0
  143. package/src/scripts/nexo-inbox-hook 2.sh +74 -0
  144. package/src/scripts/nexo-install 2.py +6 -0
  145. package/src/scripts/nexo-learning-housekeep 2.py +401 -0
  146. package/src/scripts/nexo-learning-validator 2.py +266 -0
  147. package/src/scripts/nexo-migrate 2.py +260 -0
  148. package/src/scripts/nexo-outcome-checker 2.py +127 -0
  149. package/src/scripts/nexo-postmortem-consolidator 2.py +456 -0
  150. package/src/scripts/nexo-pre-commit 2.py +120 -0
  151. package/src/scripts/nexo-prevent-sleep 2.sh +35 -0
  152. package/src/scripts/nexo-proactive-dashboard 2.py +354 -0
  153. package/src/scripts/nexo-reflection 2.py +256 -0
  154. package/src/scripts/nexo-runtime-preflight 2.py +274 -0
  155. package/src/scripts/nexo-sleep 2.py +631 -0
  156. package/src/scripts/nexo-snapshot-restore 2.sh +35 -0
  157. package/src/scripts/nexo-sync-clients 2.py +16 -0
  158. package/src/scripts/nexo-synthesis 2.py +475 -0
  159. package/src/scripts/nexo-tcc-approve 2.sh +79 -0
  160. package/src/scripts/nexo-update 2.sh +306 -0
  161. package/src/scripts/nexo-watchdog 2.sh +1207 -0
  162. package/src/scripts/nexo-watchdog-smoke 2.py +119 -0
  163. package/src/scripts/rehydrate_learnings_from_archive 2.py +245 -0
  164. package/src/server 2.py +1296 -0
  165. package/src/skills/run-nexo-audit-phase/guide 2.md +43 -0
  166. package/src/skills/run-nexo-audit-phase/skill 2.json +59 -0
  167. package/src/skills/run-nexo-core-fix-cycle/guide 2.md +17 -0
  168. package/src/skills/run-nexo-core-fix-cycle/script 2.py +276 -0
  169. package/src/skills/run-nexo-core-fix-cycle/skill 2.json +58 -0
  170. package/src/skills/run-release-final-audit/guide 2.md +16 -0
  171. package/src/skills/run-release-final-audit/script 2.py +259 -0
  172. package/src/skills/run-release-final-audit/skill 2.json +77 -0
  173. package/src/skills/run-runtime-doctor/guide 2.md +12 -0
  174. package/src/skills/run-runtime-doctor/script 2.py +21 -0
  175. package/src/skills/run-runtime-doctor/skill 2.json +25 -0
  176. package/src/skills_runtime 2.py +932 -0
  177. package/src/state_watchers_runtime 2.py +475 -0
  178. package/src/storage_router 2.py +32 -0
  179. package/src/system_catalog 2.py +786 -0
  180. package/src/tools_coordination 2.py +103 -0
  181. package/src/tools_credentials 2.py +68 -0
  182. package/src/tools_drive 2.py +487 -0
  183. package/src/tools_hot_context 2.py +163 -0
  184. package/src/tools_learnings 2.py +612 -0
  185. package/src/tools_menu 2.py +229 -0
  186. package/src/tools_reminders 2.py +88 -0
  187. package/src/tools_reminders_crud 2.py +363 -0
  188. package/src/tools_sessions 2.py +1054 -0
  189. package/src/tools_system_catalog 2.py +19 -0
  190. package/src/tools_task_history 2.py +57 -0
  191. package/src/tools_transcripts 2.py +98 -0
  192. package/src/transcript_utils 2.py +412 -0
  193. package/src/user_context 2.py +46 -0
  194. package/src/user_data_portability 2.py +328 -0
  195. package/src/user_state_model 2.py +170 -0
  196. package/templates/CLAUDE.md 2.template +108 -0
  197. package/templates/CODEX.AGENTS.md 2.template +66 -0
  198. package/templates/launchagents/README 2.md +132 -0
  199. package/templates/launchagents/com.nexo.auto-close-sessions 2.plist +39 -0
  200. package/templates/launchagents/com.nexo.auto-close-sessions.plist +1 -1
  201. package/templates/launchagents/com.nexo.catchup 2.plist +39 -0
  202. package/templates/launchagents/com.nexo.catchup.plist +1 -1
  203. package/templates/launchagents/com.nexo.cognitive-decay 2.plist +40 -0
  204. package/templates/launchagents/com.nexo.dashboard 2.plist +43 -0
  205. package/templates/launchagents/com.nexo.dashboard.plist +1 -1
  206. package/templates/launchagents/com.nexo.deep-sleep 2.plist +43 -0
  207. package/templates/launchagents/com.nexo.deep-sleep.plist +1 -1
  208. package/templates/launchagents/com.nexo.evolution 2.plist +44 -0
  209. package/templates/launchagents/com.nexo.evolution.plist +1 -1
  210. package/templates/launchagents/com.nexo.followup-hygiene 2.plist +45 -0
  211. package/templates/launchagents/com.nexo.followup-hygiene.plist +1 -1
  212. package/templates/launchagents/com.nexo.immune 2.plist +41 -0
  213. package/templates/launchagents/com.nexo.immune.plist +1 -1
  214. package/templates/launchagents/com.nexo.postmortem 2.plist +45 -0
  215. package/templates/launchagents/com.nexo.postmortem.plist +1 -1
  216. package/templates/launchagents/com.nexo.self-audit 2.plist +47 -0
  217. package/templates/launchagents/com.nexo.self-audit.plist +1 -1
  218. package/templates/launchagents/com.nexo.synthesis 2.plist +45 -0
  219. package/templates/launchagents/com.nexo.synthesis.plist +1 -1
  220. package/templates/launchagents/com.nexo.watchdog 2.plist +37 -0
  221. package/templates/launchagents/com.nexo.watchdog.plist +1 -1
  222. package/templates/nexo_helper 2.py +301 -0
  223. package/templates/openclaw 2.json +13 -0
  224. package/templates/plugin-template 2.py +40 -0
  225. package/templates/script-template 2.py +59 -0
  226. package/templates/script-template 2.sh +13 -0
  227. package/templates/script-template.py +5 -4
  228. package/templates/skill-script-template 2.py +48 -0
  229. package/templates/skill-script-template.py +2 -1
  230. package/templates/skill-template 2.md +33 -0
@@ -0,0 +1,167 @@
1
+ """Evolution plugin — NEXO self-improvement tools for interactive sessions."""
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ from db import get_latest_metrics, get_evolution_history, update_evolution_log_status, get_db
7
+
8
+
9
+ CANONICAL_DIMENSIONS = {
10
+ "episodic_memory": "Episodic Memory",
11
+ "autonomy": "Autonomy",
12
+ "proactivity": "Proactivity",
13
+ "self_improvement": "Self-improvement",
14
+ "agi": "AGI",
15
+ }
16
+
17
+
18
+ def _resolve_objective_file() -> Path:
19
+ nexo_home = Path(os.environ.get("NEXO_HOME", str(Path.home() / ".nexo")))
20
+ for candidate in (
21
+ nexo_home / "brain" / "evolution-objective.json",
22
+ nexo_home / "cortex" / "evolution-objective.json",
23
+ ):
24
+ if candidate.exists():
25
+ return candidate
26
+ return nexo_home / "brain" / "evolution-objective.json"
27
+
28
+
29
+ def _load_objective() -> dict:
30
+ try:
31
+ raw = json.loads(_resolve_objective_file().read_text())
32
+ except Exception:
33
+ return {}
34
+ return raw if isinstance(raw, dict) else {}
35
+
36
+
37
+ def handle_evolution_status() -> str:
38
+ """Show current NEXO dimension scores and recent trend."""
39
+ metrics = get_latest_metrics()
40
+ objective = _load_objective()
41
+ objective_dims = objective.get("dimensions", {}) if isinstance(objective.get("dimensions"), dict) else {}
42
+
43
+ from user_context import get_context
44
+ lines = [f"{get_context().assistant_name} EVOLUTION STATUS:"]
45
+ has_output = False
46
+ for key, label in CANONICAL_DIMENSIONS.items():
47
+ m = metrics.get(key)
48
+ if m:
49
+ score = m["score"]
50
+ delta = m["delta"]
51
+ bar = "█" * (score // 5) + "░" * (20 - score // 5)
52
+ delta_str = f" (+{delta})" if delta > 0 else f" ({delta})" if delta < 0 else " (=)"
53
+ target = ""
54
+ if isinstance(objective_dims.get(key), dict) and objective_dims[key].get("target") is not None:
55
+ target = f" / target {int(objective_dims[key].get('target', 0) or 0)}%"
56
+ lines.append(f" {label:<20} {bar} {score}%{delta_str}{target}")
57
+ has_output = True
58
+ continue
59
+
60
+ objective_entry = objective_dims.get(key)
61
+ if isinstance(objective_entry, dict):
62
+ score = int(objective_entry.get("current", 0) or 0)
63
+ target = int(objective_entry.get("target", 0) or 0)
64
+ bar = "█" * (score // 5) + "░" * (20 - score // 5)
65
+ lines.append(f" {label:<20} {bar} {score}% (objective fallback, target {target}%)")
66
+ has_output = True
67
+
68
+ if not has_output:
69
+ return "No evolution metrics recorded."
70
+
71
+ if not metrics:
72
+ lines.append(" Note: no persisted evolution_metrics rows yet; showing objective fallback.")
73
+ if objective.get("last_evolution"):
74
+ lines.append(f" Last evolution: {objective['last_evolution']}")
75
+ return "\n".join(lines)
76
+
77
+
78
+ def handle_evolution_history(limit: int = 10) -> str:
79
+ """Show past evolution cycles and their outcomes.
80
+
81
+ Args:
82
+ limit: Number of entries to return (default 10)
83
+ """
84
+ history = get_evolution_history(limit)
85
+ if not history:
86
+ return "No evolution history."
87
+
88
+ lines = [f"EVOLUTION HISTORY ({len(history)} entries):"]
89
+ for h in history:
90
+ status_icon = {
91
+ "applied": "✓",
92
+ "rolled_back": "↺",
93
+ "blocked": "⛔",
94
+ "proposed": "?",
95
+ "pending_review": "…",
96
+ "accepted": "✓✓",
97
+ "rejected": "✗✗",
98
+ }.get(h["status"], "·")
99
+ lines.append(f" {status_icon} #{h['id']} [{h['classification']}] {h['dimension']}")
100
+ lines.append(f" {h['proposal'][:100]}")
101
+ if h.get("test_result"):
102
+ lines.append(f" Test: {h['test_result'][:80]}")
103
+ if h.get("impact"):
104
+ lines.append(f" Impact: {h['impact']:+d}")
105
+ return "\n".join(lines)
106
+
107
+
108
+ def handle_evolution_propose() -> str:
109
+ """Manually trigger an evolution analysis outside the weekly schedule.
110
+ This sets a flag that the Cortex wrapper reads on the next cycle.
111
+ """
112
+ import json
113
+ from pathlib import Path
114
+ nexo_home = Path(os.environ.get("NEXO_HOME", str(Path.home() / ".nexo")))
115
+ # Check brain/ (canonical) first, fall back to cortex/ (legacy)
116
+ obj_file = nexo_home / "brain" / "evolution-objective.json"
117
+ if not obj_file.exists():
118
+ obj_file = nexo_home / "cortex" / "evolution-objective.json"
119
+ if not obj_file.exists():
120
+ return "ERROR: evolution-objective.json not found. Run the installer or create one in ~/.nexo/brain/"
121
+ try:
122
+ obj = json.loads(obj_file.read_text())
123
+ if not obj.get("evolution_enabled", True):
124
+ return f"Evolution is DISABLED: {obj.get('disabled_reason', 'unknown')}"
125
+ obj["force_next_cycle"] = True
126
+ obj_file.write_text(json.dumps(obj, indent=2, ensure_ascii=False))
127
+ return "Evolution cycle queued. Will run on next Cortex cycle (within ~10 min)."
128
+ except Exception as e:
129
+ return f"ERROR: {e}"
130
+
131
+
132
+ def handle_evolution_approve(log_id: int, notes: str = '') -> str:
133
+ """Approve a pending Evolution proposal.
134
+
135
+ Args:
136
+ log_id: Evolution log entry ID to approve
137
+ notes: Optional notes from user
138
+ """
139
+ update_evolution_log_status(log_id, "accepted",
140
+ test_result=f"Approved by user. {notes}".strip())
141
+ return f"Proposal #{log_id} APPROVED. Will be applied in next Evolution cycle."
142
+
143
+
144
+ def handle_evolution_reject(log_id: int, reason: str = '') -> str:
145
+ """Reject a pending Evolution proposal.
146
+
147
+ Args:
148
+ log_id: Evolution log entry ID to reject
149
+ reason: Why this proposal was rejected
150
+ """
151
+ update_evolution_log_status(log_id, "rejected",
152
+ test_result=f"Rejected: {reason}" if reason else "Rejected by user")
153
+ return f"Proposal #{log_id} REJECTED. Reason: {reason or 'no reason given'}"
154
+
155
+
156
+ TOOLS = [
157
+ (handle_evolution_status, "nexo_evolution_status",
158
+ "Show current NEXO dimension scores (episodic memory, autonomy, proactivity, self-improvement, AGI)"),
159
+ (handle_evolution_history, "nexo_evolution_history",
160
+ "Show past evolution cycles, proposals, and their outcomes"),
161
+ (handle_evolution_propose, "nexo_evolution_propose",
162
+ "Manually trigger an evolution analysis outside weekly schedule"),
163
+ (handle_evolution_approve, "nexo_evolution_approve",
164
+ "Approve a pending Evolution proposal (user only)"),
165
+ (handle_evolution_reject, "nexo_evolution_reject",
166
+ "Reject a pending Evolution proposal with reason"),
167
+ ]
@@ -0,0 +1,142 @@
1
+ """Goal Engine v1 — explicit optimization profiles that Cortex can resolve and trace."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from db import (
8
+ get_db,
9
+ ensure_default_goal_profiles,
10
+ get_goal_profile,
11
+ list_goal_profiles,
12
+ resolve_goal_profile,
13
+ upsert_goal_profile,
14
+ )
15
+
16
+
17
+ def handle_goal_profile_set(
18
+ profile_id: str,
19
+ weights: str = "{}",
20
+ goal_labels: str = "[]",
21
+ profile_name: str = "",
22
+ description: str = "",
23
+ scope_type: str = "default",
24
+ scope_value: str = "",
25
+ status: str = "active",
26
+ source: str = "manual",
27
+ ) -> str:
28
+ """Create or update an explicit goal profile for Goal Engine v1."""
29
+ try:
30
+ profile = upsert_goal_profile(
31
+ profile_id=profile_id,
32
+ profile_name=profile_name,
33
+ description=description,
34
+ scope_type=scope_type,
35
+ scope_value=scope_value,
36
+ goal_labels=json.loads(goal_labels) if str(goal_labels).strip() else [],
37
+ weights=json.loads(weights) if str(weights).strip() else {},
38
+ status=status,
39
+ source=source,
40
+ )
41
+ except json.JSONDecodeError as exc:
42
+ return json.dumps({"ok": False, "error": f"Invalid JSON payload: {exc}"}, ensure_ascii=False, indent=2)
43
+ except ValueError as exc:
44
+ return json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False, indent=2)
45
+
46
+ return json.dumps({"ok": True, "profile": profile}, ensure_ascii=False, indent=2)
47
+
48
+
49
+ def handle_goal_profile_get(
50
+ profile_id: str = "",
51
+ area: str = "",
52
+ task_type: str = "",
53
+ goal_id: str = "",
54
+ ) -> str:
55
+ """Get one goal profile directly or resolve the active one for a context."""
56
+ if (profile_id or "").strip():
57
+ profile = get_goal_profile(profile_id)
58
+ if not profile:
59
+ return json.dumps({"ok": False, "error": f"Unknown goal profile: {profile_id}"}, ensure_ascii=False, indent=2)
60
+ return json.dumps({"ok": True, "profile": profile}, ensure_ascii=False, indent=2)
61
+ try:
62
+ profile = resolve_goal_profile(
63
+ area=area,
64
+ task_type=task_type,
65
+ goal_id=goal_id,
66
+ )
67
+ except ValueError as exc:
68
+ return json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False, indent=2)
69
+ return json.dumps({"ok": True, "profile": profile}, ensure_ascii=False, indent=2)
70
+
71
+
72
+ def handle_goal_profile_list(scope_type: str = "", status: str = "active", limit: int = 20) -> str:
73
+ """List Goal Engine profiles currently available in the runtime."""
74
+ profiles = list_goal_profiles(scope_type=scope_type, status=status, limit=limit)
75
+ return json.dumps(
76
+ {
77
+ "ok": True,
78
+ "count": len(profiles),
79
+ "profiles": profiles,
80
+ },
81
+ ensure_ascii=False,
82
+ indent=2,
83
+ )
84
+
85
+
86
+ def handle_goal_engine_status() -> str:
87
+ """Report the telemetry readiness of Goal Engine v1 and Cortex v2 inputs."""
88
+ ensure_default_goal_profiles()
89
+ conn = get_db()
90
+ outcomes_total = conn.execute("SELECT COUNT(*) FROM outcomes").fetchone()[0]
91
+ outcomes_met = conn.execute("SELECT COUNT(*) FROM outcomes WHERE status = 'met'").fetchone()[0]
92
+ outcomes_missed = conn.execute("SELECT COUNT(*) FROM outcomes WHERE status = 'missed'").fetchone()[0]
93
+ evaluations_total = conn.execute("SELECT COUNT(*) FROM cortex_evaluations").fetchone()[0]
94
+ overrides_total = conn.execute("SELECT COUNT(*) FROM cortex_evaluations WHERE selection_source = 'override'").fetchone()[0]
95
+ linked_total = conn.execute(
96
+ "SELECT COUNT(*) FROM cortex_evaluations WHERE linked_outcome_id IS NOT NULL"
97
+ ).fetchone()[0]
98
+ active_profiles = conn.execute("SELECT COUNT(*) FROM goal_profiles WHERE status = 'active'").fetchone()[0]
99
+ active_goals = conn.execute("SELECT COUNT(*) FROM workflow_goals WHERE status = 'active'").fetchone()[0]
100
+
101
+ readiness = {
102
+ "has_outcome_history": bool(outcomes_total >= 3),
103
+ "has_cortex_history": bool(evaluations_total >= 3),
104
+ "has_linked_decisions": bool(linked_total >= 1),
105
+ "has_active_profiles": bool(active_profiles >= 1),
106
+ "has_active_goals": bool(active_goals >= 1),
107
+ }
108
+ next_gap = []
109
+ if not readiness["has_outcome_history"]:
110
+ next_gap.append("Necesita acumular outcomes reales antes de optimizar por historico.")
111
+ if not readiness["has_cortex_history"]:
112
+ next_gap.append("Necesita acumular evaluaciones reales del cortex antes de medir Decision Cortex v2.")
113
+ if not readiness["has_linked_decisions"]:
114
+ next_gap.append("Necesita decisiones de impacto enlazadas a outcome para cerrar el loop.")
115
+
116
+ return json.dumps(
117
+ {
118
+ "ok": True,
119
+ "telemetry": {
120
+ "outcomes_total": outcomes_total,
121
+ "outcomes_met": outcomes_met,
122
+ "outcomes_missed": outcomes_missed,
123
+ "cortex_evaluations_total": evaluations_total,
124
+ "cortex_overrides_total": overrides_total,
125
+ "cortex_linked_outcomes_total": linked_total,
126
+ "active_goal_profiles": active_profiles,
127
+ "active_workflow_goals": active_goals,
128
+ },
129
+ "readiness": readiness,
130
+ "next_gaps": next_gap,
131
+ },
132
+ ensure_ascii=False,
133
+ indent=2,
134
+ )
135
+
136
+
137
+ TOOLS = [
138
+ (handle_goal_profile_set, "nexo_goal_profile_set", "Create or update a Goal Engine profile with explicit weights and labels."),
139
+ (handle_goal_profile_get, "nexo_goal_profile_get", "Get or resolve the active Goal Engine profile for a context, area, task type, or workflow goal."),
140
+ (handle_goal_profile_list, "nexo_goal_profile_list", "List Goal Engine profiles currently available in the runtime."),
141
+ (handle_goal_engine_status, "nexo_goal_engine_status", "Report Goal Engine telemetry readiness: outcomes, cortex history, linked decisions, and active profiles."),
142
+ ]