nexo-brain 5.3.26 → 5.3.28

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 (212) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/package.json +1 -1
  3. package/src/hook_guardrails.py +44 -0
  4. package/src/server.py +3 -0
  5. package/src/tools_sessions.py +6 -1
  6. package/src/dashboard/static/favicon 2.svg +0 -32
  7. package/src/dashboard/static/nexo-logo 2.png +0 -0
  8. package/src/dashboard/static/nexo-logo 2.svg +0 -40
  9. package/src/dashboard/static/style 2.css +0 -2458
  10. package/src/dashboard/templates/adaptive 2.html +0 -118
  11. package/src/dashboard/templates/artifacts 2.html +0 -133
  12. package/src/dashboard/templates/backups 2.html +0 -136
  13. package/src/dashboard/templates/base 2.html +0 -417
  14. package/src/dashboard/templates/calendar 2.html +0 -591
  15. package/src/dashboard/templates/chat 2.html +0 -356
  16. package/src/dashboard/templates/claims 2.html +0 -259
  17. package/src/dashboard/templates/cortex 2.html +0 -321
  18. package/src/dashboard/templates/credentials 2.html +0 -128
  19. package/src/dashboard/templates/crons 2.html +0 -370
  20. package/src/dashboard/templates/dashboard 2.html +0 -494
  21. package/src/dashboard/templates/dreams 2.html +0 -252
  22. package/src/dashboard/templates/email 2.html +0 -160
  23. package/src/dashboard/templates/evolution 2.html +0 -189
  24. package/src/dashboard/templates/feed 2.html +0 -249
  25. package/src/dashboard/templates/followup_health 2.html +0 -170
  26. package/src/dashboard/templates/graph 2.html +0 -201
  27. package/src/dashboard/templates/guard 2.html +0 -259
  28. package/src/dashboard/templates/inbox 2.html +0 -251
  29. package/src/dashboard/templates/memory 2.html +0 -420
  30. package/src/dashboard/templates/operations 2.html +0 -608
  31. package/src/dashboard/templates/plugins 2.html +0 -185
  32. package/src/dashboard/templates/protocol 2.html +0 -199
  33. package/src/dashboard/templates/rules 2.html +0 -246
  34. package/src/dashboard/templates/sentiment 2.html +0 -247
  35. package/src/dashboard/templates/sessions 2.html +0 -218
  36. package/src/dashboard/templates/skills 2.html +0 -329
  37. package/src/dashboard/templates/somatic 2.html +0 -73
  38. package/src/dashboard/templates/triggers 2.html +0 -133
  39. package/src/dashboard/templates/trust 2.html +0 -360
  40. package/src/db/__init__ 2.py +0 -259
  41. package/src/db/_core 2.py +0 -437
  42. package/src/db/_credentials 2.py +0 -124
  43. package/src/db/_episodic 2.py +0 -762
  44. package/src/db/_evolution 2.py +0 -54
  45. package/src/db/_fts 2.py +0 -406
  46. package/src/db/_goal_profiles 2.py +0 -376
  47. package/src/db/_hot_context 2.py +0 -660
  48. package/src/db/_outcomes 2.py +0 -800
  49. package/src/db/_personal_scripts 2.py +0 -582
  50. package/src/db/_sessions 2.py +0 -330
  51. package/src/db/_tasks 2.py +0 -91
  52. package/src/db/_watchers 2.py +0 -173
  53. package/src/doctor/formatters 2.py +0 -52
  54. package/src/doctor/models 2.py +0 -69
  55. package/src/doctor/planes 2.py +0 -87
  56. package/src/doctor/providers/__init__ 2.py +0 -1
  57. package/src/doctor/providers/deep 2.py +0 -367
  58. package/src/evolution_cycle 2.py +0 -519
  59. package/src/hooks/auto_capture 2.py +0 -208
  60. package/src/hooks/caffeinate-guard 2.sh +0 -8
  61. package/src/hooks/capture-session 2.sh +0 -21
  62. package/src/hooks/capture-tool-logs 2.sh +0 -158
  63. package/src/hooks/daily-briefing-check 2.sh +0 -33
  64. package/src/hooks/heartbeat-enforcement 2.py +0 -90
  65. package/src/hooks/heartbeat-posttool 2.sh +0 -18
  66. package/src/hooks/inbox-hook 2.sh +0 -76
  67. package/src/hooks/post-compact 2.sh +0 -152
  68. package/src/hooks/pre-compact 2.sh +0 -169
  69. package/src/hooks/protocol-guardrail 2.sh +0 -10
  70. package/src/hooks/protocol-pretool-guardrail 2.sh +0 -9
  71. package/src/hooks/session-stop 2.sh +0 -52
  72. package/src/kg_populate 2.py +0 -292
  73. package/src/maintenance 2.py +0 -53
  74. package/src/memory_backends 2.py +0 -71
  75. package/src/migrate_embeddings 2.py +0 -124
  76. package/src/nexo_sdk 2.py +0 -103
  77. package/src/observability 2.py +0 -199
  78. package/src/plugin_loader 2.py +0 -217
  79. package/src/plugins/__init__ 2.py +0 -0
  80. package/src/plugins/artifact_registry 2.py +0 -450
  81. package/src/plugins/backup 2.py +0 -127
  82. package/src/plugins/claims_tools 2.py +0 -119
  83. package/src/plugins/cognitive_memory 2.py +0 -609
  84. package/src/plugins/core_rules 2.py +0 -252
  85. package/src/plugins/cortex 2.py +0 -1155
  86. package/src/plugins/entities 2.py +0 -67
  87. package/src/plugins/episodic_memory 2.py +0 -560
  88. package/src/plugins/evolution 2.py +0 -167
  89. package/src/plugins/goal_engine 2.py +0 -142
  90. package/src/plugins/guard 2.py +0 -862
  91. package/src/plugins/impact 2.py +0 -29
  92. package/src/plugins/knowledge_graph_tools 2.py +0 -137
  93. package/src/plugins/media_memory_tools 2.py +0 -98
  94. package/src/plugins/memory_export 2.py +0 -196
  95. package/src/plugins/outcomes 2.py +0 -130
  96. package/src/plugins/personal_scripts 2.py +0 -117
  97. package/src/plugins/preferences 2.py +0 -47
  98. package/src/plugins/protocol 2.py +0 -1449
  99. package/src/plugins/simple_api 2.py +0 -106
  100. package/src/plugins/skills 2.py +0 -341
  101. package/src/plugins/state_watchers 2.py +0 -79
  102. package/src/plugins/update 2.py +0 -986
  103. package/src/plugins/user_state_tools 2.py +0 -43
  104. package/src/plugins/workflow 2.py +0 -588
  105. package/src/protocol_settings 2.py +0 -59
  106. package/src/public_contribution 2.py +0 -466
  107. package/src/public_evolution_queue 2.py +0 -241
  108. package/src/requirements 2.txt +0 -14
  109. package/src/retroactive_learnings 2.py +0 -373
  110. package/src/rules/__init__ 2.py +0 -0
  111. package/src/rules/core-rules 2.json +0 -331
  112. package/src/rules/migrate 2.py +0 -207
  113. package/src/runtime_power 2.py +0 -874
  114. package/src/script_registry 2.py +0 -1559
  115. package/src/scripts/check-context 2.py +0 -272
  116. package/src/scripts/deep-sleep/apply_findings 2.py +0 -2327
  117. package/src/scripts/deep-sleep/collect 2.py +0 -928
  118. package/src/scripts/deep-sleep/extract 2.py +0 -330
  119. package/src/scripts/deep-sleep/extract-prompt 2.md +0 -285
  120. package/src/scripts/deep-sleep/synthesize 2.py +0 -312
  121. package/src/scripts/deep-sleep/synthesize-prompt 2.md +0 -336
  122. package/src/scripts/nexo-agent-run 2.py +0 -75
  123. package/src/scripts/nexo-auto-update 2.py +0 -6
  124. package/src/scripts/nexo-backup 2.sh +0 -25
  125. package/src/scripts/nexo-brain-activation 2.sh +0 -140
  126. package/src/scripts/nexo-catchup 2.py +0 -300
  127. package/src/scripts/nexo-cognitive-decay 2.py +0 -257
  128. package/src/scripts/nexo-cortex-cycle 2.py +0 -293
  129. package/src/scripts/nexo-cron-wrapper 2.sh +0 -53
  130. package/src/scripts/nexo-daily-self-audit 2.py +0 -2161
  131. package/src/scripts/nexo-dashboard 2.sh +0 -29
  132. package/src/scripts/nexo-deep-sleep 2.sh +0 -86
  133. package/src/scripts/nexo-evolution-run 2.py +0 -1664
  134. package/src/scripts/nexo-followup-hygiene 2.py +0 -139
  135. package/src/scripts/nexo-hook-record 2.py +0 -42
  136. package/src/scripts/nexo-immune 2.py +0 -936
  137. package/src/scripts/nexo-impact-scorer 2.py +0 -117
  138. package/src/scripts/nexo-inbox-hook 2.sh +0 -74
  139. package/src/scripts/nexo-install 2.py +0 -6
  140. package/src/scripts/nexo-learning-housekeep 2.py +0 -401
  141. package/src/scripts/nexo-learning-validator 2.py +0 -266
  142. package/src/scripts/nexo-migrate 2.py +0 -260
  143. package/src/scripts/nexo-outcome-checker 2.py +0 -127
  144. package/src/scripts/nexo-postmortem-consolidator 2.py +0 -456
  145. package/src/scripts/nexo-pre-commit 2.py +0 -120
  146. package/src/scripts/nexo-prevent-sleep 2.sh +0 -35
  147. package/src/scripts/nexo-proactive-dashboard 2.py +0 -354
  148. package/src/scripts/nexo-reflection 2.py +0 -256
  149. package/src/scripts/nexo-runtime-preflight 2.py +0 -274
  150. package/src/scripts/nexo-sleep 2.py +0 -631
  151. package/src/scripts/nexo-snapshot-restore 2.sh +0 -35
  152. package/src/scripts/nexo-sync-clients 2.py +0 -16
  153. package/src/scripts/nexo-synthesis 2.py +0 -475
  154. package/src/scripts/nexo-tcc-approve 2.sh +0 -79
  155. package/src/scripts/nexo-update 2.sh +0 -306
  156. package/src/scripts/nexo-watchdog 2.sh +0 -1207
  157. package/src/scripts/nexo-watchdog-smoke 2.py +0 -119
  158. package/src/scripts/rehydrate_learnings_from_archive 2.py +0 -245
  159. package/src/server 2.py +0 -1296
  160. package/src/skills/run-nexo-audit-phase/guide 2.md +0 -43
  161. package/src/skills/run-nexo-audit-phase/skill 2.json +0 -59
  162. package/src/skills/run-nexo-core-fix-cycle/guide 2.md +0 -17
  163. package/src/skills/run-nexo-core-fix-cycle/script 2.py +0 -276
  164. package/src/skills/run-nexo-core-fix-cycle/skill 2.json +0 -58
  165. package/src/skills/run-release-final-audit/guide 2.md +0 -16
  166. package/src/skills/run-release-final-audit/script 2.py +0 -259
  167. package/src/skills/run-release-final-audit/skill 2.json +0 -77
  168. package/src/skills/run-runtime-doctor/guide 2.md +0 -12
  169. package/src/skills/run-runtime-doctor/script 2.py +0 -21
  170. package/src/skills/run-runtime-doctor/skill 2.json +0 -25
  171. package/src/skills_runtime 2.py +0 -932
  172. package/src/state_watchers_runtime 2.py +0 -475
  173. package/src/storage_router 2.py +0 -32
  174. package/src/system_catalog 2.py +0 -786
  175. package/src/tools_coordination 2.py +0 -103
  176. package/src/tools_credentials 2.py +0 -68
  177. package/src/tools_drive 2.py +0 -487
  178. package/src/tools_hot_context 2.py +0 -163
  179. package/src/tools_learnings 2.py +0 -612
  180. package/src/tools_menu 2.py +0 -229
  181. package/src/tools_reminders 2.py +0 -88
  182. package/src/tools_reminders_crud 2.py +0 -363
  183. package/src/tools_sessions 2.py +0 -1054
  184. package/src/tools_system_catalog 2.py +0 -19
  185. package/src/tools_task_history 2.py +0 -57
  186. package/src/tools_transcripts 2.py +0 -98
  187. package/src/transcript_utils 2.py +0 -412
  188. package/src/user_context 2.py +0 -46
  189. package/src/user_data_portability 2.py +0 -328
  190. package/src/user_state_model 2.py +0 -170
  191. package/templates/CLAUDE.md 2.template +0 -108
  192. package/templates/CODEX.AGENTS.md 2.template +0 -66
  193. package/templates/launchagents/README 2.md +0 -132
  194. package/templates/launchagents/com.nexo.auto-close-sessions 2.plist +0 -39
  195. package/templates/launchagents/com.nexo.catchup 2.plist +0 -39
  196. package/templates/launchagents/com.nexo.cognitive-decay 2.plist +0 -40
  197. package/templates/launchagents/com.nexo.dashboard 2.plist +0 -43
  198. package/templates/launchagents/com.nexo.deep-sleep 2.plist +0 -43
  199. package/templates/launchagents/com.nexo.evolution 2.plist +0 -44
  200. package/templates/launchagents/com.nexo.followup-hygiene 2.plist +0 -45
  201. package/templates/launchagents/com.nexo.immune 2.plist +0 -41
  202. package/templates/launchagents/com.nexo.postmortem 2.plist +0 -45
  203. package/templates/launchagents/com.nexo.self-audit 2.plist +0 -47
  204. package/templates/launchagents/com.nexo.synthesis 2.plist +0 -45
  205. package/templates/launchagents/com.nexo.watchdog 2.plist +0 -37
  206. package/templates/nexo_helper 2.py +0 -301
  207. package/templates/openclaw 2.json +0 -13
  208. package/templates/plugin-template 2.py +0 -40
  209. package/templates/script-template 2.py +0 -59
  210. package/templates/script-template 2.sh +0 -13
  211. package/templates/skill-script-template 2.py +0 -48
  212. package/templates/skill-template 2.md +0 -33
