nexo-brain 2.2.0 → 2.3.1

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 (256) hide show
  1. package/README.md +5 -5
  2. package/package.json +6 -3
  3. package/src/auto_update.py +26 -0
  4. package/src/crons/manifest.json +6 -13
  5. package/src/crons/sync.py +150 -6
  6. package/src/db/__init__.py +13 -0
  7. package/src/db/_core.py +1 -0
  8. package/src/db/_cron_runs.py +74 -0
  9. package/src/db/_entities.py +1 -0
  10. package/src/db/_episodic.py +41 -6
  11. package/src/db/_learnings.py +1 -0
  12. package/src/db/_reminders.py +1 -0
  13. package/src/db/_schema.py +64 -0
  14. package/src/db/_sessions.py +1 -0
  15. package/src/db/_skills.py +515 -0
  16. package/src/hooks/session-stop.sh +13 -101
  17. package/src/plugin_loader.py +1 -0
  18. package/src/plugins/episodic_memory.py +5 -3
  19. package/src/plugins/schedule.py +212 -0
  20. package/src/plugins/skills.py +264 -0
  21. package/src/plugins/update.py +1 -0
  22. package/src/scripts/deep-sleep/apply_findings.py +111 -8
  23. package/src/scripts/deep-sleep/collect.py +34 -11
  24. package/src/scripts/deep-sleep/extract-prompt.md +38 -0
  25. package/src/scripts/deep-sleep/extract.py +81 -8
  26. package/src/scripts/deep-sleep/synthesize-prompt.md +29 -1
  27. package/src/scripts/deep-sleep/synthesize.py +4 -1
  28. package/src/scripts/nexo-catchup.py +65 -29
  29. package/src/scripts/nexo-cron-wrapper.sh +53 -0
  30. package/src/scripts/nexo-daily-self-audit.py +4 -2
  31. package/src/scripts/nexo-deep-sleep.sh +66 -77
  32. package/src/scripts/nexo-evolution-run.py +13 -0
  33. package/src/scripts/nexo-learning-housekeep.py +157 -1
  34. package/src/scripts/nexo-learning-validator.py +19 -0
  35. package/src/scripts/nexo-postmortem-consolidator.py +3 -2
  36. package/src/scripts/nexo-sleep.py +16 -11
  37. package/src/scripts/nexo-synthesis.py +46 -3
  38. package/src/scripts/nexo-watchdog.sh +91 -30
  39. package/src/server.py +6 -1
  40. package/src/tools_coordination.py +1 -0
  41. package/src/tools_sessions.py +1 -0
  42. package/scripts/migrate-to-unified 2.sh +0 -813
  43. package/scripts/migrate-to-unified.sh +0 -813
  44. package/scripts/migrate-v1.5-to-v1.6 2.py +0 -778
  45. package/scripts/migrate-v1.5-to-v1.6.py +0 -778
  46. package/scripts/migrate-v1.7-to-v1.8 2.py +0 -214
  47. package/scripts/migrate-v1.7-to-v1.8.py +0 -214
  48. package/scripts/pre-commit-check 2.sh +0 -55
  49. package/scripts/pre-commit-check.sh +0 -55
  50. package/src/__pycache__/auto_update.cpython-310.pyc +0 -0
  51. package/src/__pycache__/hnsw_index.cpython-310.pyc +0 -0
  52. package/src/__pycache__/kg_populate.cpython-310.pyc +0 -0
  53. package/src/__pycache__/knowledge_graph.cpython-310.pyc +0 -0
  54. package/src/__pycache__/plugin_loader.cpython-310.pyc +0 -0
  55. package/src/__pycache__/tools_coordination.cpython-310.pyc +0 -0
  56. package/src/__pycache__/tools_credentials.cpython-310.pyc +0 -0
  57. package/src/__pycache__/tools_learnings.cpython-310.pyc +0 -0
  58. package/src/__pycache__/tools_menu.cpython-310.pyc +0 -0
  59. package/src/__pycache__/tools_reminders.cpython-310.pyc +0 -0
  60. package/src/__pycache__/tools_reminders_crud.cpython-310.pyc +0 -0
  61. package/src/__pycache__/tools_sessions.cpython-310.pyc +0 -0
  62. package/src/__pycache__/tools_task_history.cpython-310.pyc +0 -0
  63. package/src/auto_close_sessions 2.py +0 -159
  64. package/src/auto_update 2.py +0 -634
  65. package/src/claim_graph 2.py +0 -323
  66. package/src/cognitive/__init__ 2.py +0 -62
  67. package/src/cognitive/__pycache__/__init__.cpython-310.pyc +0 -0
  68. package/src/cognitive/__pycache__/_core.cpython-310.pyc +0 -0
  69. package/src/cognitive/__pycache__/_decay.cpython-310.pyc +0 -0
  70. package/src/cognitive/__pycache__/_ingest.cpython-310.pyc +0 -0
  71. package/src/cognitive/__pycache__/_memory.cpython-310.pyc +0 -0
  72. package/src/cognitive/__pycache__/_search.cpython-310.pyc +0 -0
  73. package/src/cognitive/__pycache__/_trust.cpython-310.pyc +0 -0
  74. package/src/cognitive/_core 2.py +0 -567
  75. package/src/cognitive/_decay 2.py +0 -382
  76. package/src/cognitive/_ingest 2.py +0 -892
  77. package/src/cognitive/_memory 2.py +0 -912
  78. package/src/cognitive/_search 2.py +0 -949
  79. package/src/cognitive/_trust 2.py +0 -464
  80. package/src/crons/manifest 2.json +0 -106
  81. package/src/crons/sync 2.py +0 -217
  82. package/src/dashboard/__init__ 2.py +0 -0
  83. package/src/dashboard/__pycache__/__init__.cpython-310.pyc +0 -0
  84. package/src/dashboard/__pycache__/app.cpython-310.pyc +0 -0
  85. package/src/dashboard/app 2.py +0 -789
  86. package/src/db/__init__ 2.py +0 -89
  87. package/src/db/__pycache__/__init__.cpython-310.pyc +0 -0
  88. package/src/db/__pycache__/__init__.cpython-312.pyc +0 -0
  89. package/src/db/__pycache__/__init__.cpython-314.pyc +0 -0
  90. package/src/db/__pycache__/_core.cpython-310.pyc +0 -0
  91. package/src/db/__pycache__/_core.cpython-312.pyc +0 -0
  92. package/src/db/__pycache__/_core.cpython-314.pyc +0 -0
  93. package/src/db/__pycache__/_credentials.cpython-310.pyc +0 -0
  94. package/src/db/__pycache__/_credentials.cpython-312.pyc +0 -0
  95. package/src/db/__pycache__/_credentials.cpython-314.pyc +0 -0
  96. package/src/db/__pycache__/_entities.cpython-310.pyc +0 -0
  97. package/src/db/__pycache__/_entities.cpython-312.pyc +0 -0
  98. package/src/db/__pycache__/_entities.cpython-314.pyc +0 -0
  99. package/src/db/__pycache__/_episodic.cpython-310.pyc +0 -0
  100. package/src/db/__pycache__/_episodic.cpython-312.pyc +0 -0
  101. package/src/db/__pycache__/_episodic.cpython-314.pyc +0 -0
  102. package/src/db/__pycache__/_evolution.cpython-310.pyc +0 -0
  103. package/src/db/__pycache__/_evolution.cpython-312.pyc +0 -0
  104. package/src/db/__pycache__/_evolution.cpython-314.pyc +0 -0
  105. package/src/db/__pycache__/_fts.cpython-310.pyc +0 -0
  106. package/src/db/__pycache__/_fts.cpython-312.pyc +0 -0
  107. package/src/db/__pycache__/_fts.cpython-314.pyc +0 -0
  108. package/src/db/__pycache__/_learnings.cpython-310.pyc +0 -0
  109. package/src/db/__pycache__/_learnings.cpython-312.pyc +0 -0
  110. package/src/db/__pycache__/_learnings.cpython-314.pyc +0 -0
  111. package/src/db/__pycache__/_reminders.cpython-310.pyc +0 -0
  112. package/src/db/__pycache__/_reminders.cpython-312.pyc +0 -0
  113. package/src/db/__pycache__/_reminders.cpython-314.pyc +0 -0
  114. package/src/db/__pycache__/_schema.cpython-310.pyc +0 -0
  115. package/src/db/__pycache__/_schema.cpython-312.pyc +0 -0
  116. package/src/db/__pycache__/_schema.cpython-314.pyc +0 -0
  117. package/src/db/__pycache__/_sessions.cpython-310.pyc +0 -0
  118. package/src/db/__pycache__/_sessions.cpython-312.pyc +0 -0
  119. package/src/db/__pycache__/_sessions.cpython-314.pyc +0 -0
  120. package/src/db/__pycache__/_tasks.cpython-310.pyc +0 -0
  121. package/src/db/__pycache__/_tasks.cpython-312.pyc +0 -0
  122. package/src/db/__pycache__/_tasks.cpython-314.pyc +0 -0
  123. package/src/db/_core 2.py +0 -417
  124. package/src/db/_credentials 2.py +0 -124
  125. package/src/db/_entities 2.py +0 -178
  126. package/src/db/_episodic 2.py +0 -738
  127. package/src/db/_evolution 2.py +0 -54
  128. package/src/db/_fts 2.py +0 -406
  129. package/src/db/_learnings 2.py +0 -168
  130. package/src/db/_reminders 2.py +0 -338
  131. package/src/db/_schema 2.py +0 -364
  132. package/src/db/_sessions 2.py +0 -300
  133. package/src/db/_tasks 2.py +0 -91
  134. package/src/evolution_cycle 2.py +0 -266
  135. package/src/hnsw_index 2.py +0 -254
  136. package/src/hooks/auto_capture 2.py +0 -208
  137. package/src/hooks/caffeinate-guard 2.sh +0 -8
  138. package/src/hooks/capture-session 2.sh +0 -21
  139. package/src/hooks/capture-tool-logs 2.sh +0 -127
  140. package/src/hooks/daily-briefing-check 2.sh +0 -33
  141. package/src/hooks/inbox-hook 2.sh +0 -76
  142. package/src/hooks/post-compact 2.sh +0 -148
  143. package/src/hooks/pre-compact 2.sh +0 -151
  144. package/src/hooks/session-start 2.sh +0 -268
  145. package/src/hooks/session-stop 2.sh +0 -140
  146. package/src/kg_populate 2.py +0 -290
  147. package/src/knowledge_graph 2.py +0 -257
  148. package/src/maintenance 2.py +0 -59
  149. package/src/migrate_embeddings 2.py +0 -122
  150. package/src/plugin_loader 2.py +0 -202
  151. package/src/plugins/__init__ 2.py +0 -0
  152. package/src/plugins/__pycache__/__init__ 2.cpython-310.pyc +0 -0
  153. package/src/plugins/__pycache__/__init__.cpython-310.pyc +0 -0
  154. package/src/plugins/__pycache__/adaptive_mode 2.cpython-310.pyc +0 -0
  155. package/src/plugins/__pycache__/adaptive_mode.cpython-310.pyc +0 -0
  156. package/src/plugins/__pycache__/agents 2.cpython-310.pyc +0 -0
  157. package/src/plugins/__pycache__/agents.cpython-310.pyc +0 -0
  158. package/src/plugins/__pycache__/artifact_registry 2.cpython-310.pyc +0 -0
  159. package/src/plugins/__pycache__/artifact_registry.cpython-310.pyc +0 -0
  160. package/src/plugins/__pycache__/backup 2.cpython-310.pyc +0 -0
  161. package/src/plugins/__pycache__/backup.cpython-310.pyc +0 -0
  162. package/src/plugins/__pycache__/cognitive_memory 2.cpython-310.pyc +0 -0
  163. package/src/plugins/__pycache__/cognitive_memory.cpython-310.pyc +0 -0
  164. package/src/plugins/__pycache__/core_rules 2.cpython-310.pyc +0 -0
  165. package/src/plugins/__pycache__/core_rules.cpython-310.pyc +0 -0
  166. package/src/plugins/__pycache__/cortex 2.cpython-310.pyc +0 -0
  167. package/src/plugins/__pycache__/cortex.cpython-310.pyc +0 -0
  168. package/src/plugins/__pycache__/entities 2.cpython-310.pyc +0 -0
  169. package/src/plugins/__pycache__/entities.cpython-310.pyc +0 -0
  170. package/src/plugins/__pycache__/episodic_memory 2.cpython-310.pyc +0 -0
  171. package/src/plugins/__pycache__/episodic_memory.cpython-310.pyc +0 -0
  172. package/src/plugins/__pycache__/evolution 2.cpython-310.pyc +0 -0
  173. package/src/plugins/__pycache__/evolution.cpython-310.pyc +0 -0
  174. package/src/plugins/__pycache__/guard 2.cpython-310.pyc +0 -0
  175. package/src/plugins/__pycache__/guard.cpython-310.pyc +0 -0
  176. package/src/plugins/__pycache__/knowledge_graph_tools 2.cpython-310.pyc +0 -0
  177. package/src/plugins/__pycache__/knowledge_graph_tools.cpython-310.pyc +0 -0
  178. package/src/plugins/__pycache__/preferences 2.cpython-310.pyc +0 -0
  179. package/src/plugins/__pycache__/preferences.cpython-310.pyc +0 -0
  180. package/src/plugins/__pycache__/update 2.cpython-310.pyc +0 -0
  181. package/src/plugins/__pycache__/update.cpython-310.pyc +0 -0
  182. package/src/plugins/adaptive_mode 2.py +0 -805
  183. package/src/plugins/agents 2.py +0 -52
  184. package/src/plugins/artifact_registry 2.py +0 -450
  185. package/src/plugins/backup 2.py +0 -104
  186. package/src/plugins/cognitive_memory 2.py +0 -564
  187. package/src/plugins/core_rules 2.py +0 -252
  188. package/src/plugins/cortex 2.py +0 -299
  189. package/src/plugins/entities 2.py +0 -67
  190. package/src/plugins/episodic_memory 2.py +0 -533
  191. package/src/plugins/evolution 2.py +0 -115
  192. package/src/plugins/guard 2.py +0 -746
  193. package/src/plugins/knowledge_graph_tools 2.py +0 -105
  194. package/src/plugins/preferences 2.py +0 -47
  195. package/src/plugins/update 2.py +0 -256
  196. package/src/requirements 2.txt +0 -12
  197. package/src/rules/__init__ 2.py +0 -0
  198. package/src/rules/core-rules 2.json +0 -331
  199. package/src/rules/migrate 2.py +0 -207
  200. package/src/scripts/check-context 2.py +0 -264
  201. package/src/scripts/nexo-auto-update 2.py +0 -6
  202. package/src/scripts/nexo-backup 2.sh +0 -25
  203. package/src/scripts/nexo-brain-activation 2.sh +0 -140
  204. package/src/scripts/nexo-catchup 2.py +0 -242
  205. package/src/scripts/nexo-cognitive-decay 2.py +0 -182
  206. package/src/scripts/nexo-daily-self-audit 2.py +0 -552
  207. package/src/scripts/nexo-deep-sleep 2.sh +0 -97
  208. package/src/scripts/nexo-evolution-run 2.py +0 -597
  209. package/src/scripts/nexo-followup-hygiene 2.py +0 -112
  210. package/src/scripts/nexo-github-monitor 2.py +0 -256
  211. package/src/scripts/nexo-github-monitor.py +0 -256
  212. package/src/scripts/nexo-immune 2.py +0 -927
  213. package/src/scripts/nexo-inbox-hook 2.sh +0 -74
  214. package/src/scripts/nexo-install 2.py +0 -6
  215. package/src/scripts/nexo-learning-housekeep 2.py +0 -245
  216. package/src/scripts/nexo-learning-validator 2.py +0 -207
  217. package/src/scripts/nexo-migrate 2.py +0 -232
  218. package/src/scripts/nexo-postmortem-consolidator 2.py +0 -421
  219. package/src/scripts/nexo-pre-commit 2.py +0 -120
  220. package/src/scripts/nexo-prevent-sleep 2.sh +0 -29
  221. package/src/scripts/nexo-proactive-dashboard 2.py +0 -345
  222. package/src/scripts/nexo-reflection 2.py +0 -253
  223. package/src/scripts/nexo-runtime-preflight 2.py +0 -274
  224. package/src/scripts/nexo-send-email 2.py +0 -25
  225. package/src/scripts/nexo-send-email.py +0 -25
  226. package/src/scripts/nexo-send-reply 2.py +0 -178
  227. package/src/scripts/nexo-send-reply.py +0 -178
  228. package/src/scripts/nexo-sleep 2.py +0 -592
  229. package/src/scripts/nexo-snapshot-restore 2.sh +0 -35
  230. package/src/scripts/nexo-synthesis 2.py +0 -253
  231. package/src/scripts/nexo-tcc-approve 2.sh +0 -79
  232. package/src/scripts/nexo-update 2.sh +0 -161
  233. package/src/scripts/nexo-watchdog 2.sh +0 -878
  234. package/src/scripts/nexo-watchdog-smoke 2.py +0 -119
  235. package/src/server 2.py +0 -733
  236. package/src/storage_router 2.py +0 -32
  237. package/src/tools_coordination 2.py +0 -102
  238. package/src/tools_credentials 2.py +0 -68
  239. package/src/tools_learnings 2.py +0 -220
  240. package/src/tools_menu 2.py +0 -227
  241. package/src/tools_reminders 2.py +0 -86
  242. package/src/tools_reminders_crud 2.py +0 -159
  243. package/src/tools_sessions 2.py +0 -476
  244. package/src/tools_task_history 2.py +0 -57
  245. package/templates/CLAUDE.md 2.template +0 -63
  246. package/templates/openclaw 2.json +0 -13
  247. package/tests/__init__ 2.py +0 -0
  248. package/tests/__init__.py +0 -0
  249. package/tests/conftest 2.py +0 -71
  250. package/tests/conftest.py +0 -71
  251. package/tests/test_cognitive 2.py +0 -205
  252. package/tests/test_cognitive.py +0 -205
  253. package/tests/test_knowledge_graph 2.py +0 -140
  254. package/tests/test_knowledge_graph.py +0 -140
  255. package/tests/test_migrations 2.py +0 -137
  256. package/tests/test_migrations.py +0 -137
