nexo-brain 2.3.0 → 2.3.2
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/README.md +1 -1
- package/bin/nexo-brain.js +92 -9
- package/bin/postinstall.js +22 -15
- package/package.json +7 -4
- package/src/auto_update.py +194 -5
- package/src/crons/sync.py +6 -2
- package/src/db/_core.py +1 -0
- package/src/db/_entities.py +1 -0
- package/src/db/_episodic.py +1 -0
- package/src/db/_learnings.py +1 -0
- package/src/db/_reminders.py +1 -0
- package/src/db/_schema.py +11 -1
- package/src/db/_sessions.py +1 -0
- package/src/db/_skills.py +1 -0
- package/src/hooks/capture-tool-logs.sh +23 -6
- package/src/hooks/session-start.sh +4 -3
- package/src/plugin_loader.py +1 -0
- package/src/plugins/update.py +377 -26
- package/src/scripts/deep-sleep/apply_findings.py +1 -0
- package/src/scripts/deep-sleep/collect.py +1 -0
- package/src/scripts/deep-sleep/extract.py +1 -0
- package/src/scripts/deep-sleep/synthesize.py +1 -0
- package/src/scripts/nexo-catchup.py +29 -4
- package/src/scripts/nexo-daily-self-audit.py +21 -1
- package/src/scripts/nexo-evolution-run.py +21 -1
- package/src/scripts/nexo-learning-housekeep.py +1 -0
- package/src/scripts/nexo-postmortem-consolidator.py +34 -9
- package/src/scripts/nexo-sleep.py +32 -10
- package/src/scripts/nexo-synthesis.py +29 -9
- package/src/scripts/nexo-update.sh +109 -7
- package/src/scripts/nexo-watchdog.sh +122 -58
- package/src/server.py +66 -1
- package/src/tools_coordination.py +1 -0
- package/src/tools_sessions.py +1 -0
- package/scripts/migrate-to-unified 2.sh +0 -813
- package/scripts/migrate-to-unified.sh +0 -813
- package/scripts/migrate-v1.5-to-v1.6 2.py +0 -778
- package/scripts/migrate-v1.5-to-v1.6.py +0 -778
- package/scripts/migrate-v1.7-to-v1.8 2.py +0 -214
- package/scripts/migrate-v1.7-to-v1.8.py +0 -214
- package/scripts/nexo-preflight.sh +0 -236
- package/scripts/pre-commit-check 2.sh +0 -55
- package/scripts/pre-commit-check.sh +0 -55
- package/src/__pycache__/auto_close_sessions.cpython-314.pyc +0 -0
- package/src/__pycache__/auto_update.cpython-310.pyc +0 -0
- package/src/__pycache__/hnsw_index.cpython-310.pyc +0 -0
- package/src/__pycache__/hnsw_index.cpython-314.pyc +0 -0
- package/src/__pycache__/kg_populate.cpython-310.pyc +0 -0
- package/src/__pycache__/knowledge_graph.cpython-310.pyc +0 -0
- package/src/__pycache__/plugin_loader.cpython-310.pyc +0 -0
- package/src/__pycache__/plugin_loader.cpython-314.pyc +0 -0
- package/src/__pycache__/tools_coordination.cpython-310.pyc +0 -0
- package/src/__pycache__/tools_credentials.cpython-310.pyc +0 -0
- package/src/__pycache__/tools_learnings.cpython-310.pyc +0 -0
- package/src/__pycache__/tools_menu.cpython-310.pyc +0 -0
- package/src/__pycache__/tools_reminders.cpython-310.pyc +0 -0
- package/src/__pycache__/tools_reminders_crud.cpython-310.pyc +0 -0
- package/src/__pycache__/tools_sessions.cpython-310.pyc +0 -0
- package/src/__pycache__/tools_task_history.cpython-310.pyc +0 -0
- package/src/auto_close_sessions 2.py +0 -159
- package/src/auto_update 2.py +0 -634
- package/src/claim_graph 2.py +0 -323
- package/src/cognitive/__init__ 2.py +0 -62
- package/src/cognitive/__pycache__/__init__.cpython-310.pyc +0 -0
- package/src/cognitive/__pycache__/__init__.cpython-312.pyc +0 -0
- package/src/cognitive/__pycache__/__init__.cpython-314.pyc +0 -0
- package/src/cognitive/__pycache__/_core.cpython-310.pyc +0 -0
- package/src/cognitive/__pycache__/_core.cpython-312.pyc +0 -0
- package/src/cognitive/__pycache__/_core.cpython-314.pyc +0 -0
- package/src/cognitive/__pycache__/_decay.cpython-310.pyc +0 -0
- package/src/cognitive/__pycache__/_decay.cpython-312.pyc +0 -0
- package/src/cognitive/__pycache__/_decay.cpython-314.pyc +0 -0
- package/src/cognitive/__pycache__/_ingest.cpython-310.pyc +0 -0
- package/src/cognitive/__pycache__/_ingest.cpython-312.pyc +0 -0
- package/src/cognitive/__pycache__/_ingest.cpython-314.pyc +0 -0
- package/src/cognitive/__pycache__/_memory.cpython-310.pyc +0 -0
- package/src/cognitive/__pycache__/_memory.cpython-312.pyc +0 -0
- package/src/cognitive/__pycache__/_memory.cpython-314.pyc +0 -0
- package/src/cognitive/__pycache__/_search.cpython-310.pyc +0 -0
- package/src/cognitive/__pycache__/_search.cpython-312.pyc +0 -0
- package/src/cognitive/__pycache__/_search.cpython-314.pyc +0 -0
- package/src/cognitive/__pycache__/_trust.cpython-310.pyc +0 -0
- package/src/cognitive/__pycache__/_trust.cpython-312.pyc +0 -0
- package/src/cognitive/__pycache__/_trust.cpython-314.pyc +0 -0
- package/src/cognitive/_core 2.py +0 -567
- package/src/cognitive/_decay 2.py +0 -382
- package/src/cognitive/_ingest 2.py +0 -892
- package/src/cognitive/_memory 2.py +0 -912
- package/src/cognitive/_search 2.py +0 -949
- package/src/cognitive/_trust 2.py +0 -464
- package/src/crons/__pycache__/sync.cpython-314.pyc +0 -0
- package/src/crons/manifest 2.json +0 -106
- package/src/crons/sync 2.py +0 -217
- package/src/dashboard/__init__ 2.py +0 -0
- package/src/dashboard/__pycache__/__init__.cpython-310.pyc +0 -0
- package/src/dashboard/__pycache__/app.cpython-310.pyc +0 -0
- package/src/dashboard/app 2.py +0 -789
- package/src/db/__init__ 2.py +0 -89
- package/src/db/__pycache__/__init__.cpython-310.pyc +0 -0
- package/src/db/__pycache__/__init__.cpython-312.pyc +0 -0
- package/src/db/__pycache__/__init__.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_core.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_core.cpython-312.pyc +0 -0
- package/src/db/__pycache__/_core.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_credentials.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_credentials.cpython-312.pyc +0 -0
- package/src/db/__pycache__/_credentials.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_cron_runs.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_cron_runs.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_entities.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_entities.cpython-312.pyc +0 -0
- package/src/db/__pycache__/_entities.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_episodic.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_episodic.cpython-312.pyc +0 -0
- package/src/db/__pycache__/_episodic.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_evolution.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_evolution.cpython-312.pyc +0 -0
- package/src/db/__pycache__/_evolution.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_fts.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_fts.cpython-312.pyc +0 -0
- package/src/db/__pycache__/_fts.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_learnings.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_learnings.cpython-312.pyc +0 -0
- package/src/db/__pycache__/_learnings.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_reminders.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_reminders.cpython-312.pyc +0 -0
- package/src/db/__pycache__/_reminders.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_schema.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_schema.cpython-312.pyc +0 -0
- package/src/db/__pycache__/_schema.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_sessions.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_sessions.cpython-312.pyc +0 -0
- package/src/db/__pycache__/_sessions.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_skills.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_skills.cpython-312.pyc +0 -0
- package/src/db/__pycache__/_skills.cpython-314.pyc +0 -0
- package/src/db/__pycache__/_tasks.cpython-310.pyc +0 -0
- package/src/db/__pycache__/_tasks.cpython-312.pyc +0 -0
- package/src/db/__pycache__/_tasks.cpython-314.pyc +0 -0
- package/src/db/_core 2.py +0 -417
- package/src/db/_credentials 2.py +0 -124
- package/src/db/_entities 2.py +0 -178
- package/src/db/_episodic 2.py +0 -738
- package/src/db/_evolution 2.py +0 -54
- package/src/db/_fts 2.py +0 -406
- package/src/db/_learnings 2.py +0 -168
- package/src/db/_reminders 2.py +0 -338
- package/src/db/_schema 2.py +0 -364
- package/src/db/_sessions 2.py +0 -300
- package/src/db/_tasks 2.py +0 -91
- package/src/evolution_cycle 2.py +0 -266
- package/src/hnsw_index 2.py +0 -254
- package/src/hooks/auto_capture 2.py +0 -208
- package/src/hooks/caffeinate-guard 2.sh +0 -8
- package/src/hooks/capture-session 2.sh +0 -21
- package/src/hooks/capture-tool-logs 2.sh +0 -127
- package/src/hooks/daily-briefing-check 2.sh +0 -33
- package/src/hooks/inbox-hook 2.sh +0 -76
- package/src/hooks/post-compact 2.sh +0 -148
- package/src/hooks/pre-compact 2.sh +0 -151
- package/src/hooks/session-start 2.sh +0 -268
- package/src/hooks/session-stop 2.sh +0 -140
- package/src/kg_populate 2.py +0 -290
- package/src/knowledge_graph 2.py +0 -257
- package/src/maintenance 2.py +0 -59
- package/src/migrate_embeddings 2.py +0 -122
- package/src/plugin_loader 2.py +0 -202
- package/src/plugins/__init__ 2.py +0 -0
- package/src/plugins/__pycache__/__init__ 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/__init__.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/__init__.cpython-314.pyc +0 -0
- package/src/plugins/__pycache__/adaptive_mode 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/adaptive_mode.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/adaptive_mode.cpython-314.pyc +0 -0
- package/src/plugins/__pycache__/agents 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/agents.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/artifact_registry 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/artifact_registry.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/backup 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/backup.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/cognitive_memory 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/cognitive_memory.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/core_rules 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/core_rules.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/cortex 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/cortex.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/entities 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/entities.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/episodic_memory 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/episodic_memory.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/evolution 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/evolution.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/guard 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/guard.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/knowledge_graph_tools 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/knowledge_graph_tools.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/preferences 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/preferences.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/schedule.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/schedule.cpython-314.pyc +0 -0
- package/src/plugins/__pycache__/skills.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/skills.cpython-314.pyc +0 -0
- package/src/plugins/__pycache__/update 2.cpython-310.pyc +0 -0
- package/src/plugins/__pycache__/update.cpython-310.pyc +0 -0
- package/src/plugins/adaptive_mode 2.py +0 -805
- package/src/plugins/agents 2.py +0 -52
- package/src/plugins/artifact_registry 2.py +0 -450
- package/src/plugins/backup 2.py +0 -104
- package/src/plugins/cognitive_memory 2.py +0 -564
- package/src/plugins/core_rules 2.py +0 -252
- package/src/plugins/cortex 2.py +0 -299
- package/src/plugins/entities 2.py +0 -67
- package/src/plugins/episodic_memory 2.py +0 -533
- package/src/plugins/evolution 2.py +0 -115
- package/src/plugins/guard 2.py +0 -746
- package/src/plugins/knowledge_graph_tools 2.py +0 -105
- package/src/plugins/preferences 2.py +0 -47
- package/src/plugins/update 2.py +0 -256
- package/src/requirements 2.txt +0 -12
- package/src/rules/__init__ 2.py +0 -0
- package/src/rules/core-rules 2.json +0 -331
- package/src/rules/migrate 2.py +0 -207
- package/src/scripts/__pycache__/nexo-auto-update.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-catchup.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-cognitive-decay.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-daily-self-audit.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-evolution-run.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-followup-hygiene.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-immune.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-install.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-learning-housekeep.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-learning-validator.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-migrate.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-postmortem-consolidator.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-pre-commit.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-proactive-dashboard.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-reflection.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-runtime-preflight.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-send-email.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-send-reply.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-sleep.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-synthesis.cpython-314.pyc +0 -0
- package/src/scripts/__pycache__/nexo-watchdog-smoke.cpython-314.pyc +0 -0
- package/src/scripts/check-context 2.py +0 -264
- package/src/scripts/nexo-auto-update 2.py +0 -6
- package/src/scripts/nexo-backup 2.sh +0 -25
- package/src/scripts/nexo-brain-activation 2.sh +0 -140
- package/src/scripts/nexo-catchup 2.py +0 -242
- package/src/scripts/nexo-cognitive-decay 2.py +0 -182
- package/src/scripts/nexo-daily-self-audit 2.py +0 -552
- package/src/scripts/nexo-deep-sleep 2.sh +0 -97
- package/src/scripts/nexo-evolution-run 2.py +0 -597
- package/src/scripts/nexo-followup-hygiene 2.py +0 -112
- package/src/scripts/nexo-github-monitor 2.py +0 -256
- package/src/scripts/nexo-immune 2.py +0 -927
- package/src/scripts/nexo-inbox-hook 2.sh +0 -74
- package/src/scripts/nexo-install 2.py +0 -6
- package/src/scripts/nexo-learning-housekeep 2.py +0 -245
- package/src/scripts/nexo-learning-validator 2.py +0 -207
- package/src/scripts/nexo-migrate 2.py +0 -232
- package/src/scripts/nexo-postmortem-consolidator 2.py +0 -421
- package/src/scripts/nexo-pre-commit 2.py +0 -120
- package/src/scripts/nexo-prevent-sleep 2.sh +0 -29
- package/src/scripts/nexo-proactive-dashboard 2.py +0 -345
- package/src/scripts/nexo-reflection 2.py +0 -253
- package/src/scripts/nexo-runtime-preflight 2.py +0 -274
- package/src/scripts/nexo-send-email 2.py +0 -25
- package/src/scripts/nexo-send-email.py +0 -25
- package/src/scripts/nexo-send-reply 2.py +0 -178
- package/src/scripts/nexo-send-reply.py +0 -178
- package/src/scripts/nexo-sleep 2.py +0 -592
- package/src/scripts/nexo-snapshot-restore 2.sh +0 -35
- package/src/scripts/nexo-synthesis 2.py +0 -253
- package/src/scripts/nexo-tcc-approve 2.sh +0 -79
- package/src/scripts/nexo-update 2.sh +0 -161
- package/src/scripts/nexo-watchdog 2.sh +0 -878
- package/src/scripts/nexo-watchdog-smoke 2.py +0 -119
- package/src/server 2.py +0 -733
- package/src/storage_router 2.py +0 -32
- package/src/tools_coordination 2.py +0 -102
- package/src/tools_credentials 2.py +0 -68
- package/src/tools_learnings 2.py +0 -220
- package/src/tools_menu 2.py +0 -227
- package/src/tools_reminders 2.py +0 -86
- package/src/tools_reminders_crud 2.py +0 -159
- package/src/tools_sessions 2.py +0 -476
- package/src/tools_task_history 2.py +0 -57
- package/templates/CLAUDE.md 2.template +0 -63
- package/templates/openclaw 2.json +0 -13
- package/tests/__init__ 2.py +0 -0
- package/tests/__init__.py +0 -0
- package/tests/conftest 2.py +0 -71
- package/tests/conftest.py +0 -71
- package/tests/test_cognitive 2.py +0 -205
- package/tests/test_cognitive.py +0 -205
- package/tests/test_knowledge_graph 2.py +0 -140
- package/tests/test_knowledge_graph.py +0 -140
- package/tests/test_migrations 2.py +0 -137
- package/tests/test_migrations.py +0 -137
|
@@ -1,252 +0,0 @@
|
|
|
1
|
-
"""Core Rules plugin — query and manage versioned behavioral rules."""
|
|
2
|
-
|
|
3
|
-
import json
|
|
4
|
-
import os
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
def _get_db():
|
|
8
|
-
from db import get_db
|
|
9
|
-
return get_db()
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def _seed_if_empty():
|
|
13
|
-
"""Seed rules from JSON if table is empty (first run after migration)."""
|
|
14
|
-
import sys
|
|
15
|
-
conn = _get_db()
|
|
16
|
-
try:
|
|
17
|
-
count = conn.execute("SELECT COUNT(*) FROM core_rules WHERE is_active = 1").fetchone()[0]
|
|
18
|
-
except Exception:
|
|
19
|
-
# Table doesn't exist yet — create it
|
|
20
|
-
conn.execute("""CREATE TABLE IF NOT EXISTS core_rules (
|
|
21
|
-
id TEXT PRIMARY KEY, category TEXT NOT NULL, rule TEXT NOT NULL,
|
|
22
|
-
why TEXT NOT NULL, importance INTEGER NOT NULL DEFAULT 3,
|
|
23
|
-
type TEXT NOT NULL DEFAULT 'advisory', added_in TEXT DEFAULT '',
|
|
24
|
-
removed_in TEXT DEFAULT NULL, is_active INTEGER NOT NULL DEFAULT 1)""")
|
|
25
|
-
conn.execute("""CREATE TABLE IF NOT EXISTS core_rules_version (
|
|
26
|
-
id INTEGER PRIMARY KEY, version TEXT NOT NULL, updated_at TEXT NOT NULL)""")
|
|
27
|
-
conn.execute("INSERT OR IGNORE INTO core_rules_version (id, version, updated_at) VALUES (1, '0.0.0', datetime('now'))")
|
|
28
|
-
conn.commit()
|
|
29
|
-
count = 0
|
|
30
|
-
if count > 0:
|
|
31
|
-
return
|
|
32
|
-
|
|
33
|
-
rules_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
|
34
|
-
"rules", "core-rules.json")
|
|
35
|
-
if not os.path.exists(rules_file):
|
|
36
|
-
print(f"[core_rules] WARNING: {rules_file} not found, skipping seed", file=sys.stderr)
|
|
37
|
-
return
|
|
38
|
-
|
|
39
|
-
try:
|
|
40
|
-
with open(rules_file) as f:
|
|
41
|
-
data = json.load(f)
|
|
42
|
-
|
|
43
|
-
version = data["_meta"]["version"]
|
|
44
|
-
loaded = 0
|
|
45
|
-
for cat_key, cat in data["categories"].items():
|
|
46
|
-
for rule in cat["rules"]:
|
|
47
|
-
conn.execute(
|
|
48
|
-
"""INSERT OR REPLACE INTO core_rules (id, category, rule, why, importance, type, added_in)
|
|
49
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)""",
|
|
50
|
-
(rule["id"], cat_key, rule["rule"], rule["why"],
|
|
51
|
-
rule["importance"], rule["type"], rule.get("added_in", version))
|
|
52
|
-
)
|
|
53
|
-
loaded += 1
|
|
54
|
-
|
|
55
|
-
conn.execute("UPDATE core_rules_version SET version = ?, updated_at = datetime('now') WHERE id = 1", (version,))
|
|
56
|
-
conn.commit()
|
|
57
|
-
print(f"[core_rules] Seeded {loaded} rules (v{version})", file=sys.stderr)
|
|
58
|
-
except Exception as e:
|
|
59
|
-
print(f"[core_rules] ERROR seeding rules: {e}", file=sys.stderr)
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
def handle_rules_check(area: str = "", importance_min: int = 0) -> str:
|
|
63
|
-
"""Get applicable core rules for a given area or action.
|
|
64
|
-
|
|
65
|
-
Returns BLOCKING rules that must be followed and ADVISORY rules as guidance.
|
|
66
|
-
Call this before taking any significant action.
|
|
67
|
-
|
|
68
|
-
Args:
|
|
69
|
-
area: Area of work — 'code', 'delegation', 'communication', 'memory', or empty for all.
|
|
70
|
-
Maps to categories: code→execution+integrity, delegation→delegation, etc.
|
|
71
|
-
importance_min: Minimum importance level (1-5, default 0 = all rules)
|
|
72
|
-
"""
|
|
73
|
-
_seed_if_empty()
|
|
74
|
-
conn = _get_db()
|
|
75
|
-
|
|
76
|
-
area_to_categories = {
|
|
77
|
-
"code": ("integrity", "execution"),
|
|
78
|
-
"edit": ("integrity", "execution"),
|
|
79
|
-
"delegation": ("delegation",),
|
|
80
|
-
"delegate": ("delegation",),
|
|
81
|
-
"subagent": ("delegation",),
|
|
82
|
-
"communication": ("communication",),
|
|
83
|
-
"respond": ("communication",),
|
|
84
|
-
"memory": ("memory",),
|
|
85
|
-
"learn": ("memory",),
|
|
86
|
-
"proactivity": ("proactivity",),
|
|
87
|
-
"protect": ("proactivity",),
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
where = "WHERE is_active = 1"
|
|
91
|
-
params = []
|
|
92
|
-
|
|
93
|
-
if area and area.lower() in area_to_categories:
|
|
94
|
-
cats = area_to_categories[area.lower()]
|
|
95
|
-
placeholders = ",".join("?" * len(cats))
|
|
96
|
-
where += f" AND category IN ({placeholders})"
|
|
97
|
-
params.extend(cats)
|
|
98
|
-
|
|
99
|
-
if importance_min > 0:
|
|
100
|
-
where += " AND importance >= ?"
|
|
101
|
-
params.append(importance_min)
|
|
102
|
-
|
|
103
|
-
rows = conn.execute(
|
|
104
|
-
f"SELECT id, category, rule, why, importance, type FROM core_rules {where} ORDER BY importance DESC, category, id",
|
|
105
|
-
params
|
|
106
|
-
).fetchall()
|
|
107
|
-
|
|
108
|
-
if not rows:
|
|
109
|
-
return "No rules found for this area."
|
|
110
|
-
|
|
111
|
-
# Get version
|
|
112
|
-
ver = conn.execute("SELECT version FROM core_rules_version WHERE id = 1").fetchone()
|
|
113
|
-
version = ver[0] if ver else "unknown"
|
|
114
|
-
|
|
115
|
-
blocking = [r for r in rows if r["type"] == "blocking"]
|
|
116
|
-
advisory = [r for r in rows if r["type"] == "advisory"]
|
|
117
|
-
|
|
118
|
-
lines = [f"CORE RULES (v{version}) — {len(blocking)} BLOCKING, {len(advisory)} ADVISORY"]
|
|
119
|
-
if area:
|
|
120
|
-
lines[0] += f" [area: {area}]"
|
|
121
|
-
lines.append("")
|
|
122
|
-
|
|
123
|
-
if blocking:
|
|
124
|
-
lines.append("## BLOCKING (must follow)")
|
|
125
|
-
for r in blocking:
|
|
126
|
-
lines.append(f" {r['id']}. {r['rule']}")
|
|
127
|
-
lines.append(f" Why: {r['why']}")
|
|
128
|
-
lines.append("")
|
|
129
|
-
|
|
130
|
-
if advisory:
|
|
131
|
-
lines.append("## ADVISORY (recommended)")
|
|
132
|
-
for r in advisory:
|
|
133
|
-
lines.append(f" {r['id']}. {r['rule']}")
|
|
134
|
-
lines.append(f" Why: {r['why']}")
|
|
135
|
-
|
|
136
|
-
return "\n".join(lines)
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
def handle_rules_list() -> str:
|
|
140
|
-
"""List all core rules with their status, grouped by category."""
|
|
141
|
-
_seed_if_empty()
|
|
142
|
-
conn = _get_db()
|
|
143
|
-
|
|
144
|
-
ver = conn.execute("SELECT version FROM core_rules_version WHERE id = 1").fetchone()
|
|
145
|
-
version = ver[0] if ver else "unknown"
|
|
146
|
-
|
|
147
|
-
rows = conn.execute(
|
|
148
|
-
"SELECT id, category, rule, importance, type, is_active, added_in, removed_in FROM core_rules ORDER BY category, id"
|
|
149
|
-
).fetchall()
|
|
150
|
-
|
|
151
|
-
lines = [f"CORE RULES v{version} — {len([r for r in rows if r['is_active']])} active, {len([r for r in rows if not r['is_active']])} removed", ""]
|
|
152
|
-
|
|
153
|
-
current_cat = None
|
|
154
|
-
for r in rows:
|
|
155
|
-
if r["category"] != current_cat:
|
|
156
|
-
current_cat = r["category"]
|
|
157
|
-
lines.append(f"### {current_cat.upper()}")
|
|
158
|
-
|
|
159
|
-
status = "✓" if r["is_active"] else "✗"
|
|
160
|
-
tag = "BLOCK" if r["type"] == "blocking" else "ADVSR"
|
|
161
|
-
lines.append(f" [{status}] {r['id']} [{tag}] imp={r['importance']} — {r['rule']}")
|
|
162
|
-
if r["removed_in"]:
|
|
163
|
-
lines.append(f" Removed in v{r['removed_in']}")
|
|
164
|
-
|
|
165
|
-
return "\n".join(lines)
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
def handle_rules_migrate(dry_run: bool = False) -> str:
|
|
169
|
-
"""Sync core rules from the JSON definition file to the database.
|
|
170
|
-
|
|
171
|
-
Adds new rules, marks removed ones as inactive. Safe to run multiple times.
|
|
172
|
-
|
|
173
|
-
Args:
|
|
174
|
-
dry_run: If True, show what would change without applying
|
|
175
|
-
"""
|
|
176
|
-
conn = _get_db()
|
|
177
|
-
rules_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
|
178
|
-
"rules", "core-rules.json")
|
|
179
|
-
if not os.path.exists(rules_file):
|
|
180
|
-
return "ERROR: core-rules.json not found"
|
|
181
|
-
|
|
182
|
-
with open(rules_file) as f:
|
|
183
|
-
data = json.load(f)
|
|
184
|
-
|
|
185
|
-
new_version = data["_meta"]["version"]
|
|
186
|
-
ver = conn.execute("SELECT version FROM core_rules_version WHERE id = 1").fetchone()
|
|
187
|
-
current_version = ver[0] if ver else "0.0.0"
|
|
188
|
-
|
|
189
|
-
# Collect all rule IDs from JSON
|
|
190
|
-
json_ids = set()
|
|
191
|
-
json_rules = {}
|
|
192
|
-
for cat_key, cat in data["categories"].items():
|
|
193
|
-
for rule in cat["rules"]:
|
|
194
|
-
json_ids.add(rule["id"])
|
|
195
|
-
json_rules[rule["id"]] = {**rule, "category": cat_key}
|
|
196
|
-
|
|
197
|
-
# Collect active IDs from DB
|
|
198
|
-
db_ids = set()
|
|
199
|
-
for r in conn.execute("SELECT id FROM core_rules WHERE is_active = 1").fetchall():
|
|
200
|
-
db_ids.add(r[0])
|
|
201
|
-
|
|
202
|
-
added = json_ids - db_ids
|
|
203
|
-
removed = db_ids - json_ids
|
|
204
|
-
unchanged = json_ids & db_ids
|
|
205
|
-
|
|
206
|
-
lines = [
|
|
207
|
-
f"RULES MIGRATION: v{current_version} → v{new_version}",
|
|
208
|
-
f" Added: {len(added)} — {', '.join(sorted(added)) if added else 'none'}",
|
|
209
|
-
f" Removed: {len(removed)} — {', '.join(sorted(removed)) if removed else 'none'}",
|
|
210
|
-
f" Unchanged: {len(unchanged)}",
|
|
211
|
-
]
|
|
212
|
-
|
|
213
|
-
if dry_run:
|
|
214
|
-
lines.append(" Mode: DRY RUN (no changes applied)")
|
|
215
|
-
return "\n".join(lines)
|
|
216
|
-
|
|
217
|
-
# Apply additions
|
|
218
|
-
for rid in added:
|
|
219
|
-
r = json_rules[rid]
|
|
220
|
-
conn.execute(
|
|
221
|
-
"""INSERT OR REPLACE INTO core_rules (id, category, rule, why, importance, type, added_in, is_active)
|
|
222
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, 1)""",
|
|
223
|
-
(r["id"], r["category"], r["rule"], r["why"], r["importance"], r["type"], r.get("added_in", new_version))
|
|
224
|
-
)
|
|
225
|
-
|
|
226
|
-
# Apply removals (soft delete)
|
|
227
|
-
for rid in removed:
|
|
228
|
-
conn.execute(
|
|
229
|
-
"UPDATE core_rules SET is_active = 0, removed_in = ? WHERE id = ?",
|
|
230
|
-
(new_version, rid)
|
|
231
|
-
)
|
|
232
|
-
|
|
233
|
-
# Update existing rules (content might have changed)
|
|
234
|
-
for rid in unchanged:
|
|
235
|
-
r = json_rules[rid]
|
|
236
|
-
conn.execute(
|
|
237
|
-
"UPDATE core_rules SET rule = ?, why = ?, importance = ?, type = ?, category = ? WHERE id = ?",
|
|
238
|
-
(r["rule"], r["why"], r["importance"], r["type"], r["category"], rid)
|
|
239
|
-
)
|
|
240
|
-
|
|
241
|
-
conn.execute("UPDATE core_rules_version SET version = ?, updated_at = datetime('now') WHERE id = 1", (new_version,))
|
|
242
|
-
conn.commit()
|
|
243
|
-
|
|
244
|
-
lines.append(" Status: APPLIED")
|
|
245
|
-
return "\n".join(lines)
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
TOOLS = [
|
|
249
|
-
(handle_rules_check, "nexo_rules_check", "Get applicable core rules for an area before acting. Returns BLOCKING and ADVISORY rules."),
|
|
250
|
-
(handle_rules_list, "nexo_rules_list", "List all core rules with status, grouped by category."),
|
|
251
|
-
(handle_rules_migrate, "nexo_rules_migrate", "Sync rules from JSON definition to database. Adds new, soft-deletes removed."),
|
|
252
|
-
]
|
package/src/plugins/cortex 2.py
DELETED
|
@@ -1,299 +0,0 @@
|
|
|
1
|
-
"""Cognitive Cortex plugin — middleware cognitive layer for NEXO Brain.
|
|
2
|
-
|
|
3
|
-
Provides structured pre-action reasoning with architectural inhibitory control.
|
|
4
|
-
The Cortex does NOT generate answers — it gates, plans, and validates actions.
|
|
5
|
-
|
|
6
|
-
Activation: event-driven, not on every turn. Only on:
|
|
7
|
-
- Tool intent (edit, execute, delegate)
|
|
8
|
-
- Ambiguity in user request
|
|
9
|
-
- Destructive actions
|
|
10
|
-
- Multi-step tasks
|
|
11
|
-
- Retry after failure
|
|
12
|
-
- Contradictions with known facts
|
|
13
|
-
|
|
14
|
-
v0.1: Single MCP tool + middleware validation.
|
|
15
|
-
"""
|
|
16
|
-
|
|
17
|
-
import json
|
|
18
|
-
import time
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
def _get_db():
|
|
22
|
-
from db import get_db
|
|
23
|
-
return get_db()
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
def _get_core_rules_for_task(task_type: str) -> list[str]:
|
|
27
|
-
"""Get relevant Core Rules for the given task type."""
|
|
28
|
-
conn = _get_db()
|
|
29
|
-
try:
|
|
30
|
-
# Map task type to rule categories
|
|
31
|
-
category_map = {
|
|
32
|
-
"edit": ["integrity", "execution"],
|
|
33
|
-
"execute": ["integrity", "execution", "delegation"],
|
|
34
|
-
"delegate": ["delegation"],
|
|
35
|
-
"analyze": ["execution", "memory"],
|
|
36
|
-
"answer": ["communication"],
|
|
37
|
-
}
|
|
38
|
-
categories = category_map.get(task_type, ["integrity", "execution"])
|
|
39
|
-
placeholders = ",".join("?" * len(categories))
|
|
40
|
-
|
|
41
|
-
rows = conn.execute(
|
|
42
|
-
f"SELECT id, rule FROM core_rules WHERE category IN ({placeholders}) AND is_active = 1 AND type = 'blocking' ORDER BY importance DESC LIMIT 5",
|
|
43
|
-
categories
|
|
44
|
-
).fetchall()
|
|
45
|
-
return [f"{r['id']}: {r['rule']}" for r in rows]
|
|
46
|
-
except Exception:
|
|
47
|
-
return []
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def _get_trust_score() -> float:
|
|
51
|
-
"""Get current trust score from cognitive.db."""
|
|
52
|
-
try:
|
|
53
|
-
import cognitive
|
|
54
|
-
return cognitive.get_trust_score()
|
|
55
|
-
except Exception:
|
|
56
|
-
return 50.0
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
def _validate_state(state: dict) -> dict:
|
|
60
|
-
"""Validate cognitive state and determine action mode.
|
|
61
|
-
|
|
62
|
-
Returns dict with: mode, warnings, injected_rules, blocked_reason
|
|
63
|
-
"""
|
|
64
|
-
warnings = []
|
|
65
|
-
mode = "act" # default: allow action
|
|
66
|
-
blocked_reason = None
|
|
67
|
-
|
|
68
|
-
task_type = state.get("task_type", "answer")
|
|
69
|
-
plan = state.get("plan", [])
|
|
70
|
-
unknowns = state.get("unknowns", [])
|
|
71
|
-
evidence = state.get("evidence_refs", [])
|
|
72
|
-
verification = state.get("verification_step", "")
|
|
73
|
-
constraints = state.get("constraints", [])
|
|
74
|
-
goal = state.get("goal", "")
|
|
75
|
-
|
|
76
|
-
# === INHIBITION RULES (architectural, not advisory) ===
|
|
77
|
-
|
|
78
|
-
# Rule 1: unknowns exist → force ASK mode
|
|
79
|
-
if unknowns:
|
|
80
|
-
mode = "ask"
|
|
81
|
-
blocked_reason = f"Cannot act with {len(unknowns)} unknown(s). Resolve first."
|
|
82
|
-
warnings.append(f"UNKNOWNS: {', '.join(unknowns[:3])}")
|
|
83
|
-
|
|
84
|
-
# Rule 2: edit/execute without plan → force PROPOSE
|
|
85
|
-
if task_type in ("edit", "execute", "delegate") and not plan and mode == "act":
|
|
86
|
-
mode = "propose"
|
|
87
|
-
blocked_reason = "No plan defined for action task. Propose plan first."
|
|
88
|
-
warnings.append("MISSING PLAN: define steps before executing")
|
|
89
|
-
|
|
90
|
-
# Rule 3: edit/execute without verification → force PROPOSE
|
|
91
|
-
if task_type in ("edit", "execute") and not verification and mode == "act":
|
|
92
|
-
mode = "propose"
|
|
93
|
-
blocked_reason = "No verification step. How will you confirm it worked?"
|
|
94
|
-
warnings.append("MISSING VERIFICATION: define how to verify")
|
|
95
|
-
|
|
96
|
-
# Rule 4: execute without evidence → force PROPOSE
|
|
97
|
-
if task_type == "execute" and not evidence and mode == "act":
|
|
98
|
-
mode = "propose"
|
|
99
|
-
blocked_reason = "No evidence supporting this action."
|
|
100
|
-
warnings.append("MISSING EVIDENCE: what supports this action?")
|
|
101
|
-
|
|
102
|
-
# Rule 5: no goal → force ASK
|
|
103
|
-
if not goal:
|
|
104
|
-
mode = "ask"
|
|
105
|
-
blocked_reason = "No goal defined."
|
|
106
|
-
warnings.append("NO GOAL: what are you trying to achieve?")
|
|
107
|
-
|
|
108
|
-
# === TRUST-BASED ADJUSTMENTS ===
|
|
109
|
-
trust = _get_trust_score()
|
|
110
|
-
if trust < 30 and mode == "act" and task_type in ("edit", "execute"):
|
|
111
|
-
mode = "propose"
|
|
112
|
-
blocked_reason = f"Trust score {trust:.0f}/100 — propose before acting."
|
|
113
|
-
warnings.append(f"LOW TRUST ({trust:.0f}): extra verification required")
|
|
114
|
-
|
|
115
|
-
# === INJECT RELEVANT RULES ===
|
|
116
|
-
rules = _get_core_rules_for_task(task_type)
|
|
117
|
-
|
|
118
|
-
return {
|
|
119
|
-
"mode": mode,
|
|
120
|
-
"tools_available": _tools_for_mode(mode),
|
|
121
|
-
"warnings": warnings,
|
|
122
|
-
"blocked_reason": blocked_reason,
|
|
123
|
-
"injected_rules": rules,
|
|
124
|
-
"trust_score": round(trust),
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
def _tools_for_mode(mode: str) -> list[str]:
|
|
129
|
-
"""Define which tool categories are available per mode."""
|
|
130
|
-
if mode == "ask":
|
|
131
|
-
return ["read", "search", "ask_user"]
|
|
132
|
-
elif mode == "propose":
|
|
133
|
-
return ["read", "search", "analyze", "propose_plan"]
|
|
134
|
-
else: # act
|
|
135
|
-
return ["all"]
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
def handle_cortex_check(
|
|
139
|
-
goal: str,
|
|
140
|
-
task_type: str = "answer",
|
|
141
|
-
plan: str = "[]",
|
|
142
|
-
known_facts: str = "[]",
|
|
143
|
-
unknowns: str = "[]",
|
|
144
|
-
constraints: str = "[]",
|
|
145
|
-
evidence_refs: str = "[]",
|
|
146
|
-
verification_step: str = "",
|
|
147
|
-
) -> str:
|
|
148
|
-
"""Cognitive Cortex pre-action check. Call BEFORE significant actions.
|
|
149
|
-
|
|
150
|
-
Validates your reasoning state and determines if you can act, should propose,
|
|
151
|
-
or need to ask for clarification first. Implements architectural inhibitory control.
|
|
152
|
-
|
|
153
|
-
WHEN TO CALL:
|
|
154
|
-
- Before editing files or running commands
|
|
155
|
-
- Before delegating to subagents
|
|
156
|
-
- When the task has multiple possible approaches
|
|
157
|
-
- After a failed attempt (before retrying)
|
|
158
|
-
- When user instruction seems to conflict with known facts
|
|
159
|
-
|
|
160
|
-
DO NOT CALL for simple chat responses, greetings, or explanations.
|
|
161
|
-
|
|
162
|
-
Args:
|
|
163
|
-
goal: What you are trying to achieve (required)
|
|
164
|
-
task_type: One of: answer, analyze, edit, execute, delegate
|
|
165
|
-
plan: JSON array of planned steps (e.g. '["read file", "edit function", "test"]')
|
|
166
|
-
known_facts: JSON array of facts you have (from user, memory, files)
|
|
167
|
-
unknowns: JSON array of things you don't know yet but need
|
|
168
|
-
constraints: JSON array of rules or limitations that apply
|
|
169
|
-
evidence_refs: JSON array of evidence supporting your plan (learnings, user statements, file contents)
|
|
170
|
-
verification_step: How you will verify the action worked
|
|
171
|
-
|
|
172
|
-
Returns:
|
|
173
|
-
Mode (ask/propose/act), available tools, warnings, and relevant Core Rules
|
|
174
|
-
"""
|
|
175
|
-
# Parse JSON arrays safely
|
|
176
|
-
def _parse(s):
|
|
177
|
-
try:
|
|
178
|
-
v = json.loads(s) if isinstance(s, str) else s
|
|
179
|
-
return v if isinstance(v, list) else []
|
|
180
|
-
except (json.JSONDecodeError, TypeError):
|
|
181
|
-
return []
|
|
182
|
-
|
|
183
|
-
state = {
|
|
184
|
-
"goal": goal.strip() if goal else "",
|
|
185
|
-
"task_type": task_type if task_type in ("answer", "analyze", "edit", "execute", "delegate") else "answer",
|
|
186
|
-
"plan": _parse(plan),
|
|
187
|
-
"known_facts": _parse(known_facts),
|
|
188
|
-
"unknowns": _parse(unknowns),
|
|
189
|
-
"constraints": _parse(constraints),
|
|
190
|
-
"evidence_refs": _parse(evidence_refs),
|
|
191
|
-
"verification_step": verification_step.strip() if verification_step else "",
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
result = _validate_state(state)
|
|
195
|
-
|
|
196
|
-
# Format response
|
|
197
|
-
lines = [
|
|
198
|
-
f"CORTEX CHECK — mode: {result['mode'].upper()}",
|
|
199
|
-
f"Trust: {result['trust_score']}/100",
|
|
200
|
-
]
|
|
201
|
-
|
|
202
|
-
if result["mode"] == "act":
|
|
203
|
-
lines.append("CLEARED: You may proceed with the action.")
|
|
204
|
-
elif result["mode"] == "propose":
|
|
205
|
-
lines.append(f"PROPOSE ONLY: {result['blocked_reason']}")
|
|
206
|
-
lines.append("Show the user your plan and get approval before executing.")
|
|
207
|
-
elif result["mode"] == "ask":
|
|
208
|
-
lines.append(f"ASK FIRST: {result['blocked_reason']}")
|
|
209
|
-
lines.append("Gather the missing information before proceeding.")
|
|
210
|
-
|
|
211
|
-
if result["warnings"]:
|
|
212
|
-
lines.append("")
|
|
213
|
-
lines.append("Warnings:")
|
|
214
|
-
for w in result["warnings"]:
|
|
215
|
-
lines.append(f" - {w}")
|
|
216
|
-
|
|
217
|
-
if result["injected_rules"]:
|
|
218
|
-
lines.append("")
|
|
219
|
-
lines.append("Applicable Core Rules:")
|
|
220
|
-
for r in result["injected_rules"]:
|
|
221
|
-
lines.append(f" - {r}")
|
|
222
|
-
|
|
223
|
-
lines.append("")
|
|
224
|
-
lines.append(f"Tools available: {', '.join(result['tools_available'])}")
|
|
225
|
-
|
|
226
|
-
# Log cortex activation for metrics
|
|
227
|
-
try:
|
|
228
|
-
conn = _get_db()
|
|
229
|
-
conn.execute(
|
|
230
|
-
"""CREATE TABLE IF NOT EXISTS cortex_log (
|
|
231
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
232
|
-
goal TEXT,
|
|
233
|
-
task_type TEXT,
|
|
234
|
-
mode TEXT,
|
|
235
|
-
warnings TEXT,
|
|
236
|
-
trust_score INTEGER,
|
|
237
|
-
created_at TEXT DEFAULT (datetime('now'))
|
|
238
|
-
)"""
|
|
239
|
-
)
|
|
240
|
-
conn.execute(
|
|
241
|
-
"INSERT INTO cortex_log (goal, task_type, mode, warnings, trust_score) VALUES (?, ?, ?, ?, ?)",
|
|
242
|
-
(goal[:200], task_type, result["mode"], json.dumps(result["warnings"]), result["trust_score"])
|
|
243
|
-
)
|
|
244
|
-
conn.commit()
|
|
245
|
-
except Exception:
|
|
246
|
-
pass
|
|
247
|
-
|
|
248
|
-
return "\n".join(lines)
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
def handle_cortex_stats(days: int = 7) -> str:
|
|
252
|
-
"""View Cortex activation statistics — how often it activates, modes, warnings.
|
|
253
|
-
|
|
254
|
-
Args:
|
|
255
|
-
days: Period to analyze (default 7)
|
|
256
|
-
"""
|
|
257
|
-
conn = _get_db()
|
|
258
|
-
try:
|
|
259
|
-
conn.execute("SELECT 1 FROM cortex_log LIMIT 1")
|
|
260
|
-
except Exception:
|
|
261
|
-
return "No Cortex data yet. The Cortex activates on significant actions."
|
|
262
|
-
|
|
263
|
-
cutoff = f"datetime('now', '-{days} days')"
|
|
264
|
-
|
|
265
|
-
total = conn.execute(f"SELECT COUNT(*) FROM cortex_log WHERE created_at >= {cutoff}").fetchone()[0]
|
|
266
|
-
by_mode = conn.execute(
|
|
267
|
-
f"SELECT mode, COUNT(*) as c FROM cortex_log WHERE created_at >= {cutoff} GROUP BY mode ORDER BY c DESC"
|
|
268
|
-
).fetchall()
|
|
269
|
-
by_type = conn.execute(
|
|
270
|
-
f"SELECT task_type, COUNT(*) as c FROM cortex_log WHERE created_at >= {cutoff} GROUP BY task_type ORDER BY c DESC"
|
|
271
|
-
).fetchall()
|
|
272
|
-
|
|
273
|
-
lines = [
|
|
274
|
-
f"CORTEX STATS — last {days} days",
|
|
275
|
-
f"Total activations: {total}",
|
|
276
|
-
"",
|
|
277
|
-
"By mode:",
|
|
278
|
-
]
|
|
279
|
-
for r in by_mode:
|
|
280
|
-
pct = (r["c"] / total * 100) if total > 0 else 0
|
|
281
|
-
lines.append(f" {r['mode']}: {r['c']} ({pct:.0f}%)")
|
|
282
|
-
|
|
283
|
-
lines.append("")
|
|
284
|
-
lines.append("By task type:")
|
|
285
|
-
for r in by_type:
|
|
286
|
-
lines.append(f" {r['task_type']}: {r['c']}")
|
|
287
|
-
|
|
288
|
-
# Inhibition rate = % of activations that resulted in ask or propose (not act)
|
|
289
|
-
inhibited = sum(r["c"] for r in by_mode if r["mode"] != "act")
|
|
290
|
-
inhibition_rate = (inhibited / total * 100) if total > 0 else 0
|
|
291
|
-
lines.append(f"\nInhibition rate: {inhibition_rate:.0f}% (target: 30-60%)")
|
|
292
|
-
|
|
293
|
-
return "\n".join(lines)
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
TOOLS = [
|
|
297
|
-
(handle_cortex_check, "nexo_cortex_check", "Cognitive pre-action check. Validates reasoning and determines if you can act, should propose, or need to ask first. Call before significant actions."),
|
|
298
|
-
(handle_cortex_stats, "nexo_cortex_stats", "View Cortex activation statistics — modes, task types, inhibition rate."),
|
|
299
|
-
]
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
"""Entities plugin — people, services, URLs, recurring contacts."""
|
|
2
|
-
from db import create_entity, search_entities, list_entities, update_entity, delete_entity
|
|
3
|
-
|
|
4
|
-
def handle_entity_search(query: str, type: str = "") -> str:
|
|
5
|
-
"""Search entities by name or value. Optional type filter."""
|
|
6
|
-
results = search_entities(query, type)
|
|
7
|
-
if not results:
|
|
8
|
-
return "No results."
|
|
9
|
-
lines = []
|
|
10
|
-
for e in results:
|
|
11
|
-
notes = f" — {e['notes']}" if e.get("notes") else ""
|
|
12
|
-
lines.append(f" [{e['id']}] ({e['type']}) {e['name']}: {e['value']}{notes}")
|
|
13
|
-
return f"ENTIDADES ({len(results)}):\n" + "\n".join(lines)
|
|
14
|
-
|
|
15
|
-
def handle_entity_create(name: str, type: str, value: str, notes: str = "") -> str:
|
|
16
|
-
"""Create a new entity."""
|
|
17
|
-
eid = create_entity(name, type, value, notes)
|
|
18
|
-
# KG hook
|
|
19
|
-
try:
|
|
20
|
-
from kg_populate import on_entity_create
|
|
21
|
-
on_entity_create(eid, name, type)
|
|
22
|
-
except Exception:
|
|
23
|
-
pass
|
|
24
|
-
return f"Entity created: [{eid}] {name} ({type})"
|
|
25
|
-
|
|
26
|
-
def handle_entity_update(id: int, name: str = "", type: str = "", value: str = "", notes: str = "") -> str:
|
|
27
|
-
"""Update an entity. Only non-empty fields are changed."""
|
|
28
|
-
kwargs = {}
|
|
29
|
-
if name: kwargs["name"] = name
|
|
30
|
-
if type: kwargs["type"] = type
|
|
31
|
-
if value: kwargs["value"] = value
|
|
32
|
-
if notes: kwargs["notes"] = notes
|
|
33
|
-
if not kwargs: return "Nothing to update."
|
|
34
|
-
update_entity(id, **kwargs)
|
|
35
|
-
return f"Entity [{id}] updated."
|
|
36
|
-
|
|
37
|
-
def handle_entity_delete(id: int) -> str:
|
|
38
|
-
"""Delete an entity."""
|
|
39
|
-
if not delete_entity(id):
|
|
40
|
-
return f"ERROR: Entity [{id}] not found."
|
|
41
|
-
return f"Entity [{id}] deleted."
|
|
42
|
-
|
|
43
|
-
def handle_entity_list(type: str = "") -> str:
|
|
44
|
-
"""List all entities, optionally filtered by type."""
|
|
45
|
-
results = list_entities(type)
|
|
46
|
-
if not results:
|
|
47
|
-
return "No entities."
|
|
48
|
-
grouped = {}
|
|
49
|
-
for e in results:
|
|
50
|
-
t = e["type"]
|
|
51
|
-
if t not in grouped: grouped[t] = []
|
|
52
|
-
grouped[t].append(e)
|
|
53
|
-
lines = []
|
|
54
|
-
for t, entities in grouped.items():
|
|
55
|
-
lines.append(f"\n [{t.upper()}]")
|
|
56
|
-
for e in entities:
|
|
57
|
-
notes = f" — {e['notes']}" if e.get("notes") else ""
|
|
58
|
-
lines.append(f" [{e['id']}] {e['name']}: {e['value']}{notes}")
|
|
59
|
-
return f"ENTIDADES ({len(results)}):" + "\n".join(lines)
|
|
60
|
-
|
|
61
|
-
TOOLS = [
|
|
62
|
-
(handle_entity_search, "nexo_entity_search", "Search entities by name, value, or type"),
|
|
63
|
-
(handle_entity_create, "nexo_entity_create", "Create a new entity (person, service, URL)"),
|
|
64
|
-
(handle_entity_update, "nexo_entity_update", "Update an entity's fields"),
|
|
65
|
-
(handle_entity_delete, "nexo_entity_delete", "Delete an entity"),
|
|
66
|
-
(handle_entity_list, "nexo_entity_list", "List all entities grouped by type"),
|
|
67
|
-
]
|