@@ -1,67 +0,0 @@
1
- """Entities plugin — people, services, URLs, recurring contacts."""
2
- from db import create_entity, search_entities, list_entities, update_entity, delete_entity
3
-
4
- def handle_entity_search(query: str, type: str = "") -> str:
5
- """Search entities by name or value. Optional type filter."""
6
- results = search_entities(query, type)
7
- if not results:
8
- return "No results."
9
- lines = []
10
- for e in results:
11
- notes = f" — {e['notes']}" if e.get("notes") else ""
12
- lines.append(f" [{e['id']}] ({e['type']}) {e['name']}: {e['value']}{notes}")
13
- return f"ENTIDADES ({len(results)}):\n" + "\n".join(lines)
14
-
15
- def handle_entity_create(name: str, type: str, value: str, notes: str = "") -> str:
16
- """Create a new entity."""
17
- eid = create_entity(name, type, value, notes)
18
- # KG hook
19
- try:
20
- from kg_populate import on_entity_create
21
- on_entity_create(eid, name, type)
22
- except Exception:
23
- pass
24
- return f"Entity created: [{eid}] {name} ({type})"
25
-
26
- def handle_entity_update(id: int, name: str = "", type: str = "", value: str = "", notes: str = "") -> str:
27
- """Update an entity. Only non-empty fields are changed."""
28
- kwargs = {}
29
- if name: kwargs["name"] = name
30
- if type: kwargs["type"] = type
31
- if value: kwargs["value"] = value
32
- if notes: kwargs["notes"] = notes
33
- if not kwargs: return "Nothing to update."
34
- update_entity(id, **kwargs)
35
- return f"Entity [{id}] updated."
36
-
37
- def handle_entity_delete(id: int) -> str:
38
- """Delete an entity."""
39
- if not delete_entity(id):
40
- return f"ERROR: Entity [{id}] not found."
41
- return f"Entity [{id}] deleted."
42
-
43
- def handle_entity_list(type: str = "") -> str:
44
- """List all entities, optionally filtered by type."""
45
- results = list_entities(type)
46
- if not results:
47
- return "No entities."
48
- grouped = {}
49
- for e in results:
50
- t = e["type"]
51
- if t not in grouped: grouped[t] = []
52
- grouped[t].append(e)
53
- lines = []
54
- for t, entities in grouped.items():
55
- lines.append(f"\n [{t.upper()}]")
56
- for e in entities:
57
- notes = f" — {e['notes']}" if e.get("notes") else ""
58
- lines.append(f" [{e['id']}] {e['name']}: {e['value']}{notes}")
59
- return f"ENTIDADES ({len(results)}):" + "\n".join(lines)
60
-
61
- TOOLS = [
62
- (handle_entity_search, "nexo_entity_search", "Search entities by name, value, or type"),
63
- (handle_entity_create, "nexo_entity_create", "Create a new entity (person, service, URL)"),
64
- (handle_entity_update, "nexo_entity_update", "Update an entity's fields"),
65
- (handle_entity_delete, "nexo_entity_delete", "Delete an entity"),
66
- (handle_entity_list, "nexo_entity_list", "List all entities grouped by type"),
67
- ]
@@ -1,560 +0,0 @@
1
- """Episodic memory plugin — decisions, session diary, and reasoning traces."""
2
-
3
- import datetime
4
- import json
5
- import time
6
- from db import (
7
- log_decision, update_decision_outcome, search_decisions,
8
- write_session_diary, read_session_diary,
9
- log_change, search_changes, update_change_commit,
10
- recall, get_db, set_linked_outcomes_met,
11
- )
12
-
13
-
14
- def _cognitive_ingest_safe(content, source_type, source_id="", source_title="", domain=""):
15
- """Ingest to cognitive STM. Silently fails if cognitive engine unavailable."""
16
- try:
17
- import cognitive
18
- cognitive.ingest(content, source_type, source_id, source_title, domain)
19
- except Exception:
20
- pass # Cognitive is optional — never block operational writes
21
-
22
-
23
- def handle_decision_log(domain: str, decision: str, alternatives: str = '',
24
- based_on: str = '', confidence: str = 'medium',
25
- context_ref: str = '', session_id: str = '',
26
- review_days: int = 14) -> str:
27
- """Log a non-trivial decision with reasoning context.
28
-
29
- Args:
30
- domain: Area (ads, shopify, server, project-a, nexo, project-b, other)
31
- decision: What was decided
32
- alternatives: JSON array or text of options considered and why discarded
33
- based_on: Data, metrics, or observations that informed this decision
34
- confidence: high, medium, or low
35
- context_ref: Related followup/reminder ID (e.g., NF-ADS1, R71)
36
- session_id: Current session ID (auto-filled if empty)
37
- """
38
- valid_domains = {'ads', 'shopify', 'server', 'project-a', 'nexo', 'project-b', 'other'}
39
- if domain not in valid_domains:
40
- return f"ERROR: domain must be one of: {', '.join(sorted(valid_domains))}"
41
- if confidence not in ('high', 'medium', 'low'):
42
- return f"ERROR: confidence must be high, medium, or low"
43
-
44
- sid = session_id or 'unknown'
45
- result = log_decision(sid, domain, decision, alternatives, based_on, confidence, context_ref)
46
- if "error" in result:
47
- return f"ERROR: {result['error']}"
48
- _cognitive_ingest_safe(
49
- f"Decision: {decision}. Alternatives: {alternatives}. Based on: {based_on}",
50
- "decision", f"D{result.get('id','')}", (decision or '')[:80], domain
51
- )
52
- conn = get_db()
53
- due = (datetime.datetime.now() + datetime.timedelta(days=max(1, int(review_days)))).isoformat(timespec='seconds')
54
- conn.execute(
55
- "UPDATE decisions SET status = ?, review_due_at = ? WHERE id = ?",
56
- ("pending_review", due, result["id"])
57
- )
58
- conn.commit()
59
- # KG hook
60
- try:
61
- from kg_populate import on_decision_log
62
- on_decision_log(result["id"], domain, decision)
63
- except Exception:
64
- pass
65
- result = dict(conn.execute("SELECT * FROM decisions WHERE id = ?", (result["id"],)).fetchone())
66
- due = result.get("review_due_at", "")
67
- due_str = f" review_due={due}" if due else ""
68
- return f"Decision #{result['id']} registrada [{domain}] ({confidence}): {decision[:80]}{due_str}"
69
-
70
-
71
- def handle_decision_outcome(id: int, outcome: str) -> str:
72
- """Record what actually happened after a past decision.
73
-
74
- Args:
75
- id: Decision ID number
76
- outcome: What happened — was the decision correct? What changed?
77
- """
78
- result = update_decision_outcome(id, outcome)
79
- if "error" in result:
80
- return f"ERROR: {result['error']}"
81
- conn = get_db()
82
- conn.execute(
83
- "UPDATE decisions SET status = 'reviewed', review_due_at = NULL, last_reviewed_at = datetime('now') WHERE id = ?",
84
- (id,)
85
- )
86
- conn.commit()
87
- linked_outcomes = []
88
- try:
89
- linked_outcomes = set_linked_outcomes_met(
90
- "decision",
91
- str(id),
92
- metric_source="decision_outcome",
93
- actual_value=1.0,
94
- actual_value_text=outcome,
95
- note="Linked decision outcome recorded.",
96
- )
97
- except Exception:
98
- linked_outcomes = []
99
- suffix = f" Linked outcomes met: {len(linked_outcomes)}." if linked_outcomes else ""
100
- return f"Decision #{id} outcome recorded: {outcome[:100]}{suffix}"
101
-
102
-
103
- def handle_decision_search(query: str = '', domain: str = '', days: int = 30) -> str:
104
- """Search past decisions to answer 'why did we do X?'
105
-
106
- Args:
107
- query: Text to search in decision, alternatives, based_on, outcome
108
- domain: Filter by area (ads, shopify, server, project-a, nexo, project-b, other)
109
- days: Look back N days (default 30)
110
- """
111
- valid_domains = {'ads', 'shopify', 'server', 'project-a', 'nexo', 'project-b', 'other'}
112
- if domain and domain not in valid_domains:
113
- return f"ERROR: domain must be one of: {', '.join(sorted(valid_domains))}"
114
- results = search_decisions(query, domain, days)
115
- if not results:
116
- scope = f"'{query}'" if query else domain or 'all'
117
- return f"No decisions found for {scope} in {days} days."
118
-
119
- lines = [f"DECISIONS ({len(results)}):"]
120
- for d in results:
121
- conf = d.get('confidence', '?')
122
- outcome_str = f" → {d['outcome'][:50]}" if d.get('outcome') else ""
123
- ref = f" [{d['context_ref']}]" if d.get('context_ref') else ""
124
- status = d.get('status', 'pending_review')
125
- review_due = f" due={d['review_due_at']}" if d.get('review_due_at') else ""
126
- lines.append(f" #{d['id']} ({d['created_at']}) [{d['domain']}] {conf} [{status}]{ref}{review_due}")
127
- lines.append(f" {d['decision'][:120]}")
128
- if d.get('based_on'):
129
- lines.append(f" Basado en: {d['based_on'][:100]}")
130
- if d.get('alternatives'):
131
- lines.append(f" Alternativas: {d['alternatives'][:100]}")
132
- if outcome_str:
133
- lines.append(f" Outcome:{outcome_str}")
134
- return "\n".join(lines)
135
-
136
-
137
- def handle_memory_review_queue(days: int = 0) -> str:
138
- """Show decisions and learnings that are due for review.
139
-
140
- Args:
141
- days: Include items due within N future days (default only overdue/today)
142
- """
143
- conn = get_db()
144
- now_epoch = time.time() + (max(0, int(days)) * 86400)
145
- now_iso = (datetime.datetime.now() + datetime.timedelta(days=max(0, int(days)))).isoformat(timespec='seconds')
146
- learnings = [dict(r) for r in conn.execute(
147
- "SELECT * FROM learnings WHERE review_due_at IS NOT NULL AND status != 'superseded' AND review_due_at <= ? ORDER BY review_due_at ASC, updated_at DESC",
148
- (now_epoch,)
149
- ).fetchall()]
150
- decisions = [dict(r) for r in conn.execute(
151
- "SELECT * FROM decisions WHERE review_due_at IS NOT NULL AND status != 'reviewed' AND review_due_at <= ? ORDER BY review_due_at ASC, created_at DESC",
152
- (now_iso,)
153
- ).fetchall()]
154
- if not learnings and not decisions:
155
- return f"No memory reviews due within {days} day(s)."
156
-
157
- lines = [f"MEMORY REVIEW QUEUE (days={days}):"]
158
- if decisions:
159
- lines.append(f" Decisions ({len(decisions)}):")
160
- for d in decisions[:10]:
161
- lines.append(f" #{d['id']} [{d.get('domain','other')}] {d['decision'][:90]}")
162
- if d.get("review_due_at"):
163
- lines.append(f" due={d['review_due_at']} status={d.get('status','pending_review')}")
164
- if learnings:
165
- lines.append(f" Learnings ({len(learnings)}):")
166
- for l in learnings[:10]:
167
- lines.append(f" #{l['id']} [{l.get('category','general')}] {l['title'][:90]}")
168
- due = l.get("review_due_at")
169
- due_str = f"{due:.0f}" if isinstance(due, (int, float)) and due else str(due or "")
170
- lines.append(f" due={due_str} status={l.get('status','active')}")
171
- if l.get("prevention"):
172
- lines.append(f" prevention={str(l['prevention'])[:100]}")
173
- return "\n".join(lines)
174
-
175
-
176
- def handle_session_diary_write(decisions: str, summary: str,
177
- discarded: str = '', pending: str = '',
178
- context_next: str = '', mental_state: str = '',
179
- user_signals: str = '',
180
- domain: str = '',
181
- session_id: str = '',
182
- self_critique: str = '',
183
- source: str = 'claude') -> str:
184
- """Write session diary entry at end of session. OBLIGATORIO antes de cerrar.
185
-
186
- Args:
187
- decisions: What was decided and why (JSON array or structured text)
188
- summary: 2-3 line summary of the session
189
- discarded: Options/approaches considered but rejected, and why
190
- pending: Items left unresolved, with doubt level
191
- context_next: What the next session should know to continue effectively
192
- mental_state: Internal state to transfer — thread of thought, tone, observations not yet shared, momentum. Written in first person as NEXO.
193
- user_signals: Observable signals from user during session — response speed (fast='s' vs detailed explanations), tone (direct, frustrated, exploratory, excited), corrections given, topics he initiated vs topics NEXO initiated. Factual observations only, not interpretations.
194
- domain: Project context: ecommerce, project-a, nexo, project-b, server, other
195
- session_id: Current session ID
196
- self_critique: REQUIRED. Honest post-mortem.
197
- source: Session type. 'claude' for human-interactive sessions (default), 'cron' for automated cron jobs. Affects visibility at startup.
198
- """
199
- sid = session_id or 'unknown'
200
- # Clean up draft — manual diary supersedes it
201
- from db import delete_diary_draft
202
- delete_diary_draft(sid)
203
- result = write_session_diary(sid, decisions, summary, discarded, pending, context_next, mental_state, domain=domain, user_signals=user_signals, self_critique=self_critique, source=source)
204
- if "error" in result:
205
- return f"ERROR: {result['error']}"
206
- _cognitive_ingest_safe(summary, "diary", f"diary#{result.get('id','')}", f"Session {sid} summary", domain)
207
- if self_critique and self_critique.strip():
208
- _cognitive_ingest_safe(self_critique, "critique", f"diary#{result.get('id','')}", f"Session {sid} critique", domain)
209
- if mental_state and mental_state.strip():
210
- _cognitive_ingest_safe(mental_state, "mental_state", f"diary#{result.get('id','')}", f"Session {sid} state", domain)
211
- domain_str = f" [{domain}]" if domain else ""
212
- msg = f"Session diary #{result['id']}{domain_str} saved: {summary[:80]}"
213
-
214
- # Trust score & sentiment summary for session diary
215
- try:
216
- import cognitive
217
- trust = cognitive.get_trust_score()
218
- history = cognitive.get_trust_history(days=1)
219
- net = history.get("net_change", 0)
220
- sentiment_dist = history.get("sentiment_distribution", {})
221
- vibe = max(sentiment_dist, key=lambda k: sentiment_dist[k]["count"]) if sentiment_dist else "neutral"
222
- msg += f"\nScore: {trust:.0f}/100 ({net:+.0f}) | Vibe: {vibe}"
223
- except Exception:
224
- pass
225
-
226
- # Episodic memory audit — warn about gaps
227
- warnings = []
228
- conn = __import__('db').get_db()
229
- orphan_changes = conn.execute(
230
- "SELECT COUNT(*) FROM change_log WHERE (commit_ref IS NULL OR commit_ref = '')"
231
- ).fetchone()[0]
232
- recent_orphan_changes = conn.execute(
233
- """SELECT COUNT(*) FROM change_log
234
- WHERE (commit_ref IS NULL OR commit_ref = '')
235
- AND created_at >= datetime('now', '-7 days')"""
236
- ).fetchone()[0]
237
- if orphan_changes > 0:
238
- if recent_orphan_changes > 0 and recent_orphan_changes != orphan_changes:
239
- warnings.append(
240
- f"{recent_orphan_changes} changes recientes sin commit_ref ({orphan_changes} históricas total)"
241
- )
242
- elif recent_orphan_changes > 0:
243
- warnings.append(f"{recent_orphan_changes} changes recientes sin commit_ref")
244
- else:
245
- warnings.append(f"{orphan_changes} changes históricas sin commit_ref")
246
- orphan_decisions = conn.execute(
247
- "SELECT COUNT(*) FROM decisions WHERE (outcome IS NULL OR outcome = '') AND created_at < datetime('now', '-7 days')"
248
- ).fetchone()[0]
249
- if orphan_decisions > 0:
250
- warnings.append(f"{orphan_decisions} decisions >7d sin outcome")
251
- if warnings:
252
- msg += "\n⚠ EPISODIC GAPS: " + " | ".join(warnings) + " — resolve before closing session."
253
-
254
- return msg
255
-
256
-
257
- def handle_session_diary_read(session_id: str = '', last_n: int = 3, last_day: bool = False,
258
- domain: str = '', brief: bool = False) -> str:
259
- """Read recent session diaries for context continuity.
260
-
261
- Args:
262
- session_id: Specific session ID to read (optional)
263
- last_n: Number of recent entries to return (default 3)
264
- last_day: If true, returns the recent continuity window (~36h), including the previous evening. Use this at startup.
265
- domain: Filter by project context: ecommerce, project-a, nexo, project-b, server, other
266
- brief: If true, returns ONLY the last diary entry with summary + mental_state + context_next.
267
- Use this at startup for fast context loading (~1K chars instead of full dump).
268
- """
269
- if brief:
270
- # Fast path: only the most recent diary entry, compact format
271
- results = read_session_diary(session_id, 1, last_day=False, domain=domain)
272
- if not results:
273
- return "No session diary entries."
274
- d = results[0]
275
- lines = [f"LAST DIARY ({d['created_at']}):"]
276
- lines.append(f" {d['summary'][:300]}")
277
- if d.get('pending'):
278
- lines.append(f" Pending: {d['pending'][:200]}")
279
- if d.get('context_next'):
280
- lines.append(f" Context: {d['context_next'][:200]}")
281
- if d.get('mental_state'):
282
- lines.append(f" Mental: {d['mental_state'][:300]}")
283
- return "\n".join(lines)
284
-
285
- results = read_session_diary(session_id, last_n, last_day, domain)
286
- if not results:
287
- return "No session diary entries."
288
-
289
- lines = [f"SESSION DIARY ({len(results)}):"]
290
- for d in results:
291
- domain_label = f" [{d['domain']}]" if d.get('domain') else ""
292
- lines.append(f"\n --- Session {d['session_id']}{domain_label} ({d['created_at']}) ---")
293
- lines.append(f" Summary: {d['summary']}")
294
- if d.get('decisions'):
295
- lines.append(f" Decisions: {d['decisions'][:200]}")
296
- if d.get('discarded'):
297
- lines.append(f" Descartado: {d['discarded'][:150]}")
298
- if d.get('pending'):
299
- lines.append(f" Pending: {d['pending'][:150]}")
300
- if d.get('context_next'):
301
- lines.append(f" For next session: {d['context_next'][:200]}")
302
- if d.get('mental_state'):
303
- lines.append(f" Estado mental: {d['mental_state'][:300]}")
304
- if d.get('user_signals'):
305
- lines.append(f" User signals: {d['user_signals'][:300]}")
306
- return "\n".join(lines)
307
-
308
-
309
- def handle_change_log(files: str, what_changed: str, why: str,
310
- triggered_by: str = '', affects: str = '',
311
- risks: str = '', verify: str = '',
312
- commit_ref: str = '', session_id: str = '') -> str:
313
- """Log a code/config change with full context. OBLIGATORIO after every edit to production code.
314
-
315
- Args:
316
- files: File path(s) modified (comma-separated if multiple)
317
- what_changed: What was modified — functions, lines, behavior change
318
- why: WHY this change was needed — the root cause, not just "fix bug"
319
- triggered_by: What triggered this — bug report, metric, user's request, followup ID
320
- affects: What systems/users/flows this change impacts
321
- risks: What could go wrong — regressions, edge cases, dependencies
322
- verify: How to verify this works — what to check, followup ID if created
323
- commit_ref: Git commit hash (can be added later with nexo_change_commit)
324
- session_id: Current session ID
325
- """
326
- if not files or not what_changed or not why:
327
- return "ERROR: files, what_changed, and why are required"
328
- sid = session_id or 'unknown'
329
- result = log_change(sid, files, what_changed, why, triggered_by, affects, risks, verify, commit_ref)
330
- if "error" in result:
331
- return f"ERROR: {result['error']}"
332
- _cognitive_ingest_safe(
333
- f"{what_changed}. Why: {why}",
334
- "change", f"C{result.get('id','')}", (what_changed or '')[:80], ""
335
- )
336
- change_id = result['id']
337
- # KG hook
338
- try:
339
- from kg_populate import on_change_log
340
- on_change_log(change_id, files, "")
341
- except Exception:
342
- pass
343
- msg = f"Change #{change_id} recorded: {files[:60]} — {what_changed[:60]}"
344
- if not commit_ref:
345
- msg += f"\n⚠ NO COMMIT. Use nexo_change_commit({change_id}, 'hash') after push, or 'server-direct' if it was a direct server edit."
346
- return msg
347
-
348
-
349
- def handle_change_search(query: str = '', files: str = '', days: int = 30) -> str:
350
- """Search past code changes — answers 'what did we change in X?' or 'why did we touch Y?'
351
-
352
- Args:
353
- query: Text to search in what_changed, why, affects, triggered_by
354
- files: Filter by file path (partial match)
355
- days: Look back N days (default 30)
356
- """
357
- results = search_changes(query, files, days)
358
- if not results:
359
- scope = f"'{query}'" if query else files or 'all'
360
- return f"No changes found for {scope} in {days} days."
361
-
362
- lines = [f"CHANGES ({len(results)}):"]
363
- for c in results:
364
- commit = f" [{c['commit_ref'][:8]}]" if c.get('commit_ref') else ""
365
- lines.append(f" #{c['id']} ({c['created_at']}){commit}")
366
- lines.append(f" Files: {c['files'][:100]}")
367
- lines.append(f" What: {c['what_changed'][:120]}")
368
- lines.append(f" Why: {c['why'][:120]}")
369
- if c.get('triggered_by'):
370
- lines.append(f" Trigger: {c['triggered_by'][:80]}")
371
- if c.get('affects'):
372
- lines.append(f" Afecta: {c['affects'][:80]}")
373
- if c.get('risks'):
374
- lines.append(f" Riesgos: {c['risks'][:80]}")
375
- return "\n".join(lines)
376
-
377
-
378
- def handle_change_commit(id: int, commit_ref: str) -> str:
379
- """Link a change log entry to its git commit hash after committing.
380
-
381
- After linking, automatically resolves any open followups that match
382
- the change (by file overlap, keyword similarity, or explicit ID reference).
383
-
384
- Args:
385
- id: Change log entry ID
386
- commit_ref: Git commit hash
387
- """
388
- result = update_change_commit(id, commit_ref)
389
- if "error" in result:
390
- return f"ERROR: {result['error']}"
391
-
392
- msg = f"Change #{id} vinculado a commit {commit_ref[:8]}"
393
- auto_resolved = result.get("_auto_resolved", [])
394
- if auto_resolved:
395
- ids = ", ".join(auto_resolved)
396
- msg += f"\n✅ AUTO-RESOLVED followups: {ids}"
397
- return msg
398
-
399
-
400
- def handle_recall(query: str, days: int = 30) -> str:
401
- """Search across ALL memory — changes, decisions, learnings, followups, diary. One query to find anything.
402
-
403
- Args:
404
- query: Text to search across all memory tables
405
- days: Look back N days (default 30)
406
- """
407
- results = recall(query, days)
408
-
409
- # Fallback to diary archive if few results (subconscious memory)
410
- archive_results = []
411
- if len(results) < 5:
412
- try:
413
- from db import diary_archive_search
414
- archive_results = diary_archive_search(query=query, limit=5)
415
- except Exception:
416
- pass
417
-
418
- if not results and not archive_results:
419
- return f"No results for '{query}' in the last {days} days or in the archive."
420
-
421
- # v1.2: Passive rehearsal — strengthen matching cognitive memories
422
- try:
423
- import cognitive
424
- for r in results[:5]:
425
- title = str(r.get('title', ''))
426
- snippet = str(r.get('snippet', ''))
427
- cognitive.rehearse_by_content(f"{title} {snippet[:200]}")
428
- except Exception:
429
- pass
430
-
431
- SOURCE_LABELS = {
432
- 'change_log': '[CHANGE]',
433
- 'change': '[CHANGE]',
434
- 'decision': '[DECISION]',
435
- 'learning': '[LEARNING]',
436
- 'followup': '[FOLLOWUP]',
437
- 'diary': '[DIARY]',
438
- 'diary_archive': '[ARCHIVE]',
439
- 'entity': '[ENTITY]',
440
- 'file': '[FILE]',
441
- 'code': '[CODE]',
442
- }
443
-
444
- lines = [f"RECALL '{query}' — {len(results)} result(s):"]
445
- for r in results:
446
- source = r.get('source', '?')
447
- label = SOURCE_LABELS.get(source, f"[{source.upper()}]")
448
- sid = r.get('source_id', r.get('id', '?'))
449
- title = str(r.get('title', ''))[:120]
450
- snippet = str(r.get('snippet', ''))[:200].strip(' |')
451
- cat = r.get('category', '')
452
- cat_str = f" ({cat})" if cat else ''
453
- lines.append(f"\n {label} #{sid}{cat_str}")
454
- lines.append(f" {title}")
455
- if snippet:
456
- lines.append(f" {snippet}")
457
-
458
- if archive_results:
459
- lines.append(f"\n--- SUBCONSCIOUS (diary archive) — {len(archive_results)} result(s) ---")
460
- for r in archive_results:
461
- lines.append(f"\n [ARCHIVE] #{r['id']} ({r['created_at'][:10]}) [{r.get('domain', '?')}]")
462
- lines.append(f" {r['summary'][:200]}")
463
- elif len(results) < 5:
464
- lines.append(f"\n 💡 Only a few results. Diary archive is empty (populates automatically after 180 days).")
465
- return "\n".join(lines)
466
-
467
-
468
- def handle_diary_archive_search(
469
- query: str = "",
470
- domain: str = "",
471
- year: int = 0,
472
- month: int = 0,
473
- limit: int = 20
474
- ) -> str:
475
- """Search the permanent diary archive (subconscious memory). Use for 'last year', 'months ago', 'in February', etc.
476
-
477
- Args:
478
- query: Text to search in diary content
479
- domain: Filter by project domain (e.g. 'project-a', 'ecommerce')
480
- year: Filter by year (e.g. 2026)
481
- month: Filter by month (1-12), requires year
482
- limit: Max results (default 20)
483
- """
484
- from db import diary_archive_search, diary_archive_stats
485
-
486
- if not query and not domain and not year:
487
- stats = diary_archive_stats()
488
- if stats["count"] == 0:
489
- return "Archive empty — diaries are archived automatically after 180 days."
490
- return (
491
- f"DIARY ARCHIVE STATS:\n"
492
- f" Total: {stats['count']} archived diaries\n"
493
- f" Range: {stats['oldest']} → {stats['newest']}\n"
494
- f" Domains: {', '.join(stats['domains']) if stats['domains'] else 'N/A'}\n"
495
- f"\nUse query, domain, year/month to search."
496
- )
497
-
498
- results = diary_archive_search(query=query, domain=domain, year=year, month=month, limit=limit)
499
- if not results:
500
- return f"No results in archive for: query='{query}' domain='{domain}' year={year} month={month}"
501
-
502
- lines = [f"DIARY ARCHIVE — {len(results)} result(s):"]
503
- for r in results:
504
- lines.append(f"\n [#{r['id']}] {r['created_at'][:10]} [{r.get('domain', '?')}]")
505
- lines.append(f" {r['summary'][:200]}")
506
- if r.get('decisions'):
507
- lines.append(f" Decisions: {r['decisions'][:150]}")
508
- if r.get('mental_state'):
509
- lines.append(f" Estado: {r['mental_state'][:100]}")
510
- return "\n".join(lines)
511
-
512
-
513
- def handle_diary_archive_read(diary_id: int = 0) -> str:
514
- """Read a single archived diary entry in full detail.
515
-
516
- Args:
517
- diary_id: The archive diary ID (from search results)
518
- """
519
- if not diary_id:
520
- return "ERROR: diary_id required. Use nexo_diary_archive_search to find IDs."
521
-
522
- from db import diary_archive_read
523
- entry = diary_archive_read(diary_id)
524
- if not entry:
525
- return f"Diary #{diary_id} not found in archive."
526
-
527
- lines = [f"DIARY ARCHIVE #{entry['id']} — {entry['created_at']}"]
528
- lines.append(f" Session: {entry['session_id']}")
529
- lines.append(f" Domain: {entry.get('domain', 'N/A')}")
530
- lines.append(f" Source: {entry.get('source', 'N/A')}")
531
- lines.append(f"\nSUMMARY:\n {entry['summary']}")
532
- if entry.get('decisions'):
533
- lines.append(f"\nDECISIONS:\n {entry['decisions']}")
534
- if entry.get('pending'):
535
- lines.append(f"\nPENDING:\n {entry['pending']}")
536
- if entry.get('mental_state'):
537
- lines.append(f"\nMENTAL STATE:\n {entry['mental_state']}")
538
- if entry.get('self_critique'):
539
- lines.append(f"\nSELF-CRITIQUE:\n {entry['self_critique']}")
540
- if entry.get('user_signals'):
541
- lines.append(f"\nUSER SIGNALS:\n {entry['user_signals']}")
542
- if entry.get('context_next'):
543
- lines.append(f"\nNEXT SESSION CONTEXT:\n {entry['context_next']}")
544
- return "\n".join(lines)
545
-
546
-
547
- TOOLS = [
548
- (handle_change_log, "nexo_change_log", "Log a code/config change with full context: what, why, trigger, affects, risks"),
549
- (handle_change_search, "nexo_change_search", "Search past code changes — answers 'what did we change in X?' or 'why did we touch Y?'"),
550
- (handle_change_commit, "nexo_change_commit", "Link a change log entry to its git commit hash"),
551
- (handle_decision_log, "nexo_decision_log", "Log a non-trivial decision with reasoning, alternatives, and evidence"),
552
- (handle_decision_outcome, "nexo_decision_outcome", "Record what actually happened after a past decision"),
553
- (handle_decision_search, "nexo_decision_search", "Search past decisions — answers 'why did we do X?'"),
554
- (handle_memory_review_queue, "nexo_memory_review_queue", "Show decisions and learnings that are due for review"),
555
- (handle_session_diary_write, "nexo_session_diary_write", "Write end-of-session diary with decisions, discards, and context for next session"),
556
- (handle_session_diary_read, "nexo_session_diary_read", "Read recent session diaries for context continuity"),
557
- (handle_recall, "nexo_recall", "Search across ALL NEXO memory — changes, decisions, learnings, followups, diary, entities, .md files, code files. For deep historical context (older sessions, past work), also search diary_archive."),
558
- (handle_diary_archive_search, "nexo_diary_archive_search", "Search the permanent diary archive (subconscious memory). Diaries older than 180d are moved here forever. Use for historical lookups: 'last year', 'months ago', 'in February', etc."),
559
- (handle_diary_archive_read, "nexo_diary_archive_read", "Read a single archived diary entry in full detail. Get the ID from diary_archive_search."),
560
- ]