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,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
-