@@ -1,54 +0,0 @@
1
- """NEXO DB — Evolution module."""
2
- from db._core import get_db
3
-
4
- # ── Evolution helpers ─────────────────────────────────────────────────────
5
-
6
- def insert_evolution_metric(dimension: str, score: int, evidence: str, delta: int = 0):
7
- conn = get_db()
8
- conn.execute(
9
- "INSERT INTO evolution_metrics (dimension, score, evidence, delta) VALUES (?, ?, ?, ?)",
10
- (dimension, score, evidence, delta)
11
- )
12
-
13
-
14
- def get_latest_metrics() -> dict:
15
- conn = get_db()
16
- rows = conn.execute(
17
- "SELECT dimension, score, delta, measured_at FROM evolution_metrics "
18
- "WHERE id IN (SELECT MAX(id) FROM evolution_metrics GROUP BY dimension)"
19
- ).fetchall()
20
- return {r["dimension"]: dict(r) for r in rows}
21
-
22
-
23
- def insert_evolution_log(cycle_number: int, dimension: str, proposal: str,
24
- classification: str, reasoning: str, **kwargs) -> int:
25
- conn = get_db()
26
- cur = conn.execute(
27
- "INSERT INTO evolution_log (cycle_number, dimension, proposal, classification, reasoning, "
28
- "files_changed, snapshot_ref, test_result, status) "
29
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
30
- (cycle_number, dimension, proposal, classification, reasoning,
31
- kwargs.get("files_changed"), kwargs.get("snapshot_ref"),
32
- kwargs.get("test_result"), kwargs.get("status", "pending"))
33
- )
34
- return cur.lastrowid
35
-
36
-
37
- def get_evolution_history(limit: int = 20) -> list:
38
- conn = get_db()
39
- rows = conn.execute(
40
- "SELECT * FROM evolution_log ORDER BY id DESC LIMIT ?", (limit,)
41
- ).fetchall()
42
- return [dict(r) for r in rows]
43
-
44
-
45
- def update_evolution_log_status(log_id: int, status: str, **kwargs):
46
- conn = get_db()
47
- sets = ["status = ?"]
48
- vals = [status]
49
- for k in ("test_result", "impact", "files_changed", "snapshot_ref"):
50
- if k in kwargs:
51
- sets.append(f"{k} = ?")
52
- vals.append(kwargs[k])
53
- vals.append(log_id)
54
- conn.execute(f"UPDATE evolution_log SET {', '.join(sets)} WHERE id = ?", vals)
@@ -1,406 +0,0 @@
1
- """NEXO DB — Fts module."""
2
- import os, pathlib, sqlite3, threading, datetime
3
- from db._core import get_db, now_epoch, DB_PATH
4
-
5
- NEXO_HOME = os.environ.get("NEXO_HOME", os.path.expanduser("~/.nexo"))
6
-
7
- # ── FTS5 Unified Search ──────────────────────────────────────────
8
-
9
- # Directories to index for unified search
10
- _FTS_MD_DIRS = [
11
- os.path.join(NEXO_HOME, "docs"),
12
- os.path.join(NEXO_HOME, "projects"),
13
- os.path.join(NEXO_HOME, "memory"),
14
- os.path.join(NEXO_HOME, "operations"),
15
- os.path.join(NEXO_HOME, "learnings"),
16
- os.path.join(NEXO_HOME, "brain"),
17
- os.path.join(NEXO_HOME, "agents"),
18
- os.path.join(NEXO_HOME, "skills"),
19
- ]
20
- # Code repos: index source files (skip vendor, node_modules, etc.)
21
- _FTS_CODE_DIRS = [] # Users can add project dirs via nexo_index_add_dir
22
- _FTS_CODE_SKIP = {
23
- "vendor", "node_modules", ".git", "cache", "tmp", "logs", "uploads",
24
- "assets/img", "assets/fonts", ".next", "dist", "build", ".prisma",
25
- "public/build", ".turbo", "__pycache__",
26
- "coverage", ".nyc_output", "storage/framework", "bootstrap/cache",
27
- }
28
- _FTS_MAX_FILE_SIZE = 50_000 # skip .md files >50KB
29
- _FTS_MAX_CODE_FILE_SIZE = 30_000 # skip code files >30KB
30
-
31
- # Synonym map for cross-language search (ES <-> EN)
32
- _SYNONYMS = {
33
- "carrito": ["cart", "checkout"],
34
- "cart": ["carrito", "checkout"],
35
- "abandoned": ["abandonado"],
36
- "abandonado": ["abandoned"],
37
- "busqueda": ["search", "buscar"],
38
- "search": ["busqueda", "buscar"],
39
- "envio": ["shipping", "envío"],
40
- "shipping": ["envio", "envío"],
41
- "pedido": ["order", "orden"],
42
- "order": ["pedido", "orden"],
43
- "cliente": ["customer", "client"],
44
- "customer": ["cliente", "client"],
45
- "producto": ["product"],
46
- "product": ["producto"],
47
- "precio": ["price"],
48
- "price": ["precio"],
49
- "descuento": ["discount"],
50
- "discount": ["descuento"],
51
- "pago": ["payment"],
52
- "payment": ["pago"],
53
- "factura": ["invoice"],
54
- "invoice": ["factura"],
55
- "tienda": ["store", "shop"],
56
- "store": ["tienda", "shop"],
57
- "configuracion": ["config", "settings", "configuration"],
58
- "config": ["configuracion", "settings"],
59
- "permisos": ["permissions"],
60
- "permissions": ["permisos"],
61
- "mensaje": ["message"],
62
- "message": ["mensaje"],
63
- "plantilla": ["template"],
64
- "template": ["plantilla"],
65
- "webhook": ["gancho"],
66
- "cron": ["tarea programada", "scheduled"],
67
- "extension": ["extensión", "plugin", "addon"],
68
- "plugin": ["extension", "extensión"],
69
- }
70
-
71
-
72
- def _get_all_code_dirs(conn=None):
73
- """Return combined list of hardcoded + dynamic code dirs as [(path, [patterns])]."""
74
- if conn is None:
75
- conn = get_db()
76
- dirs = list(_FTS_CODE_DIRS)
77
- try:
78
- for r in conn.execute("SELECT path, patterns FROM fts_dirs WHERE dir_type = 'code'").fetchall():
79
- patterns = [p.strip() for p in r["patterns"].split(",") if p.strip()]
80
- dirs.append((r["path"], patterns))
81
- except Exception:
82
- pass
83
- return dirs
84
-
85
-
86
- def _get_all_md_dirs(conn=None):
87
- """Return combined list of hardcoded + dynamic md dirs."""
88
- if conn is None:
89
- conn = get_db()
90
- dirs = list(_FTS_MD_DIRS)
91
- try:
92
- for r in conn.execute("SELECT path FROM fts_dirs WHERE dir_type = 'md'").fetchall():
93
- dirs.append(r["path"])
94
- except Exception:
95
- pass
96
- return dirs
97
-
98
-
99
- def fts_add_dir(path: str, dir_type: str = 'code',
100
- patterns: str = '*.php,*.js,*.json,*.py,*.ts,*.tsx',
101
- notes: str = '') -> dict:
102
- """Register a directory for FTS indexing."""
103
- conn = get_db()
104
- path = os.path.expanduser(path)
105
- if not os.path.isdir(path):
106
- return {"error": f"Directory not found: {path}"}
107
- try:
108
- conn.execute(
109
- "INSERT OR REPLACE INTO fts_dirs (path, dir_type, patterns, added_at, notes) VALUES (?,?,?,?,?)",
110
- (path, dir_type, patterns, now_epoch(), notes)
111
- )
112
- conn.commit()
113
- return {"path": path, "dir_type": dir_type, "patterns": patterns}
114
- except Exception as e:
115
- return {"error": str(e)}
116
-
117
-
118
- def fts_remove_dir(path: str) -> dict:
119
- """Remove a directory from FTS indexing and clean up its entries."""
120
- conn = get_db()
121
- path = os.path.expanduser(path)
122
- deleted = conn.execute("DELETE FROM fts_dirs WHERE path = ?", (path,)).rowcount
123
- if deleted == 0:
124
- return {"error": f"Directory not registered: {path}"}
125
- # Remove indexed files from that directory
126
- conn.execute("DELETE FROM unified_search WHERE source IN ('file', 'code') AND source_id LIKE ?",
127
- (path + "%",))
128
- conn.commit()
129
- return {"removed": path}
130
-
131
-
132
- def fts_list_dirs() -> list[dict]:
133
- """List all registered FTS directories (hardcoded + dynamic)."""
134
- conn = get_db()
135
- result = []
136
- for d in _FTS_MD_DIRS:
137
- result.append({"path": d, "type": "md", "patterns": "*.md", "source": "builtin"})
138
- for d, pats in _FTS_CODE_DIRS:
139
- result.append({"path": d, "type": "code", "patterns": ",".join(pats), "source": "builtin"})
140
- try:
141
- for r in conn.execute("SELECT path, dir_type, patterns, notes FROM fts_dirs ORDER BY path").fetchall():
142
- result.append({"path": r["path"], "type": r["dir_type"], "patterns": r["patterns"],
143
- "source": "dynamic", "notes": r["notes"] or ""})
144
- except Exception:
145
- pass
146
- return result
147
-
148
-
149
- def _fs_indexing_enabled() -> bool:
150
- """Allow tests and smoke checks to disable expensive filesystem indexing."""
151
- return os.environ.get("NEXO_SKIP_FS_INDEX", "0") != "1"
152
-
153
-
154
- def rebuild_fts_index(conn=None):
155
- """Rebuild FTS5 index from all sources: SQLite tables + .md files."""
156
- if conn is None:
157
- conn = get_db()
158
- conn.execute("DELETE FROM unified_search")
159
-
160
- def _ins(source, source_id, title, body, category, updated_at):
161
- conn.execute(
162
- "INSERT INTO unified_search(source, source_id, title, body, category, updated_at) VALUES (?,?,?,?,?,?)",
163
- (source, str(source_id), str(title)[:200], body or '', category or '', str(updated_at or ''))
164
- )
165
-
166
- # 1. Learnings
167
- for r in conn.execute("SELECT id, category, title, content, reasoning, updated_at FROM learnings").fetchall():
168
- _ins("learning", r["id"], r["title"], f"{r['content']} {r['reasoning'] or ''}", r["category"], r["updated_at"])
169
-
170
- # 2. Decisions
171
- for r in conn.execute("SELECT id, domain, decision, alternatives, based_on, outcome, created_at FROM decisions").fetchall():
172
- body = f"{r['decision']} {r['alternatives'] or ''} {r['based_on'] or ''} {r['outcome'] or ''}"
173
- _ins("decision", r["id"], r["decision"][:200], body, r["domain"] or '', r["created_at"])
174
-
175
- # 3. Change log
176
- for r in conn.execute("SELECT id, files, what_changed, why, triggered_by, affects, risks, created_at FROM change_log").fetchall():
177
- body = f"{r['what_changed']} {r['why']} {r['triggered_by'] or ''} {r['affects'] or ''} {r['risks'] or ''}"
178
- _ins("change", r["id"], r["files"], body, "change_log", r["created_at"])
179
-
180
- # 4. Session diary
181
- for r in conn.execute("SELECT id, summary, decisions, discarded, pending, context_next, mental_state, domain, created_at FROM session_diary").fetchall():
182
- body = f"{r['summary']} {r['decisions'] or ''} {r['pending'] or ''} {r['context_next'] or ''} {r['mental_state'] or ''}"
183
- _ins("diary", r["id"], (r["summary"] or '')[:200], body, r["domain"] or "general", r["created_at"])
184
-
185
- # 5. Followups
186
- for r in conn.execute("SELECT id, description, verification, reasoning, updated_at FROM followups").fetchall():
187
- body = f"{r['description']} {r['verification'] or ''} {r['reasoning'] or ''}"
188
- _ins("followup", r["id"], r["id"], body, "followup", r["updated_at"])
189
-
190
- # 6. Entities
191
- for r in conn.execute("SELECT id, name, type, value, notes, updated_at FROM entities").fetchall():
192
- _ins("entity", r["id"], r["name"], f"{r['name']} {r['value']} {r['notes'] or ''}", r["type"] or "general", r["updated_at"])
193
-
194
- if _fs_indexing_enabled():
195
- # 7. .md files from key directories (hardcoded + dynamic)
196
- for dir_path in _get_all_md_dirs(conn):
197
- p = pathlib.Path(dir_path)
198
- if not p.exists():
199
- continue
200
- for md_file in p.rglob("*.md"):
201
- try:
202
- if md_file.stat().st_size > _FTS_MAX_FILE_SIZE:
203
- continue
204
- content = md_file.read_text(encoding="utf-8", errors="ignore")
205
- category = md_file.parent.name or "docs"
206
- _ins("file", str(md_file), md_file.stem, content, category, md_file.stat().st_mtime)
207
- except Exception:
208
- continue
209
-
210
- # 8. Code files from project repos (hardcoded + dynamic)
211
- for dir_path, patterns in _get_all_code_dirs(conn):
212
- p = pathlib.Path(dir_path)
213
- if not p.exists():
214
- continue
215
- for pattern in patterns:
216
- for code_file in p.rglob(pattern):
217
- # Skip excluded directories
218
- if any(skip in code_file.parts for skip in _FTS_CODE_SKIP):
219
- continue
220
- try:
221
- if code_file.stat().st_size > _FTS_MAX_CODE_FILE_SIZE:
222
- continue
223
- content = code_file.read_text(encoding="utf-8", errors="ignore")
224
- # Use relative path from repo root as category
225
- rel_parts = code_file.relative_to(p).parts
226
- category = rel_parts[0] if rel_parts else "code"
227
- _ins("code", str(code_file), code_file.name, content, category, code_file.stat().st_mtime)
228
- except Exception:
229
- continue
230
-
231
- conn.commit()
232
-
233
-
234
- def _refresh_fts_files(conn=None):
235
- """Refresh file + code entries in FTS index — add new, update modified, remove deleted."""
236
- if conn is None:
237
- conn = get_db()
238
-
239
- if not _fs_indexing_enabled():
240
- conn.execute("DELETE FROM unified_search WHERE source IN ('file', 'code')")
241
- conn.commit()
242
- return
243
-
244
- # Get currently indexed files with their mtime (both 'file' and 'code' sources)
245
- indexed = {}
246
- for r in conn.execute("SELECT source, source_id, updated_at FROM unified_search WHERE source IN ('file', 'code')").fetchall():
247
- indexed[r[1]] = (r[0], r[2])
248
-
249
- current_files = set()
250
-
251
- # Scan .md files (hardcoded + dynamic)
252
- for dir_path in _get_all_md_dirs(conn):
253
- p = pathlib.Path(dir_path)
254
- if not p.exists():
255
- continue
256
- for md_file in p.rglob("*.md"):
257
- try:
258
- if md_file.stat().st_size > _FTS_MAX_FILE_SIZE:
259
- continue
260
- fpath = str(md_file)
261
- current_files.add(fpath)
262
- mtime = md_file.stat().st_mtime
263
- old = indexed.get(fpath)
264
- if old is None or str(mtime) != str(old[1]):
265
- content = md_file.read_text(encoding="utf-8", errors="ignore")
266
- category = md_file.parent.name or "docs"
267
- conn.execute("DELETE FROM unified_search WHERE source_id = ?", (fpath,))
268
- conn.execute(
269
- "INSERT INTO unified_search(source, source_id, title, body, category, updated_at) VALUES (?,?,?,?,?,?)",
270
- ("file", fpath, md_file.stem, content, category, str(mtime))
271
- )
272
- except Exception:
273
- continue
274
-
275
- # Scan code files (hardcoded + dynamic)
276
- for dir_path, patterns in _get_all_code_dirs(conn):
277
- p = pathlib.Path(dir_path)
278
- if not p.exists():
279
- continue
280
- for pattern in patterns:
281
- for code_file in p.rglob(pattern):
282
- if any(skip in code_file.parts for skip in _FTS_CODE_SKIP):
283
- continue
284
- try:
285
- if code_file.stat().st_size > _FTS_MAX_CODE_FILE_SIZE:
286
- continue
287
- fpath = str(code_file)
288
- current_files.add(fpath)
289
- mtime = code_file.stat().st_mtime
290
- old = indexed.get(fpath)
291
- if old is None or str(mtime) != str(old[1]):
292
- content = code_file.read_text(encoding="utf-8", errors="ignore")
293
- rel_parts = code_file.relative_to(p).parts
294
- category = rel_parts[0] if rel_parts else "code"
295
- conn.execute("DELETE FROM unified_search WHERE source_id = ?", (fpath,))
296
- conn.execute(
297
- "INSERT INTO unified_search(source, source_id, title, body, category, updated_at) VALUES (?,?,?,?,?,?)",
298
- ("code", fpath, code_file.name, content, category, str(mtime))
299
- )
300
- except Exception:
301
- continue
302
-
303
- # Remove deleted files
304
- for fpath, (source, _) in indexed.items():
305
- if fpath not in current_files:
306
- conn.execute("DELETE FROM unified_search WHERE source_id = ?", (fpath,))
307
-
308
- conn.commit()
309
-
310
-
311
- def _expand_synonyms(words: list[str]) -> list[str]:
312
- """Expand search words with synonyms for cross-language matching."""
313
- expanded = set(words)
314
- for w in words:
315
- w_lower = w.lower()
316
- if w_lower in _SYNONYMS:
317
- expanded.update(_SYNONYMS[w_lower])
318
- return list(expanded)
319
-
320
-
321
- def fts_search(query: str, source_filter: str = None, limit: int = 20) -> list[dict]:
322
- """Search unified FTS5 index. Returns ranked results.
323
-
324
- Args:
325
- query: Search text (supports FTS5 syntax: "exact phrase", word*)
326
- source_filter: Optional filter by source (learning, decision, change, diary, followup, entity, file, code)
327
- limit: Max results (default 20)
328
- """
329
- conn = get_db()
330
- words = query.strip().split()
331
- if not words:
332
- return []
333
-
334
- # Expand with synonyms for cross-language matching
335
- all_words = _expand_synonyms(words)
336
-
337
- # Build FTS5 query: each word as quoted term with OR for broad matching
338
- fts_terms = []
339
- for w in all_words:
340
- # Strip FTS5 special chars to avoid syntax errors
341
- safe = w.replace('"', '').replace("'", '').replace('*', '').replace('^', '').replace('-', ' ').strip()
342
- if not safe:
343
- continue
344
- # Split on dots (e.g., "capabilities.json" → "capabilities" + "json")
345
- parts = [p.strip() for p in safe.split('.') if p.strip()]
346
- for part in parts:
347
- fts_terms.append(f'"{part}"')
348
- # Add prefix search for camelCase/code identifiers (contains uppercase mid-word)
349
- if any(c.isupper() for c in part[1:]) or '_' in part:
350
- fts_terms.append(f'{part}*')
351
- if not fts_terms:
352
- return []
353
- fts_query = " OR ".join(fts_terms)
354
-
355
- where_extra = ""
356
- params = [fts_query]
357
- if source_filter:
358
- where_extra = "AND source = ?"
359
- params.append(source_filter)
360
- params.append(limit)
361
-
362
- try:
363
- rows = conn.execute(f"""
364
- SELECT source, source_id, title,
365
- snippet(unified_search, 3, '»', '«', '...', 40) AS snippet,
366
- category, updated_at, rank
367
- FROM unified_search
368
- WHERE unified_search MATCH ? {where_extra}
369
- ORDER BY rank
370
- LIMIT ?
371
- """, params).fetchall()
372
- return [dict(r) for r in rows]
373
- except Exception:
374
- return []
375
-
376
-
377
- def fts_upsert(source: str, source_id: str, title: str, body: str, category: str = '', commit: bool = True):
378
- """Add or update a single entry in the FTS index."""
379
- conn = get_db()
380
- conn.execute("DELETE FROM unified_search WHERE source = ? AND source_id = ?", (source, str(source_id)))
381
- conn.execute(
382
- "INSERT INTO unified_search(source, source_id, title, body, category, updated_at) VALUES (?,?,?,?,?,?)",
383
- (source, str(source_id), str(title)[:200], body or '', category or '', datetime.datetime.now().isoformat())
384
- )
385
- if commit:
386
- conn.commit()
387
-
388
-
389
- def _migrate_add_column(conn, table: str, column: str, col_type: str):
390
- """Add column if it doesn't exist (idempotent)."""
391
- try:
392
- conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {col_type}")
393
- conn.commit()
394
- except sqlite3.OperationalError as e:
395
- if "duplicate column" in str(e).lower():
396
- pass
397
- else:
398
- raise
399
-
400
-
401
- def _migrate_add_index(conn, index_name: str, table: str, column: str):
402
- """Create index if it doesn't exist (idempotent)."""
403
- conn.execute(f"CREATE INDEX IF NOT EXISTS {index_name} ON {table}({column})")
404
- conn.commit()
405
-
406
-
@@ -1,168 +0,0 @@
1
- """NEXO DB — Learnings module."""
2
- import re, time
3
- from db._core import get_db, now_epoch
4
- from db._fts import fts_upsert, fts_search
5
-
6
- # ── Learnings ──────────────────────────────────────────────────────
7
-
8
- def create_learning(
9
- category: str,
10
- title: str,
11
- content: str,
12
- reasoning: str = '',
13
- prevention: str = '',
14
- applies_to: str = '',
15
- status: str = 'active',
16
- review_due_at: float | None = None,
17
- last_reviewed_at: float | None = None,
18
- ) -> dict:
19
- """Create a new learning entry with optional reasoning."""
20
- conn = get_db()
21
- now = now_epoch()
22
- cursor = conn.execute(
23
- "INSERT INTO learnings "
24
- "(category, title, content, reasoning, prevention, applies_to, status, review_due_at, last_reviewed_at, created_at, updated_at) "
25
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
26
- (
27
- category, title, content, reasoning, prevention, applies_to,
28
- status, review_due_at, last_reviewed_at, now, now,
29
- )
30
- )
31
- conn.commit()
32
- lid = cursor.lastrowid
33
- fts_upsert("learning", str(lid), title, f"{content} {reasoning or ''}", category, commit=False)
34
- row = conn.execute("SELECT * FROM learnings WHERE id = ?", (lid,)).fetchone()
35
- return dict(row)
36
-
37
-
38
- def update_learning(id: int, **kwargs) -> dict:
39
- """Update any fields of a learning: category, title, content, reasoning."""
40
- conn = get_db()
41
- row = conn.execute("SELECT * FROM learnings WHERE id = ?", (id,)).fetchone()
42
- if not row:
43
- return {"error": f"Learning {id} not found"}
44
- allowed = {
45
- "category", "title", "content", "reasoning", "prevention",
46
- "applies_to", "status", "review_due_at", "last_reviewed_at",
47
- }
48
- updates = {k: v for k, v in kwargs.items() if k in allowed}
49
- if not updates:
50
- return dict(row)
51
- updates["updated_at"] = now_epoch()
52
- set_clause = ", ".join(f"{k} = ?" for k in updates)
53
- values = list(updates.values()) + [id]
54
- conn.execute(f"UPDATE learnings SET {set_clause} WHERE id = ?", values)
55
- conn.commit()
56
- row = conn.execute("SELECT * FROM learnings WHERE id = ?", (id,)).fetchone()
57
- r = dict(row)
58
- fts_upsert("learning", str(id), r.get("title", ""), f"{r.get('content', '')} {r.get('reasoning', '')}", r.get("category", ""), commit=False)
59
- return r
60
-
61
-
62
- def delete_learning(id: int) -> bool:
63
- """Delete a learning entry."""
64
- conn = get_db()
65
- result = conn.execute("DELETE FROM learnings WHERE id = ?", (id,))
66
- conn.execute("DELETE FROM unified_search WHERE source = 'learning' AND source_id = ?", (str(id),))
67
- conn.commit()
68
- deleted = result.rowcount > 0
69
- return deleted
70
-
71
-
72
- def search_learnings(query: str, category: str = None) -> list[dict]:
73
- """Search learnings using FTS5 for ranked results. Falls back to LIKE if FTS fails."""
74
- # Try FTS5 first
75
- fts_results = fts_search(query, source_filter="learning", limit=30)
76
- if fts_results:
77
- conn = get_db()
78
- ids = [int(r['source_id']) for r in fts_results]
79
- placeholders = ','.join('?' * len(ids))
80
- rows = conn.execute(
81
- f"SELECT * FROM learnings WHERE id IN ({placeholders}) ORDER BY updated_at DESC",
82
- ids
83
- ).fetchall()
84
- filtered = [dict(r) for r in rows]
85
- if category:
86
- filtered = [r for r in filtered if r.get('category') == category]
87
- return filtered
88
-
89
- # Fallback to LIKE
90
- conn = get_db()
91
- words = query.strip().split()
92
- if not words:
93
- return []
94
- conditions = []
95
- params = []
96
- for word in words:
97
- pattern = f"%{word}%"
98
- conditions.append("(title LIKE ? OR content LIKE ? OR reasoning LIKE ? OR prevention LIKE ?)")
99
- params.extend([pattern, pattern, pattern, pattern])
100
- where = " AND ".join(conditions)
101
- if category:
102
- where = f"category = ? AND ({where})"
103
- params.insert(0, category)
104
- rows = conn.execute(
105
- f"SELECT * FROM learnings WHERE {where} ORDER BY updated_at DESC",
106
- params
107
- ).fetchall()
108
- return [dict(r) for r in rows]
109
-
110
-
111
- def list_learnings(category: str = None) -> list[dict]:
112
- """List all learnings, optionally filtered by category."""
113
- conn = get_db()
114
- if category:
115
- rows = conn.execute(
116
- "SELECT * FROM learnings WHERE category = ? ORDER BY updated_at DESC",
117
- (category,)
118
- ).fetchall()
119
- else:
120
- rows = conn.execute(
121
- "SELECT * FROM learnings ORDER BY category ASC, updated_at DESC"
122
- ).fetchall()
123
- return [dict(r) for r in rows]
124
-
125
-
126
- def extract_keywords(text: str) -> list[str]:
127
- """Extract meaningful keywords from text for similarity matching."""
128
- import re
129
- stop = {'the', 'a', 'an', 'is', 'was', 'are', 'were', 'be', 'been', 'being',
130
- 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',
131
- 'should', 'may', 'might', 'can', 'shall', 'to', 'of', 'in', 'for',
132
- 'on', 'with', 'at', 'by', 'from', 'as', 'into', 'through', 'during',
133
- 'before', 'after', 'above', 'below', 'between', 'out', 'off', 'over',
134
- 'under', 'again', 'further', 'then', 'once', 'and', 'but', 'or', 'nor',
135
- 'not', 'so', 'yet', 'both', 'either', 'neither', 'each', 'every', 'all',
136
- 'any', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'only',
137
- 'own', 'same', 'than', 'too', 'very', 'just', 'que', 'de', 'en', 'la',
138
- 'el', 'los', 'las', 'un', 'una', 'por', 'con', 'para', 'del', 'al',
139
- 'es', 'se', 'no', 'si', 'como', 'pero', 'su', 'ya', 'esto', 'esta'}
140
- words = re.findall(r'[a-zA-Z0-9_]+', text.lower())
141
- return [w for w in words if len(w) > 2 and w not in stop]
142
-
143
-
144
- def find_similar_learnings(new_id: int, title: str, content: str, category: str) -> list[tuple[int, float]]:
145
- """Find learnings similar to the given one based on keyword overlap.
146
- Returns list of (learning_id, similarity_score) tuples for matches > 0.3."""
147
- keywords_new = set(extract_keywords(f"{title} {content}"))
148
- if not keywords_new:
149
- return []
150
- conn = get_db()
151
- rows = conn.execute(
152
- "SELECT id, title, content FROM learnings WHERE category = ? AND id != ?",
153
- (category, new_id)
154
- ).fetchall()
155
- results = []
156
- for row in rows:
157
- keywords_existing = set(extract_keywords(f"{row['title']} {row['content']}"))
158
- if not keywords_existing:
159
- continue
160
- overlap = keywords_new & keywords_existing
161
- union = keywords_new | keywords_existing
162
- similarity = len(overlap) / len(union) if union else 0
163
- if similarity > 0.3:
164
- results.append((row['id'], round(similarity, 2)))
165
- results.sort(key=lambda x: x[1], reverse=True)
166
- return results[:5]
167
-
168
-