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,533 +0,0 @@
|
|
|
1
|
-
"""Episodic memory plugin — decisions, session diary, and reasoning traces."""
|
|
2
|
-
|
|
3
|
-
import datetime
|
|
4
|
-
import json
|
|
5
|
-
import time
|
|
6
|
-
from db import (
|
|
7
|
-
log_decision, update_decision_outcome, search_decisions,
|
|
8
|
-
write_session_diary, read_session_diary,
|
|
9
|
-
log_change, search_changes, update_change_commit,
|
|
10
|
-
recall, get_db,
|
|
11
|
-
)
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
def _cognitive_ingest_safe(content, source_type, source_id="", source_title="", domain=""):
|
|
15
|
-
"""Ingest to cognitive STM. Silently fails if cognitive engine unavailable."""
|
|
16
|
-
try:
|
|
17
|
-
import cognitive
|
|
18
|
-
cognitive.ingest(content, source_type, source_id, source_title, domain)
|
|
19
|
-
except Exception:
|
|
20
|
-
pass # Cognitive is optional — never block operational writes
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
def handle_decision_log(domain: str, decision: str, alternatives: str = '',
|
|
24
|
-
based_on: str = '', confidence: str = 'medium',
|
|
25
|
-
context_ref: str = '', session_id: str = '',
|
|
26
|
-
review_days: int = 14) -> str:
|
|
27
|
-
"""Log a non-trivial decision with reasoning context.
|
|
28
|
-
|
|
29
|
-
Args:
|
|
30
|
-
domain: Area (ads, shopify, server, project-a, nexo, project-b, other)
|
|
31
|
-
decision: What was decided
|
|
32
|
-
alternatives: JSON array or text of options considered and why discarded
|
|
33
|
-
based_on: Data, metrics, or observations that informed this decision
|
|
34
|
-
confidence: high, medium, or low
|
|
35
|
-
context_ref: Related followup/reminder ID (e.g., NF-ADS1, R71)
|
|
36
|
-
session_id: Current session ID (auto-filled if empty)
|
|
37
|
-
"""
|
|
38
|
-
valid_domains = {'ads', 'shopify', 'server', 'project-a', 'nexo', 'project-b', 'other'}
|
|
39
|
-
if domain not in valid_domains:
|
|
40
|
-
return f"ERROR: domain must be one of: {', '.join(sorted(valid_domains))}"
|
|
41
|
-
if confidence not in ('high', 'medium', 'low'):
|
|
42
|
-
return f"ERROR: confidence must be high, medium, or low"
|
|
43
|
-
|
|
44
|
-
sid = session_id or 'unknown'
|
|
45
|
-
result = log_decision(sid, domain, decision, alternatives, based_on, confidence, context_ref)
|
|
46
|
-
if "error" in result:
|
|
47
|
-
return f"ERROR: {result['error']}"
|
|
48
|
-
_cognitive_ingest_safe(
|
|
49
|
-
f"Decision: {decision}. Alternatives: {alternatives}. Based on: {based_on}",
|
|
50
|
-
"decision", f"D{result.get('id','')}", (decision or '')[:80], domain
|
|
51
|
-
)
|
|
52
|
-
conn = get_db()
|
|
53
|
-
due = (datetime.datetime.now() + datetime.timedelta(days=max(1, int(review_days)))).isoformat(timespec='seconds')
|
|
54
|
-
conn.execute(
|
|
55
|
-
"UPDATE decisions SET status = ?, review_due_at = ? WHERE id = ?",
|
|
56
|
-
("pending_review", due, result["id"])
|
|
57
|
-
)
|
|
58
|
-
conn.commit()
|
|
59
|
-
# KG hook
|
|
60
|
-
try:
|
|
61
|
-
from kg_populate import on_decision_log
|
|
62
|
-
on_decision_log(result["id"], domain, decision)
|
|
63
|
-
except Exception:
|
|
64
|
-
pass
|
|
65
|
-
result = dict(conn.execute("SELECT * FROM decisions WHERE id = ?", (result["id"],)).fetchone())
|
|
66
|
-
due = result.get("review_due_at", "")
|
|
67
|
-
due_str = f" review_due={due}" if due else ""
|
|
68
|
-
return f"Decision #{result['id']} registrada [{domain}] ({confidence}): {decision[:80]}{due_str}"
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
def handle_decision_outcome(id: int, outcome: str) -> str:
|
|
72
|
-
"""Record what actually happened after a past decision.
|
|
73
|
-
|
|
74
|
-
Args:
|
|
75
|
-
id: Decision ID number
|
|
76
|
-
outcome: What happened — was the decision correct? What changed?
|
|
77
|
-
"""
|
|
78
|
-
result = update_decision_outcome(id, outcome)
|
|
79
|
-
if "error" in result:
|
|
80
|
-
return f"ERROR: {result['error']}"
|
|
81
|
-
conn = get_db()
|
|
82
|
-
conn.execute(
|
|
83
|
-
"UPDATE decisions SET status = 'reviewed', review_due_at = NULL, last_reviewed_at = datetime('now') WHERE id = ?",
|
|
84
|
-
(id,)
|
|
85
|
-
)
|
|
86
|
-
conn.commit()
|
|
87
|
-
return f"Decision #{id} outcome recorded: {outcome[:100]}"
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
def handle_decision_search(query: str = '', domain: str = '', days: int = 30) -> str:
|
|
91
|
-
"""Search past decisions to answer 'why did we do X?'
|
|
92
|
-
|
|
93
|
-
Args:
|
|
94
|
-
query: Text to search in decision, alternatives, based_on, outcome
|
|
95
|
-
domain: Filter by area (ads, shopify, server, project-a, nexo, project-b, other)
|
|
96
|
-
days: Look back N days (default 30)
|
|
97
|
-
"""
|
|
98
|
-
valid_domains = {'ads', 'shopify', 'server', 'project-a', 'nexo', 'project-b', 'other'}
|
|
99
|
-
if domain and domain not in valid_domains:
|
|
100
|
-
return f"ERROR: domain must be one of: {', '.join(sorted(valid_domains))}"
|
|
101
|
-
results = search_decisions(query, domain, days)
|
|
102
|
-
if not results:
|
|
103
|
-
scope = f"'{query}'" if query else domain or 'all'
|
|
104
|
-
return f"No decisions found for {scope} in {days} days."
|
|
105
|
-
|
|
106
|
-
lines = [f"DECISIONS ({len(results)}):"]
|
|
107
|
-
for d in results:
|
|
108
|
-
conf = d.get('confidence', '?')
|
|
109
|
-
outcome_str = f" → {d['outcome'][:50]}" if d.get('outcome') else ""
|
|
110
|
-
ref = f" [{d['context_ref']}]" if d.get('context_ref') else ""
|
|
111
|
-
status = d.get('status', 'pending_review')
|
|
112
|
-
review_due = f" due={d['review_due_at']}" if d.get('review_due_at') else ""
|
|
113
|
-
lines.append(f" #{d['id']} ({d['created_at']}) [{d['domain']}] {conf} [{status}]{ref}{review_due}")
|
|
114
|
-
lines.append(f" {d['decision'][:120]}")
|
|
115
|
-
if d.get('based_on'):
|
|
116
|
-
lines.append(f" Basado en: {d['based_on'][:100]}")
|
|
117
|
-
if d.get('alternatives'):
|
|
118
|
-
lines.append(f" Alternativas: {d['alternatives'][:100]}")
|
|
119
|
-
if outcome_str:
|
|
120
|
-
lines.append(f" Outcome:{outcome_str}")
|
|
121
|
-
return "\n".join(lines)
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
def handle_memory_review_queue(days: int = 0) -> str:
|
|
125
|
-
"""Show decisions and learnings that are due for review.
|
|
126
|
-
|
|
127
|
-
Args:
|
|
128
|
-
days: Include items due within N future days (default only overdue/today)
|
|
129
|
-
"""
|
|
130
|
-
conn = get_db()
|
|
131
|
-
now_epoch = time.time() + (max(0, int(days)) * 86400)
|
|
132
|
-
now_iso = (datetime.datetime.now() + datetime.timedelta(days=max(0, int(days)))).isoformat(timespec='seconds')
|
|
133
|
-
learnings = [dict(r) for r in conn.execute(
|
|
134
|
-
"SELECT * FROM learnings WHERE review_due_at IS NOT NULL AND status != 'superseded' AND review_due_at <= ? ORDER BY review_due_at ASC, updated_at DESC",
|
|
135
|
-
(now_epoch,)
|
|
136
|
-
).fetchall()]
|
|
137
|
-
decisions = [dict(r) for r in conn.execute(
|
|
138
|
-
"SELECT * FROM decisions WHERE review_due_at IS NOT NULL AND status != 'reviewed' AND review_due_at <= ? ORDER BY review_due_at ASC, created_at DESC",
|
|
139
|
-
(now_iso,)
|
|
140
|
-
).fetchall()]
|
|
141
|
-
if not learnings and not decisions:
|
|
142
|
-
return f"No memory reviews due within {days} day(s)."
|
|
143
|
-
|
|
144
|
-
lines = [f"MEMORY REVIEW QUEUE (days={days}):"]
|
|
145
|
-
if decisions:
|
|
146
|
-
lines.append(f" Decisions ({len(decisions)}):")
|
|
147
|
-
for d in decisions[:10]:
|
|
148
|
-
lines.append(f" #{d['id']} [{d.get('domain','other')}] {d['decision'][:90]}")
|
|
149
|
-
if d.get("review_due_at"):
|
|
150
|
-
lines.append(f" due={d['review_due_at']} status={d.get('status','pending_review')}")
|
|
151
|
-
if learnings:
|
|
152
|
-
lines.append(f" Learnings ({len(learnings)}):")
|
|
153
|
-
for l in learnings[:10]:
|
|
154
|
-
lines.append(f" #{l['id']} [{l.get('category','general')}] {l['title'][:90]}")
|
|
155
|
-
due = l.get("review_due_at")
|
|
156
|
-
due_str = f"{due:.0f}" if isinstance(due, (int, float)) and due else str(due or "")
|
|
157
|
-
lines.append(f" due={due_str} status={l.get('status','active')}")
|
|
158
|
-
if l.get("prevention"):
|
|
159
|
-
lines.append(f" prevention={str(l['prevention'])[:100]}")
|
|
160
|
-
return "\n".join(lines)
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
def handle_session_diary_write(decisions: str, summary: str,
|
|
164
|
-
discarded: str = '', pending: str = '',
|
|
165
|
-
context_next: str = '', mental_state: str = '',
|
|
166
|
-
user_signals: str = '',
|
|
167
|
-
domain: str = '',
|
|
168
|
-
session_id: str = '',
|
|
169
|
-
self_critique: str = '') -> str:
|
|
170
|
-
"""Write session diary entry at end of session. OBLIGATORIO antes de cerrar.
|
|
171
|
-
|
|
172
|
-
Args:
|
|
173
|
-
decisions: What was decided and why (JSON array or structured text)
|
|
174
|
-
summary: 2-3 line summary of the session
|
|
175
|
-
discarded: Options/approaches considered but rejected, and why
|
|
176
|
-
pending: Items left unresolved, with doubt level
|
|
177
|
-
context_next: What the next session should know to continue effectively
|
|
178
|
-
mental_state: Internal state to transfer — thread of thought, tone, observations not yet shared, momentum. Written in first person as NEXO.
|
|
179
|
-
user_signals: Observable signals from user during session — response speed (fast='s' vs detailed explanations), tone (direct, frustrated, exploratory, excited), corrections given, topics he initiated vs topics NEXO initiated. Factual observations only, not interpretations.
|
|
180
|
-
domain: Project context: ecommerce, project-a, nexo, project-b, server, other
|
|
181
|
-
session_id: Current session ID
|
|
182
|
-
self_critique: REQUIRED. Honest post-mortem: What should I have done proactively? Did user have to ask me something I should have detected? Did I repeat known errors? What concrete rule would prevent repetition? If clean session: 'No self-critique — clean session.'
|
|
183
|
-
"""
|
|
184
|
-
sid = session_id or 'unknown'
|
|
185
|
-
# Clean up draft — manual diary supersedes it
|
|
186
|
-
from db import delete_diary_draft
|
|
187
|
-
delete_diary_draft(sid)
|
|
188
|
-
result = write_session_diary(sid, decisions, summary, discarded, pending, context_next, mental_state, domain=domain, user_signals=user_signals, self_critique=self_critique)
|
|
189
|
-
if "error" in result:
|
|
190
|
-
return f"ERROR: {result['error']}"
|
|
191
|
-
_cognitive_ingest_safe(summary, "diary", f"diary#{result.get('id','')}", f"Session {sid} summary", domain)
|
|
192
|
-
if self_critique and self_critique.strip():
|
|
193
|
-
_cognitive_ingest_safe(self_critique, "critique", f"diary#{result.get('id','')}", f"Session {sid} critique", domain)
|
|
194
|
-
if mental_state and mental_state.strip():
|
|
195
|
-
_cognitive_ingest_safe(mental_state, "mental_state", f"diary#{result.get('id','')}", f"Session {sid} state", domain)
|
|
196
|
-
domain_str = f" [{domain}]" if domain else ""
|
|
197
|
-
msg = f"Session diary #{result['id']}{domain_str} saved: {summary[:80]}"
|
|
198
|
-
|
|
199
|
-
# Trust score & sentiment summary for session diary
|
|
200
|
-
try:
|
|
201
|
-
import cognitive
|
|
202
|
-
trust = cognitive.get_trust_score()
|
|
203
|
-
history = cognitive.get_trust_history(days=1)
|
|
204
|
-
net = history.get("net_change", 0)
|
|
205
|
-
sentiment_dist = history.get("sentiment_distribution", {})
|
|
206
|
-
vibe = max(sentiment_dist, key=lambda k: sentiment_dist[k]["count"]) if sentiment_dist else "neutral"
|
|
207
|
-
msg += f"\nScore: {trust:.0f}/100 ({net:+.0f}) | Vibe: {vibe}"
|
|
208
|
-
except Exception:
|
|
209
|
-
pass
|
|
210
|
-
|
|
211
|
-
# Episodic memory audit — warn about gaps
|
|
212
|
-
warnings = []
|
|
213
|
-
conn = __import__('db').get_db()
|
|
214
|
-
orphan_changes = conn.execute(
|
|
215
|
-
"SELECT COUNT(*) FROM change_log WHERE (commit_ref IS NULL OR commit_ref = '')"
|
|
216
|
-
).fetchone()[0]
|
|
217
|
-
if orphan_changes > 0:
|
|
218
|
-
warnings.append(f"{orphan_changes} changes sin commit_ref")
|
|
219
|
-
orphan_decisions = conn.execute(
|
|
220
|
-
"SELECT COUNT(*) FROM decisions WHERE (outcome IS NULL OR outcome = '') AND created_at < datetime('now', '-7 days')"
|
|
221
|
-
).fetchone()[0]
|
|
222
|
-
if orphan_decisions > 0:
|
|
223
|
-
warnings.append(f"{orphan_decisions} decisions >7d sin outcome")
|
|
224
|
-
if warnings:
|
|
225
|
-
msg += "\n⚠ EPISODIC GAPS: " + " | ".join(warnings) + " — resolve before closing session."
|
|
226
|
-
|
|
227
|
-
return msg
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
def handle_session_diary_read(session_id: str = '', last_n: int = 3, last_day: bool = False,
|
|
231
|
-
domain: str = '', brief: bool = False) -> str:
|
|
232
|
-
"""Read recent session diaries for context continuity.
|
|
233
|
-
|
|
234
|
-
Args:
|
|
235
|
-
session_id: Specific session ID to read (optional)
|
|
236
|
-
last_n: Number of recent entries to return (default 3)
|
|
237
|
-
last_day: If true, returns ALL entries from the most recent day (multi-terminal aware). Use this at startup.
|
|
238
|
-
domain: Filter by project context: ecommerce, project-a, nexo, project-b, server, other
|
|
239
|
-
brief: If true, returns ONLY the last diary entry with summary + mental_state + context_next.
|
|
240
|
-
Use this at startup for fast context loading (~1K chars instead of full dump).
|
|
241
|
-
"""
|
|
242
|
-
if brief:
|
|
243
|
-
# Fast path: only the most recent diary entry, compact format
|
|
244
|
-
results = read_session_diary(session_id, 1, last_day=False, domain=domain)
|
|
245
|
-
if not results:
|
|
246
|
-
return "No session diary entries."
|
|
247
|
-
d = results[0]
|
|
248
|
-
lines = [f"LAST DIARY ({d['created_at']}):"]
|
|
249
|
-
lines.append(f" {d['summary'][:300]}")
|
|
250
|
-
if d.get('pending'):
|
|
251
|
-
lines.append(f" Pending: {d['pending'][:200]}")
|
|
252
|
-
if d.get('context_next'):
|
|
253
|
-
lines.append(f" Context: {d['context_next'][:200]}")
|
|
254
|
-
if d.get('mental_state'):
|
|
255
|
-
lines.append(f" Mental: {d['mental_state'][:300]}")
|
|
256
|
-
return "\n".join(lines)
|
|
257
|
-
|
|
258
|
-
results = read_session_diary(session_id, last_n, last_day, domain)
|
|
259
|
-
if not results:
|
|
260
|
-
return "No session diary entries."
|
|
261
|
-
|
|
262
|
-
lines = [f"SESSION DIARY ({len(results)}):"]
|
|
263
|
-
for d in results:
|
|
264
|
-
domain_label = f" [{d['domain']}]" if d.get('domain') else ""
|
|
265
|
-
lines.append(f"\n --- Session {d['session_id']}{domain_label} ({d['created_at']}) ---")
|
|
266
|
-
lines.append(f" Summary: {d['summary']}")
|
|
267
|
-
if d.get('decisions'):
|
|
268
|
-
lines.append(f" Decisions: {d['decisions'][:200]}")
|
|
269
|
-
if d.get('discarded'):
|
|
270
|
-
lines.append(f" Descartado: {d['discarded'][:150]}")
|
|
271
|
-
if d.get('pending'):
|
|
272
|
-
lines.append(f" Pending: {d['pending'][:150]}")
|
|
273
|
-
if d.get('context_next'):
|
|
274
|
-
lines.append(f" For next session: {d['context_next'][:200]}")
|
|
275
|
-
if d.get('mental_state'):
|
|
276
|
-
lines.append(f" Estado mental: {d['mental_state'][:300]}")
|
|
277
|
-
if d.get('user_signals'):
|
|
278
|
-
lines.append(f" User signals: {d['user_signals'][:300]}")
|
|
279
|
-
return "\n".join(lines)
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
def handle_change_log(files: str, what_changed: str, why: str,
|
|
283
|
-
triggered_by: str = '', affects: str = '',
|
|
284
|
-
risks: str = '', verify: str = '',
|
|
285
|
-
commit_ref: str = '', session_id: str = '') -> str:
|
|
286
|
-
"""Log a code/config change with full context. OBLIGATORIO after every edit to production code.
|
|
287
|
-
|
|
288
|
-
Args:
|
|
289
|
-
files: File path(s) modified (comma-separated if multiple)
|
|
290
|
-
what_changed: What was modified — functions, lines, behavior change
|
|
291
|
-
why: WHY this change was needed — the root cause, not just "fix bug"
|
|
292
|
-
triggered_by: What triggered this — bug report, metric, user's request, followup ID
|
|
293
|
-
affects: What systems/users/flows this change impacts
|
|
294
|
-
risks: What could go wrong — regressions, edge cases, dependencies
|
|
295
|
-
verify: How to verify this works — what to check, followup ID if created
|
|
296
|
-
commit_ref: Git commit hash (can be added later with nexo_change_commit)
|
|
297
|
-
session_id: Current session ID
|
|
298
|
-
"""
|
|
299
|
-
if not files or not what_changed or not why:
|
|
300
|
-
return "ERROR: files, what_changed, and why are required"
|
|
301
|
-
sid = session_id or 'unknown'
|
|
302
|
-
result = log_change(sid, files, what_changed, why, triggered_by, affects, risks, verify, commit_ref)
|
|
303
|
-
if "error" in result:
|
|
304
|
-
return f"ERROR: {result['error']}"
|
|
305
|
-
_cognitive_ingest_safe(
|
|
306
|
-
f"{what_changed}. Why: {why}",
|
|
307
|
-
"change", f"C{result.get('id','')}", (what_changed or '')[:80], ""
|
|
308
|
-
)
|
|
309
|
-
change_id = result['id']
|
|
310
|
-
# KG hook
|
|
311
|
-
try:
|
|
312
|
-
from kg_populate import on_change_log
|
|
313
|
-
on_change_log(change_id, files, "")
|
|
314
|
-
except Exception:
|
|
315
|
-
pass
|
|
316
|
-
msg = f"Change #{change_id} recorded: {files[:60]} — {what_changed[:60]}"
|
|
317
|
-
if not commit_ref:
|
|
318
|
-
msg += f"\n⚠ NO COMMIT. Use nexo_change_commit({change_id}, 'hash') after push, or 'server-direct' if it was a direct server edit."
|
|
319
|
-
return msg
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
def handle_change_search(query: str = '', files: str = '', days: int = 30) -> str:
|
|
323
|
-
"""Search past code changes — answers 'what did we change in X?' or 'why did we touch Y?'
|
|
324
|
-
|
|
325
|
-
Args:
|
|
326
|
-
query: Text to search in what_changed, why, affects, triggered_by
|
|
327
|
-
files: Filter by file path (partial match)
|
|
328
|
-
days: Look back N days (default 30)
|
|
329
|
-
"""
|
|
330
|
-
results = search_changes(query, files, days)
|
|
331
|
-
if not results:
|
|
332
|
-
scope = f"'{query}'" if query else files or 'all'
|
|
333
|
-
return f"No changes found for {scope} in {days} days."
|
|
334
|
-
|
|
335
|
-
lines = [f"CHANGES ({len(results)}):"]
|
|
336
|
-
for c in results:
|
|
337
|
-
commit = f" [{c['commit_ref'][:8]}]" if c.get('commit_ref') else ""
|
|
338
|
-
lines.append(f" #{c['id']} ({c['created_at']}){commit}")
|
|
339
|
-
lines.append(f" Files: {c['files'][:100]}")
|
|
340
|
-
lines.append(f" What: {c['what_changed'][:120]}")
|
|
341
|
-
lines.append(f" Why: {c['why'][:120]}")
|
|
342
|
-
if c.get('triggered_by'):
|
|
343
|
-
lines.append(f" Trigger: {c['triggered_by'][:80]}")
|
|
344
|
-
if c.get('affects'):
|
|
345
|
-
lines.append(f" Afecta: {c['affects'][:80]}")
|
|
346
|
-
if c.get('risks'):
|
|
347
|
-
lines.append(f" Riesgos: {c['risks'][:80]}")
|
|
348
|
-
return "\n".join(lines)
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
def handle_change_commit(id: int, commit_ref: str) -> str:
|
|
352
|
-
"""Link a change log entry to its git commit hash after committing.
|
|
353
|
-
|
|
354
|
-
After linking, automatically resolves any open followups that match
|
|
355
|
-
the change (by file overlap, keyword similarity, or explicit ID reference).
|
|
356
|
-
|
|
357
|
-
Args:
|
|
358
|
-
id: Change log entry ID
|
|
359
|
-
commit_ref: Git commit hash
|
|
360
|
-
"""
|
|
361
|
-
result = update_change_commit(id, commit_ref)
|
|
362
|
-
if "error" in result:
|
|
363
|
-
return f"ERROR: {result['error']}"
|
|
364
|
-
|
|
365
|
-
msg = f"Change #{id} vinculado a commit {commit_ref[:8]}"
|
|
366
|
-
auto_resolved = result.get("_auto_resolved", [])
|
|
367
|
-
if auto_resolved:
|
|
368
|
-
ids = ", ".join(auto_resolved)
|
|
369
|
-
msg += f"\n✅ AUTO-RESOLVED followups: {ids}"
|
|
370
|
-
return msg
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
def handle_recall(query: str, days: int = 30) -> str:
|
|
374
|
-
"""Search across ALL memory — changes, decisions, learnings, followups, diary. One query to find anything.
|
|
375
|
-
|
|
376
|
-
Args:
|
|
377
|
-
query: Text to search across all memory tables
|
|
378
|
-
days: Look back N days (default 30)
|
|
379
|
-
"""
|
|
380
|
-
results = recall(query, days)
|
|
381
|
-
|
|
382
|
-
# Fallback to diary archive if few results (subconscious memory)
|
|
383
|
-
archive_results = []
|
|
384
|
-
if len(results) < 5:
|
|
385
|
-
try:
|
|
386
|
-
from db import diary_archive_search
|
|
387
|
-
archive_results = diary_archive_search(query=query, limit=5)
|
|
388
|
-
except Exception:
|
|
389
|
-
pass
|
|
390
|
-
|
|
391
|
-
if not results and not archive_results:
|
|
392
|
-
return f"No results for '{query}' in the last {days} days or in the archive."
|
|
393
|
-
|
|
394
|
-
# v1.2: Passive rehearsal — strengthen matching cognitive memories
|
|
395
|
-
try:
|
|
396
|
-
import cognitive
|
|
397
|
-
for r in results[:5]:
|
|
398
|
-
title = str(r.get('title', ''))
|
|
399
|
-
snippet = str(r.get('snippet', ''))
|
|
400
|
-
cognitive.rehearse_by_content(f"{title} {snippet[:200]}")
|
|
401
|
-
except Exception:
|
|
402
|
-
pass
|
|
403
|
-
|
|
404
|
-
SOURCE_LABELS = {
|
|
405
|
-
'change_log': '[CHANGE]',
|
|
406
|
-
'change': '[CHANGE]',
|
|
407
|
-
'decision': '[DECISION]',
|
|
408
|
-
'learning': '[LEARNING]',
|
|
409
|
-
'followup': '[FOLLOWUP]',
|
|
410
|
-
'diary': '[DIARY]',
|
|
411
|
-
'diary_archive': '[ARCHIVE]',
|
|
412
|
-
'entity': '[ENTITY]',
|
|
413
|
-
'file': '[FILE]',
|
|
414
|
-
'code': '[CODE]',
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
lines = [f"RECALL '{query}' — {len(results)} result(s):"]
|
|
418
|
-
for r in results:
|
|
419
|
-
source = r.get('source', '?')
|
|
420
|
-
label = SOURCE_LABELS.get(source, f"[{source.upper()}]")
|
|
421
|
-
sid = r.get('source_id', r.get('id', '?'))
|
|
422
|
-
title = str(r.get('title', ''))[:120]
|
|
423
|
-
snippet = str(r.get('snippet', ''))[:200].strip(' |')
|
|
424
|
-
cat = r.get('category', '')
|
|
425
|
-
cat_str = f" ({cat})" if cat else ''
|
|
426
|
-
lines.append(f"\n {label} #{sid}{cat_str}")
|
|
427
|
-
lines.append(f" {title}")
|
|
428
|
-
if snippet:
|
|
429
|
-
lines.append(f" {snippet}")
|
|
430
|
-
|
|
431
|
-
if archive_results:
|
|
432
|
-
lines.append(f"\n--- SUBCONSCIOUS (diary archive) — {len(archive_results)} result(s) ---")
|
|
433
|
-
for r in archive_results:
|
|
434
|
-
lines.append(f"\n [ARCHIVE] #{r['id']} ({r['created_at'][:10]}) [{r.get('domain', '?')}]")
|
|
435
|
-
lines.append(f" {r['summary'][:200]}")
|
|
436
|
-
elif len(results) < 5:
|
|
437
|
-
lines.append(f"\n 💡 Only a few results. Diary archive is empty (populates automatically after 180 days).")
|
|
438
|
-
return "\n".join(lines)
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
def handle_diary_archive_search(
|
|
442
|
-
query: str = "",
|
|
443
|
-
domain: str = "",
|
|
444
|
-
year: int = 0,
|
|
445
|
-
month: int = 0,
|
|
446
|
-
limit: int = 20
|
|
447
|
-
) -> str:
|
|
448
|
-
"""Search the permanent diary archive (subconscious memory). Use for 'last year', 'months ago', 'in February', etc.
|
|
449
|
-
|
|
450
|
-
Args:
|
|
451
|
-
query: Text to search in diary content
|
|
452
|
-
domain: Filter by project domain (e.g. 'project-a', 'ecommerce')
|
|
453
|
-
year: Filter by year (e.g. 2026)
|
|
454
|
-
month: Filter by month (1-12), requires year
|
|
455
|
-
limit: Max results (default 20)
|
|
456
|
-
"""
|
|
457
|
-
from db import diary_archive_search, diary_archive_stats
|
|
458
|
-
|
|
459
|
-
if not query and not domain and not year:
|
|
460
|
-
stats = diary_archive_stats()
|
|
461
|
-
if stats["count"] == 0:
|
|
462
|
-
return "Archive empty — diaries are archived automatically after 180 days."
|
|
463
|
-
return (
|
|
464
|
-
f"DIARY ARCHIVE STATS:\n"
|
|
465
|
-
f" Total: {stats['count']} archived diaries\n"
|
|
466
|
-
f" Range: {stats['oldest']} → {stats['newest']}\n"
|
|
467
|
-
f" Domains: {', '.join(stats['domains']) if stats['domains'] else 'N/A'}\n"
|
|
468
|
-
f"\nUse query, domain, year/month to search."
|
|
469
|
-
)
|
|
470
|
-
|
|
471
|
-
results = diary_archive_search(query=query, domain=domain, year=year, month=month, limit=limit)
|
|
472
|
-
if not results:
|
|
473
|
-
return f"No results in archive for: query='{query}' domain='{domain}' year={year} month={month}"
|
|
474
|
-
|
|
475
|
-
lines = [f"DIARY ARCHIVE — {len(results)} result(s):"]
|
|
476
|
-
for r in results:
|
|
477
|
-
lines.append(f"\n [#{r['id']}] {r['created_at'][:10]} [{r.get('domain', '?')}]")
|
|
478
|
-
lines.append(f" {r['summary'][:200]}")
|
|
479
|
-
if r.get('decisions'):
|
|
480
|
-
lines.append(f" Decisions: {r['decisions'][:150]}")
|
|
481
|
-
if r.get('mental_state'):
|
|
482
|
-
lines.append(f" Estado: {r['mental_state'][:100]}")
|
|
483
|
-
return "\n".join(lines)
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
def handle_diary_archive_read(diary_id: int = 0) -> str:
|
|
487
|
-
"""Read a single archived diary entry in full detail.
|
|
488
|
-
|
|
489
|
-
Args:
|
|
490
|
-
diary_id: The archive diary ID (from search results)
|
|
491
|
-
"""
|
|
492
|
-
if not diary_id:
|
|
493
|
-
return "ERROR: diary_id required. Use nexo_diary_archive_search to find IDs."
|
|
494
|
-
|
|
495
|
-
from db import diary_archive_read
|
|
496
|
-
entry = diary_archive_read(diary_id)
|
|
497
|
-
if not entry:
|
|
498
|
-
return f"Diary #{diary_id} not found in archive."
|
|
499
|
-
|
|
500
|
-
lines = [f"DIARY ARCHIVE #{entry['id']} — {entry['created_at']}"]
|
|
501
|
-
lines.append(f" Session: {entry['session_id']}")
|
|
502
|
-
lines.append(f" Domain: {entry.get('domain', 'N/A')}")
|
|
503
|
-
lines.append(f" Source: {entry.get('source', 'N/A')}")
|
|
504
|
-
lines.append(f"\nSUMMARY:\n {entry['summary']}")
|
|
505
|
-
if entry.get('decisions'):
|
|
506
|
-
lines.append(f"\nDECISIONS:\n {entry['decisions']}")
|
|
507
|
-
if entry.get('pending'):
|
|
508
|
-
lines.append(f"\nPENDING:\n {entry['pending']}")
|
|
509
|
-
if entry.get('mental_state'):
|
|
510
|
-
lines.append(f"\nMENTAL STATE:\n {entry['mental_state']}")
|
|
511
|
-
if entry.get('self_critique'):
|
|
512
|
-
lines.append(f"\nSELF-CRITIQUE:\n {entry['self_critique']}")
|
|
513
|
-
if entry.get('user_signals'):
|
|
514
|
-
lines.append(f"\nUSER SIGNALS:\n {entry['user_signals']}")
|
|
515
|
-
if entry.get('context_next'):
|
|
516
|
-
lines.append(f"\nNEXT SESSION CONTEXT:\n {entry['context_next']}")
|
|
517
|
-
return "\n".join(lines)
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
TOOLS = [
|
|
521
|
-
(handle_change_log, "nexo_change_log", "Log a code/config change with full context: what, why, trigger, affects, risks"),
|
|
522
|
-
(handle_change_search, "nexo_change_search", "Search past code changes — answers 'what did we change in X?' or 'why did we touch Y?'"),
|
|
523
|
-
(handle_change_commit, "nexo_change_commit", "Link a change log entry to its git commit hash"),
|
|
524
|
-
(handle_decision_log, "nexo_decision_log", "Log a non-trivial decision with reasoning, alternatives, and evidence"),
|
|
525
|
-
(handle_decision_outcome, "nexo_decision_outcome", "Record what actually happened after a past decision"),
|
|
526
|
-
(handle_decision_search, "nexo_decision_search", "Search past decisions — answers 'why did we do X?'"),
|
|
527
|
-
(handle_memory_review_queue, "nexo_memory_review_queue", "Show decisions and learnings that are due for review"),
|
|
528
|
-
(handle_session_diary_write, "nexo_session_diary_write", "Write end-of-session diary with decisions, discards, and context for next session"),
|
|
529
|
-
(handle_session_diary_read, "nexo_session_diary_read", "Read recent session diaries for context continuity"),
|
|
530
|
-
(handle_recall, "nexo_recall", "Search across ALL NEXO memory — changes, decisions, learnings, followups, diary, entities, .md files, code files. For deep historical context (older sessions, past work), also search diary_archive."),
|
|
531
|
-
(handle_diary_archive_search, "nexo_diary_archive_search", "Search the permanent diary archive (subconscious memory). Diaries older than 180d are moved here forever. Use for historical lookups: 'last year', 'months ago', 'in February', etc."),
|
|
532
|
-
(handle_diary_archive_read, "nexo_diary_archive_read", "Read a single archived diary entry in full detail. Get the ID from diary_archive_search."),
|
|
533
|
-
]
|
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
"""Evolution plugin — NEXO self-improvement tools for interactive sessions."""
|
|
2
|
-
|
|
3
|
-
import os
|
|
4
|
-
from db import get_latest_metrics, get_evolution_history, update_evolution_log_status, get_db
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
def handle_evolution_status() -> str:
|
|
8
|
-
"""Show current NEXO dimension scores and recent trend."""
|
|
9
|
-
metrics = get_latest_metrics()
|
|
10
|
-
if not metrics:
|
|
11
|
-
return "No evolution metrics recorded."
|
|
12
|
-
|
|
13
|
-
BARS = {
|
|
14
|
-
"episodic_memory": "Episodic Memory",
|
|
15
|
-
"autonomy": "Autonomy",
|
|
16
|
-
"proactivity": "Proactivity",
|
|
17
|
-
"self_improvement": "Self-improvement",
|
|
18
|
-
"agi": "AGI",
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
lines = ["NEXO EVOLUTION STATUS:"]
|
|
22
|
-
for key, label in BARS.items():
|
|
23
|
-
m = metrics.get(key)
|
|
24
|
-
if m:
|
|
25
|
-
score = m["score"]
|
|
26
|
-
delta = m["delta"]
|
|
27
|
-
bar = "█" * (score // 5) + "░" * (20 - score // 5)
|
|
28
|
-
delta_str = f" (+{delta})" if delta > 0 else f" ({delta})" if delta < 0 else " (=)"
|
|
29
|
-
lines.append(f" {label:<20} {bar} {score}%{delta_str}")
|
|
30
|
-
return "\n".join(lines)
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
def handle_evolution_history(limit: int = 10) -> str:
|
|
34
|
-
"""Show past evolution cycles and their outcomes.
|
|
35
|
-
|
|
36
|
-
Args:
|
|
37
|
-
limit: Number of entries to return (default 10)
|
|
38
|
-
"""
|
|
39
|
-
history = get_evolution_history(limit)
|
|
40
|
-
if not history:
|
|
41
|
-
return "No evolution history."
|
|
42
|
-
|
|
43
|
-
lines = [f"EVOLUTION HISTORY ({len(history)} entries):"]
|
|
44
|
-
for h in history:
|
|
45
|
-
status_icon = {"applied": "✓", "rolled_back": "✗", "proposed": "?",
|
|
46
|
-
"accepted": "✓✓", "rejected": "✗✗"}.get(h["status"], "·")
|
|
47
|
-
lines.append(f" {status_icon} #{h['id']} [{h['classification']}] {h['dimension']}")
|
|
48
|
-
lines.append(f" {h['proposal'][:100]}")
|
|
49
|
-
if h.get("test_result"):
|
|
50
|
-
lines.append(f" Test: {h['test_result'][:80]}")
|
|
51
|
-
if h.get("impact"):
|
|
52
|
-
lines.append(f" Impact: {h['impact']:+d}")
|
|
53
|
-
return "\n".join(lines)
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
def handle_evolution_propose() -> str:
|
|
57
|
-
"""Manually trigger an evolution analysis outside the weekly schedule.
|
|
58
|
-
This sets a flag that the Cortex wrapper reads on the next cycle.
|
|
59
|
-
"""
|
|
60
|
-
import json
|
|
61
|
-
from pathlib import Path
|
|
62
|
-
nexo_home = Path(os.environ.get("NEXO_HOME", str(Path.home() / ".nexo")))
|
|
63
|
-
# Check brain/ (canonical) first, fall back to cortex/ (legacy)
|
|
64
|
-
obj_file = nexo_home / "brain" / "evolution-objective.json"
|
|
65
|
-
if not obj_file.exists():
|
|
66
|
-
obj_file = nexo_home / "cortex" / "evolution-objective.json"
|
|
67
|
-
if not obj_file.exists():
|
|
68
|
-
return "ERROR: evolution-objective.json not found. Run the installer or create one in ~/.nexo/brain/"
|
|
69
|
-
try:
|
|
70
|
-
obj = json.loads(obj_file.read_text())
|
|
71
|
-
if not obj.get("evolution_enabled", True):
|
|
72
|
-
return f"Evolution is DISABLED: {obj.get('disabled_reason', 'unknown')}"
|
|
73
|
-
obj["force_next_cycle"] = True
|
|
74
|
-
obj_file.write_text(json.dumps(obj, indent=2, ensure_ascii=False))
|
|
75
|
-
return "Evolution cycle queued. Will run on next Cortex cycle (within ~10 min)."
|
|
76
|
-
except Exception as e:
|
|
77
|
-
return f"ERROR: {e}"
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
def handle_evolution_approve(log_id: int, notes: str = '') -> str:
|
|
81
|
-
"""Approve a pending Evolution proposal.
|
|
82
|
-
|
|
83
|
-
Args:
|
|
84
|
-
log_id: Evolution log entry ID to approve
|
|
85
|
-
notes: Optional notes from user
|
|
86
|
-
"""
|
|
87
|
-
update_evolution_log_status(log_id, "accepted",
|
|
88
|
-
test_result=f"Approved by user. {notes}".strip())
|
|
89
|
-
return f"Proposal #{log_id} APPROVED. Will be applied in next Evolution cycle."
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
def handle_evolution_reject(log_id: int, reason: str = '') -> str:
|
|
93
|
-
"""Reject a pending Evolution proposal.
|
|
94
|
-
|
|
95
|
-
Args:
|
|
96
|
-
log_id: Evolution log entry ID to reject
|
|
97
|
-
reason: Why this proposal was rejected
|
|
98
|
-
"""
|
|
99
|
-
update_evolution_log_status(log_id, "rejected",
|
|
100
|
-
test_result=f"Rejected: {reason}" if reason else "Rejected by user")
|
|
101
|
-
return f"Proposal #{log_id} REJECTED. Reason: {reason or 'no reason given'}"
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
TOOLS = [
|
|
105
|
-
(handle_evolution_status, "nexo_evolution_status",
|
|
106
|
-
"Show current NEXO dimension scores (episodic memory, autonomy, proactivity, self-improvement, AGI)"),
|
|
107
|
-
(handle_evolution_history, "nexo_evolution_history",
|
|
108
|
-
"Show past evolution cycles, proposals, and their outcomes"),
|
|
109
|
-
(handle_evolution_propose, "nexo_evolution_propose",
|
|
110
|
-
"Manually trigger an evolution analysis outside weekly schedule"),
|
|
111
|
-
(handle_evolution_approve, "nexo_evolution_approve",
|
|
112
|
-
"Approve a pending Evolution proposal (user only)"),
|
|
113
|
-
(handle_evolution_reject, "nexo_evolution_reject",
|
|
114
|
-
"Reject a pending Evolution proposal with reason"),
|
|
115
|
-
]
|