nexo-brain 5.3.13 → 5.3.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/bin/nexo-brain.js +52 -1
- package/package.json +1 -1
- package/src/crons/sync.py +18 -4
- package/src/dashboard/static/favicon 2.svg +32 -0
- package/src/dashboard/static/nexo-logo 2.png +0 -0
- package/src/dashboard/static/nexo-logo 2.svg +40 -0
- package/src/dashboard/static/style 2.css +2458 -0
- package/src/dashboard/templates/adaptive 2.html +118 -0
- package/src/dashboard/templates/artifacts 2.html +133 -0
- package/src/dashboard/templates/backups 2.html +136 -0
- package/src/dashboard/templates/base 2.html +417 -0
- package/src/dashboard/templates/calendar 2.html +591 -0
- package/src/dashboard/templates/chat 2.html +356 -0
- package/src/dashboard/templates/claims 2.html +259 -0
- package/src/dashboard/templates/cortex 2.html +321 -0
- package/src/dashboard/templates/credentials 2.html +128 -0
- package/src/dashboard/templates/crons 2.html +370 -0
- package/src/dashboard/templates/dashboard 2.html +494 -0
- package/src/dashboard/templates/dreams 2.html +252 -0
- package/src/dashboard/templates/email 2.html +160 -0
- package/src/dashboard/templates/evolution 2.html +189 -0
- package/src/dashboard/templates/feed 2.html +249 -0
- package/src/dashboard/templates/followup_health 2.html +170 -0
- package/src/dashboard/templates/graph 2.html +201 -0
- package/src/dashboard/templates/guard 2.html +259 -0
- package/src/dashboard/templates/inbox 2.html +251 -0
- package/src/dashboard/templates/memory 2.html +420 -0
- package/src/dashboard/templates/operations 2.html +608 -0
- package/src/dashboard/templates/plugins 2.html +185 -0
- package/src/dashboard/templates/protocol 2.html +199 -0
- package/src/dashboard/templates/rules 2.html +246 -0
- package/src/dashboard/templates/sentiment 2.html +247 -0
- package/src/dashboard/templates/sessions 2.html +218 -0
- package/src/dashboard/templates/skills 2.html +329 -0
- package/src/dashboard/templates/somatic 2.html +73 -0
- package/src/dashboard/templates/triggers 2.html +133 -0
- package/src/dashboard/templates/trust 2.html +360 -0
- package/src/db/__init__ 2.py +259 -0
- package/src/db/_core 2.py +437 -0
- package/src/db/_credentials 2.py +124 -0
- package/src/db/_entities.py +1 -1
- package/src/db/_episodic 2.py +762 -0
- package/src/db/_evolution 2.py +54 -0
- package/src/db/_fts 2.py +406 -0
- package/src/db/_goal_profiles 2.py +376 -0
- package/src/db/_hot_context 2.py +660 -0
- package/src/db/_outcomes 2.py +800 -0
- package/src/db/_personal_scripts 2.py +582 -0
- package/src/db/_sessions 2.py +330 -0
- package/src/db/_tasks 2.py +91 -0
- package/src/db/_watchers 2.py +173 -0
- package/src/doctor/formatters 2.py +52 -0
- package/src/doctor/models 2.py +69 -0
- package/src/doctor/planes 2.py +87 -0
- package/src/doctor/providers/__init__ 2.py +1 -0
- package/src/doctor/providers/deep 2.py +367 -0
- package/src/evolution_cycle 2.py +519 -0
- package/src/hooks/auto_capture 2.py +208 -0
- package/src/hooks/caffeinate-guard 2.sh +8 -0
- package/src/hooks/capture-session 2.sh +21 -0
- package/src/hooks/capture-tool-logs 2.sh +158 -0
- package/src/hooks/daily-briefing-check 2.sh +33 -0
- package/src/hooks/heartbeat-enforcement 2.py +90 -0
- package/src/hooks/heartbeat-posttool 2.sh +18 -0
- package/src/hooks/inbox-hook 2.sh +76 -0
- package/src/hooks/post-compact 2.sh +152 -0
- package/src/hooks/pre-compact 2.sh +169 -0
- package/src/hooks/protocol-guardrail 2.sh +10 -0
- package/src/hooks/protocol-pretool-guardrail 2.sh +9 -0
- package/src/hooks/session-stop 2.sh +52 -0
- package/src/kg_populate 2.py +292 -0
- package/src/maintenance 2.py +53 -0
- package/src/memory_backends 2.py +71 -0
- package/src/migrate_embeddings 2.py +124 -0
- package/src/nexo_sdk 2.py +103 -0
- package/src/observability 2.py +199 -0
- package/src/plugin_loader 2.py +217 -0
- package/src/plugins/__init__ 2.py +0 -0
- package/src/plugins/agents.py +10 -3
- package/src/plugins/artifact_registry 2.py +450 -0
- package/src/plugins/backup 2.py +127 -0
- package/src/plugins/claims_tools 2.py +119 -0
- package/src/plugins/cognitive_memory 2.py +609 -0
- package/src/plugins/core_rules 2.py +252 -0
- package/src/plugins/cortex 2.py +1155 -0
- package/src/plugins/entities 2.py +67 -0
- package/src/plugins/episodic_memory 2.py +560 -0
- package/src/plugins/evolution 2.py +167 -0
- package/src/plugins/goal_engine 2.py +142 -0
- package/src/plugins/guard 2.py +862 -0
- package/src/plugins/impact 2.py +29 -0
- package/src/plugins/knowledge_graph_tools 2.py +137 -0
- package/src/plugins/media_memory_tools 2.py +98 -0
- package/src/plugins/memory_export 2.py +196 -0
- package/src/plugins/outcomes 2.py +130 -0
- package/src/plugins/personal_scripts 2.py +117 -0
- package/src/plugins/preferences 2.py +47 -0
- package/src/plugins/protocol 2.py +1449 -0
- package/src/plugins/schedule.py +2 -1
- package/src/plugins/simple_api 2.py +106 -0
- package/src/plugins/skills 2.py +341 -0
- package/src/plugins/state_watchers 2.py +79 -0
- package/src/plugins/update 2.py +986 -0
- package/src/plugins/user_state_tools 2.py +43 -0
- package/src/plugins/workflow 2.py +588 -0
- package/src/protocol_settings 2.py +59 -0
- package/src/public_contribution 2.py +466 -0
- package/src/public_evolution_queue 2.py +241 -0
- package/src/requirements 2.txt +14 -0
- package/src/requirements.txt +1 -1
- package/src/retroactive_learnings 2.py +373 -0
- package/src/rules/__init__ 2.py +0 -0
- package/src/rules/core-rules 2.json +331 -0
- package/src/rules/migrate 2.py +207 -0
- package/src/runtime_power 2.py +874 -0
- package/src/runtime_power.py +18 -1
- package/src/script_registry 2.py +1559 -0
- package/src/scripts/check-context 2.py +272 -0
- package/src/scripts/deep-sleep/apply_findings 2.py +2327 -0
- package/src/scripts/deep-sleep/collect 2.py +928 -0
- package/src/scripts/deep-sleep/extract 2.py +330 -0
- package/src/scripts/deep-sleep/extract-prompt 2.md +285 -0
- package/src/scripts/deep-sleep/synthesize 2.py +312 -0
- package/src/scripts/deep-sleep/synthesize-prompt 2.md +336 -0
- package/src/scripts/nexo-agent-run 2.py +75 -0
- package/src/scripts/nexo-auto-update 2.py +6 -0
- package/src/scripts/nexo-backup 2.sh +25 -0
- package/src/scripts/nexo-brain-activation 2.sh +140 -0
- package/src/scripts/nexo-catchup 2.py +300 -0
- package/src/scripts/nexo-cognitive-decay 2.py +257 -0
- package/src/scripts/nexo-cortex-cycle 2.py +293 -0
- package/src/scripts/nexo-cron-wrapper 2.sh +53 -0
- package/src/scripts/nexo-cron-wrapper.sh +7 -0
- package/src/scripts/nexo-daily-self-audit 2.py +2161 -0
- package/src/scripts/nexo-dashboard 2.sh +29 -0
- package/src/scripts/nexo-deep-sleep 2.sh +86 -0
- package/src/scripts/nexo-evolution-run 2.py +1664 -0
- package/src/scripts/nexo-followup-hygiene 2.py +139 -0
- package/src/scripts/nexo-hook-record 2.py +42 -0
- package/src/scripts/nexo-immune 2.py +936 -0
- package/src/scripts/nexo-impact-scorer 2.py +117 -0
- package/src/scripts/nexo-inbox-hook 2.sh +74 -0
- package/src/scripts/nexo-install 2.py +6 -0
- package/src/scripts/nexo-learning-housekeep 2.py +401 -0
- package/src/scripts/nexo-learning-validator 2.py +266 -0
- package/src/scripts/nexo-migrate 2.py +260 -0
- package/src/scripts/nexo-outcome-checker 2.py +127 -0
- package/src/scripts/nexo-postmortem-consolidator 2.py +456 -0
- package/src/scripts/nexo-pre-commit 2.py +120 -0
- package/src/scripts/nexo-prevent-sleep 2.sh +35 -0
- package/src/scripts/nexo-proactive-dashboard 2.py +354 -0
- package/src/scripts/nexo-reflection 2.py +256 -0
- package/src/scripts/nexo-runtime-preflight 2.py +274 -0
- package/src/scripts/nexo-sleep 2.py +631 -0
- package/src/scripts/nexo-snapshot-restore 2.sh +35 -0
- package/src/scripts/nexo-sync-clients 2.py +16 -0
- package/src/scripts/nexo-synthesis 2.py +475 -0
- package/src/scripts/nexo-tcc-approve 2.sh +79 -0
- package/src/scripts/nexo-update 2.sh +306 -0
- package/src/scripts/nexo-watchdog 2.sh +1207 -0
- package/src/scripts/nexo-watchdog-smoke 2.py +119 -0
- package/src/scripts/rehydrate_learnings_from_archive 2.py +245 -0
- package/src/server 2.py +1296 -0
- package/src/skills/run-nexo-audit-phase/guide 2.md +43 -0
- package/src/skills/run-nexo-audit-phase/skill 2.json +59 -0
- package/src/skills/run-nexo-core-fix-cycle/guide 2.md +17 -0
- package/src/skills/run-nexo-core-fix-cycle/script 2.py +276 -0
- package/src/skills/run-nexo-core-fix-cycle/skill 2.json +58 -0
- package/src/skills/run-release-final-audit/guide 2.md +16 -0
- package/src/skills/run-release-final-audit/script 2.py +259 -0
- package/src/skills/run-release-final-audit/skill 2.json +77 -0
- package/src/skills/run-runtime-doctor/guide 2.md +12 -0
- package/src/skills/run-runtime-doctor/script 2.py +21 -0
- package/src/skills/run-runtime-doctor/skill 2.json +25 -0
- package/src/skills_runtime 2.py +932 -0
- package/src/state_watchers_runtime 2.py +475 -0
- package/src/storage_router 2.py +32 -0
- package/src/system_catalog 2.py +786 -0
- package/src/tools_coordination 2.py +103 -0
- package/src/tools_credentials 2.py +68 -0
- package/src/tools_drive 2.py +487 -0
- package/src/tools_hot_context 2.py +163 -0
- package/src/tools_learnings 2.py +612 -0
- package/src/tools_menu 2.py +229 -0
- package/src/tools_reminders 2.py +88 -0
- package/src/tools_reminders_crud 2.py +363 -0
- package/src/tools_sessions 2.py +1054 -0
- package/src/tools_system_catalog 2.py +19 -0
- package/src/tools_task_history 2.py +57 -0
- package/src/tools_transcripts 2.py +98 -0
- package/src/transcript_utils 2.py +412 -0
- package/src/user_context 2.py +46 -0
- package/src/user_data_portability 2.py +328 -0
- package/src/user_state_model 2.py +170 -0
- package/templates/CLAUDE.md 2.template +108 -0
- package/templates/CODEX.AGENTS.md 2.template +66 -0
- package/templates/launchagents/README 2.md +132 -0
- package/templates/launchagents/com.nexo.auto-close-sessions 2.plist +39 -0
- package/templates/launchagents/com.nexo.auto-close-sessions.plist +1 -1
- package/templates/launchagents/com.nexo.catchup 2.plist +39 -0
- package/templates/launchagents/com.nexo.catchup.plist +1 -1
- package/templates/launchagents/com.nexo.cognitive-decay 2.plist +40 -0
- package/templates/launchagents/com.nexo.dashboard 2.plist +43 -0
- package/templates/launchagents/com.nexo.dashboard.plist +1 -1
- package/templates/launchagents/com.nexo.deep-sleep 2.plist +43 -0
- package/templates/launchagents/com.nexo.deep-sleep.plist +1 -1
- package/templates/launchagents/com.nexo.evolution 2.plist +44 -0
- package/templates/launchagents/com.nexo.evolution.plist +1 -1
- package/templates/launchagents/com.nexo.followup-hygiene 2.plist +45 -0
- package/templates/launchagents/com.nexo.followup-hygiene.plist +1 -1
- package/templates/launchagents/com.nexo.immune 2.plist +41 -0
- package/templates/launchagents/com.nexo.immune.plist +1 -1
- package/templates/launchagents/com.nexo.postmortem 2.plist +45 -0
- package/templates/launchagents/com.nexo.postmortem.plist +1 -1
- package/templates/launchagents/com.nexo.self-audit 2.plist +47 -0
- package/templates/launchagents/com.nexo.self-audit.plist +1 -1
- package/templates/launchagents/com.nexo.synthesis 2.plist +45 -0
- package/templates/launchagents/com.nexo.synthesis.plist +1 -1
- package/templates/launchagents/com.nexo.watchdog 2.plist +37 -0
- package/templates/launchagents/com.nexo.watchdog.plist +1 -1
- package/templates/nexo_helper 2.py +301 -0
- package/templates/openclaw 2.json +13 -0
- package/templates/plugin-template 2.py +40 -0
- package/templates/script-template 2.py +59 -0
- package/templates/script-template 2.sh +13 -0
- package/templates/script-template.py +5 -4
- package/templates/skill-script-template 2.py +48 -0
- package/templates/skill-script-template.py +2 -1
- package/templates/skill-template 2.md +33 -0
|
@@ -0,0 +1,54 @@
|
|
|
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)
|
package/src/db/_fts 2.py
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
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
|
+
|