nexo-brain 5.3.13 → 5.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (230) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/bin/nexo-brain.js +52 -1
  3. package/package.json +1 -1
  4. package/src/crons/sync.py +18 -4
  5. package/src/dashboard/static/favicon 2.svg +32 -0
  6. package/src/dashboard/static/nexo-logo 2.png +0 -0
  7. package/src/dashboard/static/nexo-logo 2.svg +40 -0
  8. package/src/dashboard/static/style 2.css +2458 -0
  9. package/src/dashboard/templates/adaptive 2.html +118 -0
  10. package/src/dashboard/templates/artifacts 2.html +133 -0
  11. package/src/dashboard/templates/backups 2.html +136 -0
  12. package/src/dashboard/templates/base 2.html +417 -0
  13. package/src/dashboard/templates/calendar 2.html +591 -0
  14. package/src/dashboard/templates/chat 2.html +356 -0
  15. package/src/dashboard/templates/claims 2.html +259 -0
  16. package/src/dashboard/templates/cortex 2.html +321 -0
  17. package/src/dashboard/templates/credentials 2.html +128 -0
  18. package/src/dashboard/templates/crons 2.html +370 -0
  19. package/src/dashboard/templates/dashboard 2.html +494 -0
  20. package/src/dashboard/templates/dreams 2.html +252 -0
  21. package/src/dashboard/templates/email 2.html +160 -0
  22. package/src/dashboard/templates/evolution 2.html +189 -0
  23. package/src/dashboard/templates/feed 2.html +249 -0
  24. package/src/dashboard/templates/followup_health 2.html +170 -0
  25. package/src/dashboard/templates/graph 2.html +201 -0
  26. package/src/dashboard/templates/guard 2.html +259 -0
  27. package/src/dashboard/templates/inbox 2.html +251 -0
  28. package/src/dashboard/templates/memory 2.html +420 -0
  29. package/src/dashboard/templates/operations 2.html +608 -0
  30. package/src/dashboard/templates/plugins 2.html +185 -0
  31. package/src/dashboard/templates/protocol 2.html +199 -0
  32. package/src/dashboard/templates/rules 2.html +246 -0
  33. package/src/dashboard/templates/sentiment 2.html +247 -0
  34. package/src/dashboard/templates/sessions 2.html +218 -0
  35. package/src/dashboard/templates/skills 2.html +329 -0
  36. package/src/dashboard/templates/somatic 2.html +73 -0
  37. package/src/dashboard/templates/triggers 2.html +133 -0
  38. package/src/dashboard/templates/trust 2.html +360 -0
  39. package/src/db/__init__ 2.py +259 -0
  40. package/src/db/_core 2.py +437 -0
  41. package/src/db/_credentials 2.py +124 -0
  42. package/src/db/_entities.py +1 -1
  43. package/src/db/_episodic 2.py +762 -0
  44. package/src/db/_evolution 2.py +54 -0
  45. package/src/db/_fts 2.py +406 -0
  46. package/src/db/_goal_profiles 2.py +376 -0
  47. package/src/db/_hot_context 2.py +660 -0
  48. package/src/db/_outcomes 2.py +800 -0
  49. package/src/db/_personal_scripts 2.py +582 -0
  50. package/src/db/_sessions 2.py +330 -0
  51. package/src/db/_tasks 2.py +91 -0
  52. package/src/db/_watchers 2.py +173 -0
  53. package/src/doctor/formatters 2.py +52 -0
  54. package/src/doctor/models 2.py +69 -0
  55. package/src/doctor/planes 2.py +87 -0
  56. package/src/doctor/providers/__init__ 2.py +1 -0
  57. package/src/doctor/providers/deep 2.py +367 -0
  58. package/src/evolution_cycle 2.py +519 -0
  59. package/src/hooks/auto_capture 2.py +208 -0
  60. package/src/hooks/caffeinate-guard 2.sh +8 -0
  61. package/src/hooks/capture-session 2.sh +21 -0
  62. package/src/hooks/capture-tool-logs 2.sh +158 -0
  63. package/src/hooks/daily-briefing-check 2.sh +33 -0
  64. package/src/hooks/heartbeat-enforcement 2.py +90 -0
  65. package/src/hooks/heartbeat-posttool 2.sh +18 -0
  66. package/src/hooks/inbox-hook 2.sh +76 -0
  67. package/src/hooks/post-compact 2.sh +152 -0
  68. package/src/hooks/pre-compact 2.sh +169 -0
  69. package/src/hooks/protocol-guardrail 2.sh +10 -0
  70. package/src/hooks/protocol-pretool-guardrail 2.sh +9 -0
  71. package/src/hooks/session-stop 2.sh +52 -0
  72. package/src/kg_populate 2.py +292 -0
  73. package/src/maintenance 2.py +53 -0
  74. package/src/memory_backends 2.py +71 -0
  75. package/src/migrate_embeddings 2.py +124 -0
  76. package/src/nexo_sdk 2.py +103 -0
  77. package/src/observability 2.py +199 -0
  78. package/src/plugin_loader 2.py +217 -0
  79. package/src/plugins/__init__ 2.py +0 -0
  80. package/src/plugins/agents.py +10 -3
  81. package/src/plugins/artifact_registry 2.py +450 -0
  82. package/src/plugins/backup 2.py +127 -0
  83. package/src/plugins/claims_tools 2.py +119 -0
  84. package/src/plugins/cognitive_memory 2.py +609 -0
  85. package/src/plugins/core_rules 2.py +252 -0
  86. package/src/plugins/cortex 2.py +1155 -0
  87. package/src/plugins/entities 2.py +67 -0
  88. package/src/plugins/episodic_memory 2.py +560 -0
  89. package/src/plugins/evolution 2.py +167 -0
  90. package/src/plugins/goal_engine 2.py +142 -0
  91. package/src/plugins/guard 2.py +862 -0
  92. package/src/plugins/impact 2.py +29 -0
  93. package/src/plugins/knowledge_graph_tools 2.py +137 -0
  94. package/src/plugins/media_memory_tools 2.py +98 -0
  95. package/src/plugins/memory_export 2.py +196 -0
  96. package/src/plugins/outcomes 2.py +130 -0
  97. package/src/plugins/personal_scripts 2.py +117 -0
  98. package/src/plugins/preferences 2.py +47 -0
  99. package/src/plugins/protocol 2.py +1449 -0
  100. package/src/plugins/schedule.py +2 -1
  101. package/src/plugins/simple_api 2.py +106 -0
  102. package/src/plugins/skills 2.py +341 -0
  103. package/src/plugins/state_watchers 2.py +79 -0
  104. package/src/plugins/update 2.py +986 -0
  105. package/src/plugins/user_state_tools 2.py +43 -0
  106. package/src/plugins/workflow 2.py +588 -0
  107. package/src/protocol_settings 2.py +59 -0
  108. package/src/public_contribution 2.py +466 -0
  109. package/src/public_evolution_queue 2.py +241 -0
  110. package/src/requirements 2.txt +14 -0
  111. package/src/requirements.txt +1 -1
  112. package/src/retroactive_learnings 2.py +373 -0
  113. package/src/rules/__init__ 2.py +0 -0
  114. package/src/rules/core-rules 2.json +331 -0
  115. package/src/rules/migrate 2.py +207 -0
  116. package/src/runtime_power 2.py +874 -0
  117. package/src/runtime_power.py +18 -1
  118. package/src/script_registry 2.py +1559 -0
  119. package/src/scripts/check-context 2.py +272 -0
  120. package/src/scripts/deep-sleep/apply_findings 2.py +2327 -0
  121. package/src/scripts/deep-sleep/collect 2.py +928 -0
  122. package/src/scripts/deep-sleep/extract 2.py +330 -0
  123. package/src/scripts/deep-sleep/extract-prompt 2.md +285 -0
  124. package/src/scripts/deep-sleep/synthesize 2.py +312 -0
  125. package/src/scripts/deep-sleep/synthesize-prompt 2.md +336 -0
  126. package/src/scripts/nexo-agent-run 2.py +75 -0
  127. package/src/scripts/nexo-auto-update 2.py +6 -0
  128. package/src/scripts/nexo-backup 2.sh +25 -0
  129. package/src/scripts/nexo-brain-activation 2.sh +140 -0
  130. package/src/scripts/nexo-catchup 2.py +300 -0
  131. package/src/scripts/nexo-cognitive-decay 2.py +257 -0
  132. package/src/scripts/nexo-cortex-cycle 2.py +293 -0
  133. package/src/scripts/nexo-cron-wrapper 2.sh +53 -0
  134. package/src/scripts/nexo-cron-wrapper.sh +7 -0
  135. package/src/scripts/nexo-daily-self-audit 2.py +2161 -0
  136. package/src/scripts/nexo-dashboard 2.sh +29 -0
  137. package/src/scripts/nexo-deep-sleep 2.sh +86 -0
  138. package/src/scripts/nexo-evolution-run 2.py +1664 -0
  139. package/src/scripts/nexo-followup-hygiene 2.py +139 -0
  140. package/src/scripts/nexo-hook-record 2.py +42 -0
  141. package/src/scripts/nexo-immune 2.py +936 -0
  142. package/src/scripts/nexo-impact-scorer 2.py +117 -0
  143. package/src/scripts/nexo-inbox-hook 2.sh +74 -0
  144. package/src/scripts/nexo-install 2.py +6 -0
  145. package/src/scripts/nexo-learning-housekeep 2.py +401 -0
  146. package/src/scripts/nexo-learning-validator 2.py +266 -0
  147. package/src/scripts/nexo-migrate 2.py +260 -0
  148. package/src/scripts/nexo-outcome-checker 2.py +127 -0
  149. package/src/scripts/nexo-postmortem-consolidator 2.py +456 -0
  150. package/src/scripts/nexo-pre-commit 2.py +120 -0
  151. package/src/scripts/nexo-prevent-sleep 2.sh +35 -0
  152. package/src/scripts/nexo-proactive-dashboard 2.py +354 -0
  153. package/src/scripts/nexo-reflection 2.py +256 -0
  154. package/src/scripts/nexo-runtime-preflight 2.py +274 -0
  155. package/src/scripts/nexo-sleep 2.py +631 -0
  156. package/src/scripts/nexo-snapshot-restore 2.sh +35 -0
  157. package/src/scripts/nexo-sync-clients 2.py +16 -0
  158. package/src/scripts/nexo-synthesis 2.py +475 -0
  159. package/src/scripts/nexo-tcc-approve 2.sh +79 -0
  160. package/src/scripts/nexo-update 2.sh +306 -0
  161. package/src/scripts/nexo-watchdog 2.sh +1207 -0
  162. package/src/scripts/nexo-watchdog-smoke 2.py +119 -0
  163. package/src/scripts/rehydrate_learnings_from_archive 2.py +245 -0
  164. package/src/server 2.py +1296 -0
  165. package/src/skills/run-nexo-audit-phase/guide 2.md +43 -0
  166. package/src/skills/run-nexo-audit-phase/skill 2.json +59 -0
  167. package/src/skills/run-nexo-core-fix-cycle/guide 2.md +17 -0
  168. package/src/skills/run-nexo-core-fix-cycle/script 2.py +276 -0
  169. package/src/skills/run-nexo-core-fix-cycle/skill 2.json +58 -0
  170. package/src/skills/run-release-final-audit/guide 2.md +16 -0
  171. package/src/skills/run-release-final-audit/script 2.py +259 -0
  172. package/src/skills/run-release-final-audit/skill 2.json +77 -0
  173. package/src/skills/run-runtime-doctor/guide 2.md +12 -0
  174. package/src/skills/run-runtime-doctor/script 2.py +21 -0
  175. package/src/skills/run-runtime-doctor/skill 2.json +25 -0
  176. package/src/skills_runtime 2.py +932 -0
  177. package/src/state_watchers_runtime 2.py +475 -0
  178. package/src/storage_router 2.py +32 -0
  179. package/src/system_catalog 2.py +786 -0
  180. package/src/tools_coordination 2.py +103 -0
  181. package/src/tools_credentials 2.py +68 -0
  182. package/src/tools_drive 2.py +487 -0
  183. package/src/tools_hot_context 2.py +163 -0
  184. package/src/tools_learnings 2.py +612 -0
  185. package/src/tools_menu 2.py +229 -0
  186. package/src/tools_reminders 2.py +88 -0
  187. package/src/tools_reminders_crud 2.py +363 -0
  188. package/src/tools_sessions 2.py +1054 -0
  189. package/src/tools_system_catalog 2.py +19 -0
  190. package/src/tools_task_history 2.py +57 -0
  191. package/src/tools_transcripts 2.py +98 -0
  192. package/src/transcript_utils 2.py +412 -0
  193. package/src/user_context 2.py +46 -0
  194. package/src/user_data_portability 2.py +328 -0
  195. package/src/user_state_model 2.py +170 -0
  196. package/templates/CLAUDE.md 2.template +108 -0
  197. package/templates/CODEX.AGENTS.md 2.template +66 -0
  198. package/templates/launchagents/README 2.md +132 -0
  199. package/templates/launchagents/com.nexo.auto-close-sessions 2.plist +39 -0
  200. package/templates/launchagents/com.nexo.auto-close-sessions.plist +1 -1
  201. package/templates/launchagents/com.nexo.catchup 2.plist +39 -0
  202. package/templates/launchagents/com.nexo.catchup.plist +1 -1
  203. package/templates/launchagents/com.nexo.cognitive-decay 2.plist +40 -0
  204. package/templates/launchagents/com.nexo.dashboard 2.plist +43 -0
  205. package/templates/launchagents/com.nexo.dashboard.plist +1 -1
  206. package/templates/launchagents/com.nexo.deep-sleep 2.plist +43 -0
  207. package/templates/launchagents/com.nexo.deep-sleep.plist +1 -1
  208. package/templates/launchagents/com.nexo.evolution 2.plist +44 -0
  209. package/templates/launchagents/com.nexo.evolution.plist +1 -1
  210. package/templates/launchagents/com.nexo.followup-hygiene 2.plist +45 -0
  211. package/templates/launchagents/com.nexo.followup-hygiene.plist +1 -1
  212. package/templates/launchagents/com.nexo.immune 2.plist +41 -0
  213. package/templates/launchagents/com.nexo.immune.plist +1 -1
  214. package/templates/launchagents/com.nexo.postmortem 2.plist +45 -0
  215. package/templates/launchagents/com.nexo.postmortem.plist +1 -1
  216. package/templates/launchagents/com.nexo.self-audit 2.plist +47 -0
  217. package/templates/launchagents/com.nexo.self-audit.plist +1 -1
  218. package/templates/launchagents/com.nexo.synthesis 2.plist +45 -0
  219. package/templates/launchagents/com.nexo.synthesis.plist +1 -1
  220. package/templates/launchagents/com.nexo.watchdog 2.plist +37 -0
  221. package/templates/launchagents/com.nexo.watchdog.plist +1 -1
  222. package/templates/nexo_helper 2.py +301 -0
  223. package/templates/openclaw 2.json +13 -0
  224. package/templates/plugin-template 2.py +40 -0
  225. package/templates/script-template 2.py +59 -0
  226. package/templates/script-template 2.sh +13 -0
  227. package/templates/script-template.py +5 -4
  228. package/templates/skill-script-template 2.py +48 -0
  229. package/templates/skill-script-template.py +2 -1
  230. package/templates/skill-template 2.md +33 -0
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ """Small CLI wrapper around the schedule-configured automation backend."""
5
+
6
+ import argparse
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+
11
+
12
+ _SCRIPT_DIR = Path(__file__).resolve().parent
13
+ _DEFAULT_RUNTIME_ROOT = _SCRIPT_DIR.parent
14
+ NEXO_CODE = Path(os.environ.get("NEXO_CODE", str(_DEFAULT_RUNTIME_ROOT)))
15
+ if str(NEXO_CODE) not in sys.path:
16
+ sys.path.insert(0, str(NEXO_CODE))
17
+
18
+ from agent_runner import AutomationBackendUnavailableError, run_automation_prompt
19
+
20
+
21
+ def _read_text(path: str | None) -> str:
22
+ if not path:
23
+ return ""
24
+ return Path(path).expanduser().read_text()
25
+
26
+
27
+ def main(argv: list[str] | None = None) -> int:
28
+ parser = argparse.ArgumentParser(description="Run a prompt through the configured NEXO automation backend.")
29
+ parser.add_argument("--prompt", default="", help="Prompt text")
30
+ parser.add_argument("--prompt-file", default="", help="Read prompt text from a file")
31
+ parser.add_argument("--cwd", default="", help="Working directory for the backend")
32
+ parser.add_argument("--task-profile", default="", help="Automation task profile: default|fast|balanced|deep")
33
+ parser.add_argument("--model", default="", help="Backend model hint")
34
+ parser.add_argument("--reasoning-effort", default="", help="Backend reasoning effort/profile")
35
+ parser.add_argument("--timeout", type=int, default=21600, help="Timeout in seconds")
36
+ parser.add_argument("--output-format", default="text", help="Requested output format")
37
+ parser.add_argument("--allowed-tools", default="", help="Claude-style allowed tools contract")
38
+ parser.add_argument("--append-system-prompt", default="", help="Extra system prompt text")
39
+ parser.add_argument("--append-system-prompt-file", default="", help="Read extra system prompt from a file")
40
+ args = parser.parse_args(argv)
41
+
42
+ prompt = args.prompt or _read_text(args.prompt_file)
43
+ if not prompt:
44
+ prompt = sys.stdin.read()
45
+ if not prompt.strip():
46
+ print("No prompt provided.", file=sys.stderr)
47
+ return 1
48
+
49
+ append_system_prompt = args.append_system_prompt or _read_text(args.append_system_prompt_file)
50
+
51
+ try:
52
+ result = run_automation_prompt(
53
+ prompt,
54
+ cwd=args.cwd or None,
55
+ task_profile=args.task_profile,
56
+ model=args.model,
57
+ reasoning_effort=args.reasoning_effort,
58
+ timeout=args.timeout,
59
+ output_format=args.output_format,
60
+ append_system_prompt=append_system_prompt,
61
+ allowed_tools=args.allowed_tools,
62
+ )
63
+ except AutomationBackendUnavailableError as exc:
64
+ print(str(exc), file=sys.stderr)
65
+ return 2
66
+
67
+ if result.stdout:
68
+ print(result.stdout, end="" if result.stdout.endswith("\n") else "\n")
69
+ if result.stderr:
70
+ print(result.stderr, file=sys.stderr, end="" if result.stderr.endswith("\n") else "\n")
71
+ return int(result.returncode)
72
+
73
+
74
+ if __name__ == "__main__":
75
+ raise SystemExit(main())
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env python3
2
+ """DEPRECATED: Updates are handled automatically by NEXO on startup."""
3
+ import sys
4
+ print("This script is deprecated. NEXO auto-updates on startup.")
5
+ print("To update manually, use the nexo_update MCP tool.")
6
+ sys.exit(0)
@@ -0,0 +1,25 @@
1
+ #!/bin/bash
2
+ # NEXO DB hourly backup — crontab: 0 * * * * $NEXO_HOME/scripts/nexo-backup.sh
3
+ NEXO_HOME="${NEXO_HOME:-$HOME/.nexo}"
4
+ NEXO_DIR="$NEXO_HOME"
5
+ BACKUP_DIR="$NEXO_HOME/backups"
6
+ WEEKLY_DIR="$BACKUP_DIR/weekly"
7
+ DB="$NEXO_HOME/data/nexo.db"
8
+ RETENTION_HOURS=48
9
+
10
+ mkdir -p "$BACKUP_DIR" "$WEEKLY_DIR"
11
+
12
+ # Hourly backup
13
+ TIMESTAMP=$(date +%Y-%m-%d-%H%M)
14
+ sqlite3 "$DB" ".backup '$BACKUP_DIR/nexo-$TIMESTAMP.db'"
15
+
16
+ # Weekly backup — save one per week (Sundays)
17
+ WEEK=$(date +%Y-W%V)
18
+ WEEKLY_FILE="$WEEKLY_DIR/weekly-$WEEK.db"
19
+ if [ ! -f "$WEEKLY_FILE" ] && [ "$(date +%u)" = "7" ]; then
20
+ cp "$BACKUP_DIR/nexo-$TIMESTAMP.db" "$WEEKLY_FILE"
21
+ fi
22
+
23
+ # Cleanup: hourly >48h, weekly >90 days
24
+ find "$BACKUP_DIR" -maxdepth 1 -name "nexo-*.db" -mmin +$((RETENTION_HOURS * 60)) -delete
25
+ find "$WEEKLY_DIR" -name "weekly-*.db" -mtime +90 -delete
@@ -0,0 +1,140 @@
1
+ #!/usr/bin/env bash
2
+ # nexo-brain-activation.sh — NF24: Spontaneous Activation
3
+ # Reads user_model.json, detects significant shifts, and generates insights
4
+ # for NEXO startup. If nothing relevant: exit 0 with no output.
5
+
6
+ set -euo pipefail
7
+
8
+ BRAIN_DIR="~/.nexo/brain"
9
+ MODEL_FILE="$BRAIN_DIR/user_model.json"
10
+ SUMMARIES_DIR="$BRAIN_DIR/daily_summaries"
11
+
12
+ # --- Guard: required file ---
13
+ if [[ ! -f "$MODEL_FILE" ]]; then
14
+ exit 0
15
+ fi
16
+
17
+ # --- Inline Python to parse JSON and analyze ---
18
+ python3 - <<'PYEOF'
19
+ import json
20
+ import sys
21
+ import os
22
+ import glob
23
+ from datetime import datetime, timedelta
24
+
25
+ BRAIN_DIR = os.path.expanduser("~/.nexo/brain")
26
+ MODEL_FILE = os.path.join(BRAIN_DIR, "user_model.json")
27
+ SUMMARIES_DIR = os.path.join(BRAIN_DIR, "daily_summaries")
28
+
29
+ # ── Load model ──────────────────────────────────────────────────────────
30
+ try:
31
+ with open(MODEL_FILE) as f:
32
+ model = json.load(f)
33
+ except Exception:
34
+ sys.exit(0)
35
+
36
+ insights = []
37
+
38
+ # ── 1. Analyze evolution_log — last 3-5 entries ─────────────────────
39
+ evolution = model.get("evolution_log", [])
40
+ recent = evolution[-5:] if len(evolution) >= 5 else evolution
41
+
42
+ # Detect entries from the last 3 days
43
+ today = datetime.now().date()
44
+ cutoff = today - timedelta(days=3)
45
+
46
+ recent_obs = []
47
+ for entry in recent:
48
+ try:
49
+ entry_date = datetime.strptime(entry["date"], "%Y-%m-%d").date()
50
+ if entry_date >= cutoff:
51
+ recent_obs.append(entry)
52
+ except Exception:
53
+ pass
54
+
55
+ if recent_obs:
56
+ for obs in recent_obs[-2:]: # max 2 most recent
57
+ insights.append(obs["observation"].strip())
58
+
59
+ # ── 2. Detect trait changes >0.1 between entries (if history exists) ──
60
+ # The current model only has a snapshot; if in the future there is history
61
+ # in evolution_log with trait deltas, this can be expanded here.
62
+ # Detect the most extreme trait as the dominant identity signal.
63
+ traits = model.get("traits", {})
64
+ if traits:
65
+ dominant = max(traits, key=lambda k: traits[k])
66
+ dominant_val = traits[dominant]
67
+ weakest = min(traits, key=lambda k: traits[k])
68
+ weakest_val = traits[weakest]
69
+ # Only report if extreme (>0.9 or <0.2) to avoid noise
70
+ if dominant_val >= 0.9:
71
+ insights.append(f"Dominant trait: {dominant}={dominant_val} (highest recorded)")
72
+ if weakest_val <= 0.2:
73
+ insights.append(f"Lowest trait: {weakest}={weakest_val} (low tolerance active)")
74
+
75
+ # ── 3. Recent contradictions (last 3 days) ─────────────────────────
76
+ contradictions = model.get("contradictions", [])
77
+ recent_contradictions = []
78
+ for c in contradictions:
79
+ try:
80
+ c_date = datetime.strptime(c["date"], "%Y-%m-%d").date()
81
+ if c_date >= cutoff:
82
+ recent_contradictions.append(c)
83
+ except Exception:
84
+ pass
85
+
86
+ for c in recent_contradictions:
87
+ insights.append(f"Contradiction detected: {c['description'].strip()}")
88
+
89
+ # ── 4. Current active focus ─────────────────────────────────────────────────
90
+ current_focus = model.get("current_focus", [])
91
+ # Only include if there are focus items (and it's not initial startup)
92
+ if len(current_focus) > 0 and len(insights) == 0:
93
+ # If no other insights, report focus as minimum context
94
+ focus_str = ", ".join(current_focus)
95
+ insights.append(f"Current focus: {focus_str}")
96
+
97
+ # ── 5. Goals: active/dormant changes ─────────────────────────────────────
98
+ goals_active = model.get("goals_active", [])
99
+ goals_dormant = model.get("goals_dormant", [])
100
+ # If there are dormant goals, mention them (may need reactivation)
101
+ if goals_dormant:
102
+ insights.append(f"Goal dormant: {goals_dormant[0]}")
103
+
104
+ # ── Read last daily summary ─────────────────────────────────────────────
105
+ summary_text = ""
106
+ try:
107
+ files = sorted(glob.glob(os.path.join(SUMMARIES_DIR, "*.md")))
108
+ if files:
109
+ with open(files[-1]) as f:
110
+ lines = [l.rstrip() for l in f.readlines() if l.strip()]
111
+ # Take up to 3 lines of content (exclude header)
112
+ content_lines = [l for l in lines if not l.startswith("# Resumen") and not l.startswith("# Summary")]
113
+ summary_text = " | ".join(content_lines[:3])
114
+ except Exception:
115
+ pass
116
+
117
+ # ── Output ────────────────────────────────────────────────────────────────
118
+ # If no real insights, exit without output
119
+ if not insights and not summary_text:
120
+ sys.exit(0)
121
+
122
+ # Deduplicate and limit
123
+ seen = set()
124
+ unique_insights = []
125
+ for ins in insights:
126
+ key = ins[:60]
127
+ if key not in seen:
128
+ seen.add(key)
129
+ unique_insights.append(ins)
130
+
131
+ if unique_insights:
132
+ print("BRAIN_INSIGHTS:")
133
+ for ins in unique_insights[:5]:
134
+ print(f"- {ins}")
135
+
136
+ if summary_text:
137
+ print("RECENT_SUMMARY:")
138
+ print(summary_text[:400])
139
+
140
+ PYEOF
@@ -0,0 +1,300 @@
1
+ #!/usr/bin/env python3
2
+ """NEXO Catch-Up — recover missed core cron windows after boot/wake.
3
+
4
+ Recovery is driven by the explicit manifest contract plus cron_runs.
5
+ Legacy .catchup-state.json is now only a fallback for pre-wrapper history.
6
+ """
7
+
8
+ import fcntl
9
+ import json
10
+ import os
11
+ import subprocess
12
+ import sys
13
+ from datetime import datetime
14
+ from pathlib import Path
15
+
16
+
17
+ try:
18
+ from client_preferences import resolve_user_model as _resolve_user_model
19
+ _USER_MODEL = _resolve_user_model()
20
+ except Exception:
21
+ _USER_MODEL = ""
22
+
23
+ _SCRIPT_DIR = Path(__file__).resolve().parent
24
+ _DEFAULT_RUNTIME_ROOT = _SCRIPT_DIR.parent
25
+ _runtime_root = Path(os.environ.get("NEXO_CODE", str(_DEFAULT_RUNTIME_ROOT)))
26
+ if str(_runtime_root) not in sys.path:
27
+ sys.path.insert(0, str(_runtime_root))
28
+
29
+ from agent_runner import AutomationBackendUnavailableError, probe_automation_backend, run_automation_prompt
30
+ from cron_recovery import catchup_candidates
31
+
32
+ HOME = Path.home()
33
+ NEXO_HOME = Path(os.environ.get("NEXO_HOME", str(HOME / ".nexo")))
34
+
35
+
36
+ def _resolve_claude_cli() -> Path:
37
+ """Find claude CLI: saved path > PATH > common locations."""
38
+ saved = NEXO_HOME / "config" / "claude-cli-path"
39
+ if saved.exists():
40
+ p = Path(saved.read_text().strip())
41
+ if p.exists():
42
+ return p
43
+ import shutil
44
+ found = shutil.which("claude")
45
+ if found:
46
+ return Path(found)
47
+ for candidate in [
48
+ HOME / ".local" / "bin" / "claude",
49
+ HOME / ".npm-global" / "bin" / "claude",
50
+ Path("/usr/local/bin/claude"),
51
+ ]:
52
+ if candidate.exists():
53
+ return candidate
54
+ return HOME / ".local" / "bin" / "claude" # last resort
55
+
56
+
57
+ CLAUDE_CLI = _resolve_claude_cli()
58
+ LOG_DIR = NEXO_HOME / "logs"
59
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
60
+ LOG_FILE = LOG_DIR / "catchup.log"
61
+ STATE_FILE = NEXO_HOME / "operations" / ".catchup-state.json"
62
+ LOCK_FILE = NEXO_HOME / "operations" / ".catchup.lock"
63
+
64
+ SCRIPTS = NEXO_HOME / "scripts"
65
+ WRAPPER = SCRIPTS / "nexo-cron-wrapper.sh"
66
+
67
+ # Resolve Python: prefer NEXO's venv, then the same Python running this script
68
+ def _resolve_python() -> str:
69
+ """Find the best Python to use for subprocess calls."""
70
+ # Check for NEXO_CODE env var pointing to the repo's src/
71
+ nexo_code = os.environ.get("NEXO_CODE", "")
72
+ if nexo_code:
73
+ venv_python = Path(nexo_code).parent / ".venv" / "bin" / "python"
74
+ if venv_python.exists():
75
+ return str(venv_python)
76
+ # Check for venv relative to NEXO_HOME
77
+ venv_python = NEXO_HOME / ".venv" / "bin" / "python"
78
+ if venv_python.exists():
79
+ return str(venv_python)
80
+ # Fall back to the same Python running this script
81
+ return sys.executable
82
+
83
+ NEXO_PYTHON = _resolve_python()
84
+
85
+
86
+ def log(msg: str):
87
+ ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
88
+ line = f"[{ts}] {msg}"
89
+ print(line, flush=True)
90
+ with open(LOG_FILE, "a") as f:
91
+ f.write(line + "\n")
92
+
93
+
94
+ def load_state() -> dict:
95
+ if STATE_FILE.exists():
96
+ try:
97
+ return json.loads(STATE_FILE.read_text())
98
+ except Exception:
99
+ pass
100
+ return {}
101
+
102
+
103
+ def save_state(state: dict):
104
+ STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
105
+ STATE_FILE.write_text(json.dumps(state, indent=2))
106
+
107
+
108
+ def _resolve_runtime_command(script_type: str) -> str:
109
+ if script_type == "shell":
110
+ return "/bin/bash"
111
+ if script_type == "node":
112
+ return "node"
113
+ if script_type == "php":
114
+ return "php"
115
+ return NEXO_PYTHON
116
+
117
+
118
+ def _acquire_lock():
119
+ LOCK_FILE.parent.mkdir(parents=True, exist_ok=True)
120
+ handle = LOCK_FILE.open("w")
121
+ try:
122
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
123
+ except BlockingIOError:
124
+ handle.close()
125
+ return None
126
+ handle.write(str(os.getpid()))
127
+ handle.flush()
128
+ return handle
129
+
130
+
131
+ def _heal_personal_schedules() -> dict:
132
+ """Recreate declared personal schedules before catch-up checks missed windows."""
133
+ summary = {"created": 0, "repaired": 0, "invalid": 0, "error": ""}
134
+ try:
135
+ from script_registry import reconcile_personal_scripts
136
+ result = reconcile_personal_scripts(dry_run=False)
137
+ ensured = result.get("ensure_schedules", {})
138
+ summary["created"] = len(ensured.get("created", []))
139
+ summary["repaired"] = len(ensured.get("repaired", []))
140
+ summary["invalid"] = len(ensured.get("invalid", []))
141
+ if summary["created"] or summary["repaired"]:
142
+ log(
143
+ "Repaired declared personal schedules before catch-up: "
144
+ f"{summary['created']} created, {summary['repaired']} repaired."
145
+ )
146
+ if summary["invalid"]:
147
+ log(f"WARNING: {summary['invalid']} declared personal schedules are invalid.")
148
+ except Exception as e:
149
+ summary["error"] = str(e)
150
+ log(f"Personal schedule self-heal skipped: {e}")
151
+ return summary
152
+
153
+
154
+ def run_task(candidate: dict, state: dict) -> bool:
155
+ """Execute a task and update state."""
156
+ name = candidate["cron_id"]
157
+ raw_script = str(candidate.get("script", ""))
158
+ script_candidate = Path(raw_script)
159
+ if script_candidate.is_absolute():
160
+ script_path = script_candidate
161
+ else:
162
+ script_path = SCRIPTS / script_candidate.name
163
+ script_name = script_path.name
164
+ if not script_path.exists():
165
+ log(f" SKIP {name}: script not found ({script_path})")
166
+ return False
167
+
168
+ runtime_cmd = _resolve_runtime_command(candidate.get("type", "python"))
169
+ if WRAPPER.exists():
170
+ command = ["/bin/bash", str(WRAPPER), name, runtime_cmd, str(script_path)]
171
+ else:
172
+ command = [runtime_cmd, str(script_path)]
173
+
174
+ log(f" RUNNING {name}: {script_name}")
175
+ try:
176
+ result = subprocess.run(
177
+ command,
178
+ capture_output=True, text=True, timeout=21600,
179
+ env={**os.environ, "HOME": str(HOME), "NEXO_CATCHUP": "1"}
180
+ )
181
+ if result.returncode == 0:
182
+ log(f" OK {name} (exit 0)")
183
+ state[name] = datetime.now().isoformat()
184
+ save_state(state)
185
+ return True
186
+ else:
187
+ log(f" FAIL {name} (exit {result.returncode})")
188
+ if result.stderr:
189
+ log(f" stderr: {result.stderr[:300]}")
190
+ return False
191
+ except subprocess.TimeoutExpired:
192
+ log(f" TIMEOUT {name} (21600s)")
193
+ return False
194
+ except Exception as e:
195
+ log(f" ERROR {name}: {e}")
196
+ return False
197
+
198
+
199
+ def main():
200
+ log("=== NEXO Catch-Up starting (boot/wake) ===")
201
+ lock_handle = _acquire_lock()
202
+ if lock_handle is None:
203
+ log("Catch-Up already running; skipping overlapping invocation.")
204
+ return
205
+
206
+ ran = 0
207
+ skipped = 0
208
+ skipped_out_of_window = 0
209
+ try:
210
+ _heal_personal_schedules()
211
+ state = load_state()
212
+ tasks = catchup_candidates()
213
+
214
+ for candidate in tasks:
215
+ name = candidate["cron_id"]
216
+ if not candidate.get("missed"):
217
+ skipped += 1
218
+ continue
219
+ if not candidate.get("within_window"):
220
+ skipped_out_of_window += 1
221
+ log(
222
+ f" SKIP {name}: missed window is {candidate['age_seconds']}s old "
223
+ f"(max_catchup_age={candidate['contract']['max_catchup_age']}s)"
224
+ )
225
+ continue
226
+ due_at = candidate["last_due_at"].astimezone().strftime("%Y-%m-%d %H:%M")
227
+ log(f" {name} — missed scheduled run due at {due_at}, catching up...")
228
+ if run_task(candidate, state):
229
+ ran += 1
230
+
231
+ if ran == 0 and skipped_out_of_window == 0:
232
+ log("All tasks up to date, nothing to catch up.")
233
+ elif ran >= 3:
234
+ # Many tasks caught up — ask CLI to assess system state
235
+ _cli_post_catchup_assessment(ran, skipped, state)
236
+ else:
237
+ suffix = f", {skipped_out_of_window} outside recovery window" if skipped_out_of_window else ""
238
+ log(f"Caught up {ran} tasks, {skipped} already current{suffix}.")
239
+
240
+ log("=== Catch-Up complete ===")
241
+ finally:
242
+ lock_handle.close()
243
+
244
+
245
+ def _cli_post_catchup_assessment(ran: int, skipped: int, state: dict):
246
+ """When 3+ tasks were missed, use CLI to assess if there are concerns."""
247
+ probe = probe_automation_backend(timeout=30)
248
+ if not probe.get("ok"):
249
+ print(
250
+ f"[{datetime.now().strftime('%H:%M:%S')}] "
251
+ f"Automation backend unavailable. Skipping CLI analysis. ({probe.get('reason') or probe.get('stderr') or 'not ready'})"
252
+ )
253
+ return
254
+
255
+ assessment_file = LOG_DIR / "catchup-assessment.md"
256
+ state_summary = json.dumps(state, indent=2, default=str)
257
+
258
+ prompt = f"""You are the NEXO Catch-Up system. The Mac was off/asleep and {ran} scheduled tasks just ran as catch-up ({skipped} were already current).
259
+
260
+ Task run state (timestamps of last successful runs):
261
+ {state_summary}
262
+
263
+ Assess:
264
+ 1. How long was the system likely offline? (compare timestamps to now)
265
+ 2. Are there any tasks that depend on each other where order matters?
266
+ 3. Any tasks that may have produced stale results because they ran late?
267
+ 4. Should any task be re-run at its normal time today?
268
+
269
+ Write a brief assessment (max 20 lines) to: {assessment_file}
270
+
271
+ Format:
272
+ ## Catch-Up Assessment — {datetime.now().strftime('%Y-%m-%d %H:%M')}
273
+ - Offline duration: ~Xh
274
+ - Tasks caught up: {ran}
275
+ - Concerns: ...
276
+ - Recommendation: ..."""
277
+
278
+ log(f"Caught up {ran} tasks — running CLI assessment...")
279
+ try:
280
+ result = run_automation_prompt(
281
+ prompt,
282
+ model=_USER_MODEL or "opus",
283
+ timeout=21600,
284
+ output_format="text",
285
+ allowed_tools="Read,Write,Edit,Glob,Grep,Bash,mcp__nexo__*",
286
+ )
287
+ if result.returncode == 0:
288
+ log(f"Assessment written to {assessment_file}")
289
+ else:
290
+ log(f"CLI assessment exited {result.returncode}")
291
+ except AutomationBackendUnavailableError as e:
292
+ log(f"CLI assessment skipped: {e}")
293
+ except subprocess.TimeoutExpired:
294
+ log("CLI assessment timed out (90s)")
295
+ except Exception as e:
296
+ log(f"CLI assessment error: {e}")
297
+
298
+
299
+ if __name__ == "__main__":
300
+ main()