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,229 @@
1
+ """Menu generator — operations center."""
2
+
3
+ from datetime import datetime, timedelta
4
+ import json
5
+ import os
6
+ import subprocess
7
+ from user_context import get_context as _get_ctx
8
+ import sys
9
+ from pathlib import Path
10
+ from tools_sessions import handle_status
11
+ from tools_reminders import handle_reminders
12
+ from db import get_db
13
+
14
+
15
+ def _get_date_str() -> str:
16
+ """Get formatted date in Madrid timezone."""
17
+ try:
18
+ result = subprocess.run(
19
+ ["date", "+%A %d %B %Y, %H:%M"],
20
+ capture_output=True, text=True,
21
+ env={"PATH": "/usr/bin:/bin"}
22
+ )
23
+ return result.stdout.strip()
24
+ except Exception:
25
+ return datetime.now().strftime("%Y-%m-%d %H:%M")
26
+
27
+
28
+ MENU_ITEMS = [
29
+ ("Projects", [
30
+ ("1", "Projects - Review project status"),
31
+ ("9", "Claude Agent VPS - Review autonomous changes"),
32
+ ]),
33
+ ("Advertising", [
34
+ ("7", "Google Ads - Manage campaigns"),
35
+ ("7b", "Meta Ads - Manage Facebook/Instagram campaigns"),
36
+ ("7c", "Ads Tracking - Combined Google+Meta review"),
37
+ ]),
38
+ ("Shopify", [
39
+ ("4", "Shopify Theme Sync - Sync theme"),
40
+ ("5", "Shopify Scripts - Run periodic scripts"),
41
+ ("6", "Change Shopify Promotion"),
42
+ ]),
43
+ ("Server & Infrastructure", [
44
+ ("2", "Server - Health check your-server.example.com"),
45
+ ("3", "WhatsApp Logs - Review logs your-whatsapp-account"),
46
+ ("11", "File Tracker - PHP file report"),
47
+ ("12", "Google Cloud - Spend, usage and GCP status"),
48
+ ]),
49
+ ("Communication & Monitoring", [
50
+ ("8", "Recovery Optimizer - Weekly AI analysis (MONDAY)"),
51
+ ("10", "Recovery Monitor - Email/WA recovery status (24h)"),
52
+ ("13", "Review Monitor - Email/WA review status"),
53
+ ("14", "WhatsApp Full Analysis - Global statistics"),
54
+ ("15", "Google Analytics - Review web analytics"),
55
+ ("16", "Email Review - Check inboxes and spam"),
56
+ ]),
57
+ ("Reports & SEO", [
58
+ ("17", "Search Console Audit (every 2 weeks)"),
59
+ ("18", "Sitemap resubmission (every 30 days)"),
60
+ ("19", "SEO meta verification"),
61
+ ("20", "Weekly Email Report (Sundays)"),
62
+ ]),
63
+ ]
64
+
65
+
66
+ def _get_dashboard_alerts() -> list[dict]:
67
+ """Run proactive dashboard and return alerts."""
68
+ try:
69
+ nexo_home = Path(os.environ.get("NEXO_HOME", str(Path.home() / ".nexo")))
70
+ script = nexo_home / "scripts" / "nexo-proactive-dashboard.py"
71
+ if not script.exists():
72
+ return []
73
+ result = subprocess.run(
74
+ [sys.executable, str(script), "--json"],
75
+ capture_output=True, text=True, timeout=10
76
+ )
77
+ if result.stdout.strip():
78
+ return json.loads(result.stdout)
79
+ except Exception:
80
+ pass
81
+ return []
82
+
83
+
84
+ def _get_memory_review_summary() -> dict:
85
+ """Return counts of due memory reviews."""
86
+ try:
87
+ conn = get_db()
88
+ now_epoch = datetime.now().timestamp()
89
+ now_iso = datetime.now().isoformat(timespec="seconds")
90
+ due_learnings = conn.execute(
91
+ "SELECT COUNT(*) FROM learnings WHERE review_due_at IS NOT NULL AND status != 'superseded' AND review_due_at <= ?",
92
+ (now_epoch,)
93
+ ).fetchone()[0]
94
+ due_decisions = conn.execute(
95
+ "SELECT COUNT(*) FROM decisions WHERE review_due_at IS NOT NULL AND status != 'reviewed' AND review_due_at <= ?",
96
+ (now_iso,)
97
+ ).fetchone()[0]
98
+ return {
99
+ "learnings": due_learnings,
100
+ "decisions": due_decisions,
101
+ "total": due_learnings + due_decisions,
102
+ }
103
+ except Exception:
104
+ return {"learnings": 0, "decisions": 0, "total": 0}
105
+
106
+
107
+ def handle_menu() -> str:
108
+ """Generate the full operations menu with alerts."""
109
+ date_str = _get_date_str()
110
+ W = 56 # inner width
111
+
112
+ lines = []
113
+ lines.append("╔" + "═" * W + "╗")
114
+ lines.append("║" + f"{_get_ctx().assistant_name} — OPERATIONS CENTER".center(W) + "║")
115
+ lines.append("║" + date_str.center(W) + "║")
116
+ lines.append("╠" + "═" * W + "╣")
117
+
118
+ # Proactive dashboard alerts
119
+ dashboard_alerts = _get_dashboard_alerts()
120
+ memory_reviews = _get_memory_review_summary()
121
+ due = handle_reminders("due")
122
+ has_alerts = dashboard_alerts or memory_reviews["total"] > 0 or (due and "No reminders" not in due)
123
+
124
+ if has_alerts:
125
+ lines.append("║" + " PROACTIVE ALERTS".ljust(W) + "║")
126
+ lines.append("╠" + "═" * W + "╣")
127
+
128
+ if dashboard_alerts:
129
+ for alert in dashboard_alerts[:10]: # Top 10
130
+ sev = alert.get("severity", "low")
131
+ icon = {"high": "!!!", "medium": " ! ", "low": " . "}.get(sev, " . ")
132
+ text = alert.get("title", "")[:W - 8]
133
+ lines.append("║" + f" {icon} {text}".ljust(W) + "║")
134
+ if len(dashboard_alerts) > 10:
135
+ more = len(dashboard_alerts) - 10
136
+ lines.append("║" + f" ... and {more} more alerts".ljust(W) + "║")
137
+
138
+ if memory_reviews["total"] > 0:
139
+ text = (
140
+ f"MEMORY: {memory_reviews['total']} pending reviews "
141
+ f"({memory_reviews['decisions']} decisions, {memory_reviews['learnings']} learnings)"
142
+ )[:W - 4]
143
+ lines.append("║" + f" ! {text}".ljust(W) + "║")
144
+
145
+ if due and "No reminders" not in due:
146
+ for reminder_line in due.split("\n"):
147
+ if reminder_line.strip():
148
+ truncated = reminder_line[:W - 2]
149
+ lines.append("║" + f" {truncated}".ljust(W) + "║")
150
+
151
+ lines.append("╠" + "═" * W + "╣")
152
+
153
+ # Menu categories
154
+ for category, items in MENU_ITEMS:
155
+ lines.append("║" + f" {category.upper()}".ljust(W) + "║")
156
+ lines.append("║" + "─" * W + "║")
157
+ for num, desc in items:
158
+ entry = f" {num:>3}. {desc}"
159
+ lines.append("║" + entry.ljust(W) + "║")
160
+ lines.append("╠" + "═" * W + "╣")
161
+
162
+ # Backlog: ideas, future projects, undated or distant tasks
163
+ try:
164
+ conn = get_db()
165
+ cutoff = (datetime.now() + timedelta(days=7)).strftime("%Y-%m-%d")
166
+ # Reminders without date (backlog/ideas)
167
+ no_date = conn.execute(
168
+ "SELECT id, description, category FROM reminders WHERE status LIKE 'PENDING%' AND (date IS NULL OR date='') ORDER BY category, id"
169
+ ).fetchall()
170
+ # Reminders with date > 7 days ahead (future)
171
+ future = conn.execute(
172
+ "SELECT id, description, date, category FROM reminders WHERE status LIKE 'PENDING%' AND date > ? ORDER BY date",
173
+ (cutoff,)
174
+ ).fetchall()
175
+ # Followups without date
176
+ nf_no_date = conn.execute(
177
+ "SELECT id, description FROM followups WHERE status NOT LIKE 'COMPLETED%' AND status NOT IN ('DELETED','archived','blocked','waiting') AND (date IS NULL OR date='') ORDER BY id"
178
+ ).fetchall()
179
+
180
+ if no_date or future or nf_no_date:
181
+ lines.append("║" + " BACKLOG / IDEAS / FUTURE".ljust(W) + "║")
182
+ lines.append("║" + "─" * W + "║")
183
+
184
+ if no_date:
185
+ by_cat = {}
186
+ for r in no_date:
187
+ cat = (r["category"] or "general").capitalize()
188
+ by_cat.setdefault(cat, []).append(r)
189
+ for cat, items in by_cat.items():
190
+ lines.append("║" + f" [{cat}]".ljust(W) + "║")
191
+ for r in items:
192
+ short = r["description"][:W - 10]
193
+ lines.append("║" + f" {r['id']}: {short}".ljust(W) + "║")
194
+
195
+ if future:
196
+ lines.append("║" + f" [Scheduled]".ljust(W) + "║")
197
+ for r in future:
198
+ short = r["description"][:W - 18]
199
+ lines.append("║" + f" {r['id']} ({r['date']}): {short}".ljust(W) + "║")
200
+
201
+ if nf_no_date:
202
+ lines.append("║" + f" [Pending followups]".ljust(W) + "║")
203
+ for r in nf_no_date:
204
+ short = r["description"][:W - 12]
205
+ lines.append("║" + f" {r['id']}: {short}".ljust(W) + "║")
206
+
207
+ lines.append("╠" + "═" * W + "╣")
208
+ except Exception as e:
209
+ lines.append("║" + f" ⚠ Error backlog: {e}".ljust(W) + "║")
210
+ lines.append("╠" + "═" * W + "╣")
211
+
212
+ # Active sessions
213
+ sessions = handle_status()
214
+ if "No sessions" not in sessions:
215
+ lines.append("║" + " ACTIVE SESSIONS".ljust(W) + "║")
216
+ lines.append("║" + "─" * W + "║")
217
+ for s_line in sessions.split("\n"):
218
+ if s_line.strip() and "ACTIVE SESSIONS" not in s_line:
219
+ truncated = s_line[:W - 2]
220
+ lines.append("║" + f" {truncated}".ljust(W) + "║")
221
+ lines.append("╠" + "═" * W + "╣")
222
+
223
+ # Replace last ╠═╣ with bottom border
224
+ if lines[-1].startswith("╠"):
225
+ lines[-1] = "╚" + "═" * W + "╝"
226
+ else:
227
+ lines.append("╚" + "═" * W + "╝")
228
+
229
+ return "\n".join(lines)
@@ -0,0 +1,88 @@
1
+ """Reminders and followups reader — reads from SQLite database."""
2
+
3
+ from db import get_reminders, get_followups
4
+ from datetime import date
5
+
6
+
7
+ def _is_due(date_str: str) -> bool:
8
+ """Check if a date string is today or in the past."""
9
+ if not date_str:
10
+ return False
11
+ try:
12
+ d = date.fromisoformat(date_str.strip()[:10])
13
+ return d <= date.today()
14
+ except (ValueError, IndexError):
15
+ return False
16
+
17
+
18
+ def handle_reminders(filter_type: str = "due") -> str:
19
+ """Read reminders and followups from SQLite, return relevant ones.
20
+
21
+ Args:
22
+ filter_type: 'due', 'all', 'followups', 'completed', 'deleted', 'history', 'any'
23
+ """
24
+ parts = []
25
+
26
+ if filter_type in ("due", "all", "completed", "deleted", "history", "any"):
27
+ r = _format_reminders(filter_type)
28
+ if r:
29
+ parts.append(r)
30
+
31
+ if filter_type in ("due", "all", "followups", "completed", "deleted", "history", "any"):
32
+ f = _format_followups(filter_type)
33
+ if f:
34
+ parts.append(f)
35
+
36
+ result = "\n\n".join(parts)
37
+ return result if result else "No pending reminders."
38
+
39
+
40
+ def _format_reminders(filter_type: str) -> str:
41
+ """Format reminders from database."""
42
+ rows = get_reminders(filter_type)
43
+ if not rows:
44
+ return ""
45
+
46
+ lines = ["REMINDERS:"]
47
+ for r in rows:
48
+ rid = r.get("id", "?")
49
+ fecha = r.get("date") or ""
50
+ desc = r.get("description", "")
51
+ status = r.get("status", "")
52
+ desc = desc.replace("**", "")
53
+ due_marker = " [DUE]" if _is_due(fecha) else ""
54
+ fecha_display = f"({fecha})" if fecha else "(—)"
55
+ status_tag = f" [{status}]" if status and status != "PENDING" else ""
56
+ lines.append(f" {rid} {fecha_display}{due_marker}{status_tag} — {desc[:120]}")
57
+ if "RECURRENTE" in status.upper():
58
+ lines.append(f" Status: {status}")
59
+
60
+ return "\n".join(lines)
61
+
62
+
63
+ def _format_followups(filter_type: str) -> str:
64
+ """Format followups from database."""
65
+ rows = get_followups(filter_type)
66
+ if not rows:
67
+ return ""
68
+
69
+ lines = ["FOLLOWUPS NEXO:"]
70
+ for r in rows:
71
+ nfid = r.get("id", "?")
72
+ fecha = r.get("date") or ""
73
+ desc = r.get("description", "")
74
+ desc = desc.replace("**", "")
75
+ due_marker = " [DUE]" if _is_due(fecha) else ""
76
+ fecha_display = f"({fecha})" if fecha else "(—)"
77
+ rec = r.get("recurrence") or ""
78
+ rec_tag = f" [♻️ {rec}]" if rec else ""
79
+ pri = r.get("priority") or "medium"
80
+ pri_icon = {"critical": "🔴", "high": "🟠", "medium": "", "low": "⚪"}.get(pri, "")
81
+ pri_tag = f" {pri_icon}" if pri_icon else ""
82
+ impact = float(r.get("impact_score") or 0)
83
+ impact_tag = f" [impact {impact:.1f}]" if impact > 0 else ""
84
+ status = r.get("status") or ""
85
+ status_tag = f" [{status}]" if status and status != "PENDING" else ""
86
+ lines.append(f" {nfid} {fecha_display}{due_marker}{pri_tag}{impact_tag}{rec_tag}{status_tag} — {desc[:120]}")
87
+
88
+ return "\n".join(lines)
@@ -0,0 +1,363 @@
1
+ """CRUD handlers for reminders and followups — operates on SQLite via db.py."""
2
+
3
+ from db import (
4
+ create_reminder, update_reminder, complete_reminder, delete_reminder,
5
+ restore_reminder, add_reminder_note, get_reminder,
6
+ create_followup, update_followup, complete_followup, delete_followup,
7
+ restore_followup, add_followup_note, get_followup,
8
+ validate_item_read_token,
9
+ find_decisions_by_context_ref, update_decision_outcome,
10
+ set_linked_outcomes_met,
11
+ )
12
+
13
+
14
+ def _require_item_read(item_type: str, item_id: str, read_token: str) -> str | None:
15
+ ok, message = validate_item_read_token(read_token, item_type, item_id)
16
+ if ok:
17
+ return None
18
+ prefix = "followup" if item_type == "followup" else "reminder"
19
+ return f"ERROR: {message} Use nexo_{prefix}_get(id='{item_id}') first."
20
+
21
+
22
+ def _history_lines(history: list[dict]) -> list[str]:
23
+ if not history:
24
+ return ["- (no history)"]
25
+ lines: list[str] = []
26
+ for event in history:
27
+ created_at = event.get("created_at") or "?"
28
+ event_type = event.get("event_type") or "event"
29
+ actor = event.get("actor") or "system"
30
+ note = (event.get("note") or "").strip()
31
+ suffix = f" — {note}" if note else ""
32
+ lines.append(f"- {created_at} [{event_type}] ({actor}){suffix}")
33
+ return lines
34
+
35
+
36
+ def _format_reminder_payload(reminder: dict) -> str:
37
+ lines = [
38
+ f"REMINDER {reminder['id']}",
39
+ f"Description: {reminder.get('description') or ''}",
40
+ f"Date: {reminder.get('date') or '—'}",
41
+ f"Status: {reminder.get('status') or '—'}",
42
+ f"Category: {reminder.get('category') or 'general'}",
43
+ ]
44
+ history_rules = reminder.get("history_rules") or []
45
+ if history_rules:
46
+ lines.append("Usage rules:")
47
+ lines.extend(f"- {rule}" for rule in history_rules)
48
+ lines.append("History:")
49
+ lines.extend(_history_lines(reminder.get("history") or []))
50
+ if reminder.get("read_token"):
51
+ lines.append(f"READ_TOKEN: {reminder['read_token']}")
52
+ return "\n".join(lines)
53
+
54
+
55
+ def _format_followup_payload(followup: dict) -> str:
56
+ lines = [
57
+ f"FOLLOWUP {followup['id']}",
58
+ f"Description: {followup.get('description') or ''}",
59
+ f"Date: {followup.get('date') or '—'}",
60
+ f"Status: {followup.get('status') or '—'}",
61
+ f"Verification: {followup.get('verification') or '—'}",
62
+ f"Reasoning: {followup.get('reasoning') or '—'}",
63
+ f"Recurrence: {followup.get('recurrence') or '—'}",
64
+ f"Priority: {followup.get('priority') or 'medium'}",
65
+ ]
66
+ history_rules = followup.get("history_rules") or []
67
+ if history_rules:
68
+ lines.append("Usage rules:")
69
+ lines.extend(f"- {rule}" for rule in history_rules)
70
+ lines.append("History:")
71
+ lines.extend(_history_lines(followup.get("history") or []))
72
+ if followup.get("read_token"):
73
+ lines.append(f"READ_TOKEN: {followup['read_token']}")
74
+ return "\n".join(lines)
75
+
76
+
77
+ # ── Reminders ──────────────────────────────────────────────────────────────────
78
+
79
+ def handle_reminder_create(id: str, description: str, date: str = '', category: str = 'general') -> str:
80
+ """Create a new reminder. id must start with 'R'."""
81
+ if not id.startswith('R'):
82
+ return f"ERROR: Reminder ID must start with 'R' (received: '{id}')."
83
+
84
+ result = create_reminder(id=id, description=description, date=date or None, category=category)
85
+ if not result or "error" in result:
86
+ error_msg = result.get("error", "unknown") if isinstance(result, dict) else "unknown"
87
+ return f"ERROR: {error_msg}"
88
+
89
+ date_str = date if date else 'no date'
90
+ return f"Reminder created. Date: {date_str}. Category: {category}."
91
+
92
+
93
+ def handle_reminder_get(id: str) -> str:
94
+ """Read a reminder with history and return a read token for safe mutations."""
95
+ result = get_reminder(id=id, include_history=True)
96
+ if not result:
97
+ return f"ERROR: Reminder {id} not found."
98
+ return _format_reminder_payload(result)
99
+
100
+
101
+ def handle_reminder_update(
102
+ id: str,
103
+ description: str = '',
104
+ date: str = '',
105
+ status: str = '',
106
+ category: str = '',
107
+ read_token: str = '',
108
+ ) -> str:
109
+ """Update one or more fields of an existing reminder."""
110
+ error = _require_item_read("reminder", id, read_token)
111
+ if error:
112
+ return error
113
+
114
+ fields: dict = {}
115
+ if description:
116
+ fields['description'] = description
117
+ if date:
118
+ fields['date'] = date
119
+ if status:
120
+ fields['status'] = status
121
+ if category:
122
+ fields['category'] = category
123
+
124
+ if not fields:
125
+ return f"ERROR: No fields specified to update for {id}."
126
+
127
+ result = update_reminder(id=id, **fields)
128
+ if not result or "error" in result:
129
+ error_msg = result.get("error", f"Reminder {id} not found.") if isinstance(result, dict) else f"Reminder {id} not found."
130
+ return f"ERROR: {error_msg}"
131
+
132
+ changed = ', '.join(fields.keys())
133
+ return f"Reminder {id} updated: {changed}."
134
+
135
+
136
+ def handle_reminder_complete(id: str) -> str:
137
+ """Mark a reminder as completed."""
138
+ result = complete_reminder(id=id)
139
+ if not result or "error" in result:
140
+ return f"ERROR: Reminder {id} not found."
141
+
142
+ return f"Reminder {id} marked COMPLETED."
143
+
144
+
145
+ def handle_reminder_note(id: str, note: str, read_token: str = '', actor: str = 'nexo') -> str:
146
+ """Append a note to reminder history."""
147
+ if not note.strip():
148
+ return "ERROR: note is required."
149
+ error = _require_item_read("reminder", id, read_token)
150
+ if error:
151
+ return error
152
+ result = add_reminder_note(id=id, note=note.strip(), actor=actor or "nexo")
153
+ if not result or "error" in result:
154
+ error_msg = result.get("error", f"Reminder {id} not found.") if isinstance(result, dict) else f"Reminder {id} not found."
155
+ return f"ERROR: {error_msg}"
156
+ return f"Reminder {id} note added."
157
+
158
+
159
+ def handle_reminder_restore(id: str, read_token: str = '') -> str:
160
+ """Restore a soft-deleted reminder."""
161
+ error = _require_item_read("reminder", id, read_token)
162
+ if error:
163
+ return error
164
+ result = restore_reminder(id=id)
165
+ if not result or "error" in result:
166
+ error_msg = result.get("error", f"Reminder {id} not found.") if isinstance(result, dict) else f"Reminder {id} not found."
167
+ return f"ERROR: {error_msg}"
168
+ return f"Reminder {id} restored to PENDING."
169
+
170
+
171
+ def handle_reminder_delete(id: str, read_token: str = '') -> str:
172
+ """Soft-delete a reminder."""
173
+ error = _require_item_read("reminder", id, read_token)
174
+ if error:
175
+ return error
176
+ result = delete_reminder(id=id)
177
+ if not result:
178
+ return f"ERROR: Reminder {id} not found."
179
+
180
+ return f"Reminder {id} soft-deleted."
181
+
182
+
183
+ # ── Followups ──────────────────────────────────────────────────────────────────
184
+
185
+ def handle_followup_create(
186
+ id: str,
187
+ description: str,
188
+ date: str = '',
189
+ verification: str = '',
190
+ reasoning: str = '',
191
+ recurrence: str = '',
192
+ priority: str = 'medium',
193
+ ) -> str:
194
+ """Create a new NEXO followup. id must start with 'NF'.
195
+
196
+ Args:
197
+ id: Unique ID starting with 'NF'
198
+ description: What to verify/do
199
+ date: Target date YYYY-MM-DD (optional)
200
+ verification: How to verify completion (optional)
201
+ reasoning: WHY this followup exists — what decision/context led to it
202
+ recurrence: Recurrence pattern (optional). Formats: 'weekly:monday', 'monthly:1', 'quarterly'.
203
+ When completed, auto-creates the next occurrence.
204
+ """
205
+ if not id.startswith('NF'):
206
+ return f"ERROR: Followup ID must start with 'NF' (received: '{id}')."
207
+
208
+ result = create_followup(
209
+ id=id,
210
+ description=description,
211
+ date=date or None,
212
+ verification=verification,
213
+ reasoning=reasoning,
214
+ recurrence=recurrence or None,
215
+ priority=priority or "medium",
216
+ )
217
+ if not result or "error" in result:
218
+ error_msg = result.get("error", "unknown") if isinstance(result, dict) else "unknown"
219
+ return f"ERROR: {error_msg}"
220
+
221
+ date_str = date if date else 'no date'
222
+ rec_str = f" Recurrence: {recurrence}." if recurrence else ""
223
+ priority_str = f" Priority: {priority or 'medium'}."
224
+ warning = result.get("warning", "")
225
+ warn_str = f"\n{warning}" if warning else ""
226
+ return f"Followup created. Date: {date_str}.{priority_str}{rec_str}{warn_str}"
227
+
228
+
229
+ def handle_followup_get(id: str) -> str:
230
+ """Read a followup with history and return a read token for safe mutations."""
231
+ result = get_followup(id=id, include_history=True)
232
+ if not result:
233
+ return f"ERROR: Followup {id} not found."
234
+ return _format_followup_payload(result)
235
+
236
+
237
+ def handle_followup_update(
238
+ id: str,
239
+ description: str = '',
240
+ date: str = '',
241
+ verification: str = '',
242
+ status: str = '',
243
+ priority: str = '',
244
+ read_token: str = '',
245
+ ) -> str:
246
+ """Update one or more fields of an existing followup."""
247
+ error = _require_item_read("followup", id, read_token)
248
+ if error:
249
+ return error
250
+
251
+ fields: dict = {}
252
+ if description:
253
+ fields['description'] = description
254
+ if date:
255
+ fields['date'] = date
256
+ if verification:
257
+ fields['verification'] = verification
258
+ if status:
259
+ fields['status'] = status
260
+ if priority:
261
+ fields['priority'] = priority
262
+
263
+ if not fields:
264
+ return f"ERROR: No fields specified to update for {id}."
265
+
266
+ result = update_followup(id=id, **fields)
267
+ if not result or "error" in result:
268
+ error_msg = result.get("error", f"Followup {id} not found.") if isinstance(result, dict) else f"Followup {id} not found."
269
+ return f"ERROR: {error_msg}"
270
+
271
+ changed = ', '.join(fields.keys())
272
+ return f"Followup {id} updated: {changed}."
273
+
274
+
275
+ def handle_followup_complete(id: str, result: str = '') -> str:
276
+ """Mark a followup as completed, optionally recording the result.
277
+ Also auto-updates any decision that references this followup in context_ref.
278
+ If the followup is recurring, auto-creates the next occurrence."""
279
+ from db import get_db
280
+ # Check recurrence before completing (complete may rename the ID)
281
+ conn = get_db()
282
+ row = conn.execute("SELECT recurrence FROM followups WHERE id = ?", (id,)).fetchone()
283
+ has_recurrence = row and row["recurrence"]
284
+
285
+ db_result = complete_followup(id=id, result=result)
286
+ if not db_result or "error" in db_result:
287
+ return f"ERROR: Followup {id} not found."
288
+
289
+ # Emit trust event: task completed successfully
290
+ try:
291
+ from cognitive._trust import adjust_trust
292
+ adjust_trust("task_completed", f"Followup {id} completed")
293
+ except Exception:
294
+ pass
295
+
296
+ # Auto-link: find decisions whose context_ref matches this followup ID
297
+ msg = f"Followup {id} marked COMPLETED."
298
+ if has_recurrence:
299
+ # The new one was auto-created by complete_followup
300
+ new_row = conn.execute("SELECT date FROM followups WHERE id = ?", (id,)).fetchone()
301
+ if new_row:
302
+ msg += f" ♻️ Next auto-created for {new_row['date']}."
303
+ linked_decisions = find_decisions_by_context_ref(id)
304
+ if linked_decisions:
305
+ outcome_text = result if result else f"Followup {id} completed"
306
+ for dec in linked_decisions:
307
+ update_decision_outcome(dec['id'], outcome_text)
308
+ dec_ids = ', '.join(f"#{d['id']}" for d in linked_decisions)
309
+ msg += f" Decision(s) {dec_ids} updated with automatic outcome."
310
+
311
+ try:
312
+ linked_outcomes = set_linked_outcomes_met(
313
+ "followup",
314
+ id,
315
+ metric_source="followup_status",
316
+ actual_value=1.0,
317
+ actual_value_text=result if result else f"Followup {id} completed",
318
+ note="Linked followup completed.",
319
+ )
320
+ except Exception:
321
+ linked_outcomes = []
322
+ if linked_outcomes:
323
+ msg += f" Linked outcomes met: {len(linked_outcomes)}."
324
+
325
+ return msg
326
+
327
+
328
+ def handle_followup_note(id: str, note: str, read_token: str = '', actor: str = 'nexo') -> str:
329
+ """Append a note to followup history."""
330
+ if not note.strip():
331
+ return "ERROR: note is required."
332
+ error = _require_item_read("followup", id, read_token)
333
+ if error:
334
+ return error
335
+ result = add_followup_note(id=id, note=note.strip(), actor=actor or "nexo")
336
+ if not result or "error" in result:
337
+ error_msg = result.get("error", f"Followup {id} not found.") if isinstance(result, dict) else f"Followup {id} not found."
338
+ return f"ERROR: {error_msg}"
339
+ return f"Followup {id} note added."
340
+
341
+
342
+ def handle_followup_restore(id: str, read_token: str = '') -> str:
343
+ """Restore a soft-deleted followup."""
344
+ error = _require_item_read("followup", id, read_token)
345
+ if error:
346
+ return error
347
+ result = restore_followup(id=id)
348
+ if not result or "error" in result:
349
+ error_msg = result.get("error", f"Followup {id} not found.") if isinstance(result, dict) else f"Followup {id} not found."
350
+ return f"ERROR: {error_msg}"
351
+ return f"Followup {id} restored to PENDING."
352
+
353
+
354
+ def handle_followup_delete(id: str, read_token: str = '') -> str:
355
+ """Soft-delete a followup."""
356
+ error = _require_item_read("followup", id, read_token)
357
+ if error:
358
+ return error
359
+ result = delete_followup(id=id)
360
+ if not result:
361
+ return f"ERROR: Followup {id} not found."
362
+
363
+ return f"Followup {id} soft-deleted."