nexo-brain 5.3.26 → 5.3.27

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 (211) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/package.json +1 -1
  3. package/src/server.py +3 -0
  4. package/src/tools_sessions.py +6 -1
  5. package/src/dashboard/static/favicon 2.svg +0 -32
  6. package/src/dashboard/static/nexo-logo 2.png +0 -0
  7. package/src/dashboard/static/nexo-logo 2.svg +0 -40
  8. package/src/dashboard/static/style 2.css +0 -2458
  9. package/src/dashboard/templates/adaptive 2.html +0 -118
  10. package/src/dashboard/templates/artifacts 2.html +0 -133
  11. package/src/dashboard/templates/backups 2.html +0 -136
  12. package/src/dashboard/templates/base 2.html +0 -417
  13. package/src/dashboard/templates/calendar 2.html +0 -591
  14. package/src/dashboard/templates/chat 2.html +0 -356
  15. package/src/dashboard/templates/claims 2.html +0 -259
  16. package/src/dashboard/templates/cortex 2.html +0 -321
  17. package/src/dashboard/templates/credentials 2.html +0 -128
  18. package/src/dashboard/templates/crons 2.html +0 -370
  19. package/src/dashboard/templates/dashboard 2.html +0 -494
  20. package/src/dashboard/templates/dreams 2.html +0 -252
  21. package/src/dashboard/templates/email 2.html +0 -160
  22. package/src/dashboard/templates/evolution 2.html +0 -189
  23. package/src/dashboard/templates/feed 2.html +0 -249
  24. package/src/dashboard/templates/followup_health 2.html +0 -170
  25. package/src/dashboard/templates/graph 2.html +0 -201
  26. package/src/dashboard/templates/guard 2.html +0 -259
  27. package/src/dashboard/templates/inbox 2.html +0 -251
  28. package/src/dashboard/templates/memory 2.html +0 -420
  29. package/src/dashboard/templates/operations 2.html +0 -608
  30. package/src/dashboard/templates/plugins 2.html +0 -185
  31. package/src/dashboard/templates/protocol 2.html +0 -199
  32. package/src/dashboard/templates/rules 2.html +0 -246
  33. package/src/dashboard/templates/sentiment 2.html +0 -247
  34. package/src/dashboard/templates/sessions 2.html +0 -218
  35. package/src/dashboard/templates/skills 2.html +0 -329
  36. package/src/dashboard/templates/somatic 2.html +0 -73
  37. package/src/dashboard/templates/triggers 2.html +0 -133
  38. package/src/dashboard/templates/trust 2.html +0 -360
  39. package/src/db/__init__ 2.py +0 -259
  40. package/src/db/_core 2.py +0 -437
  41. package/src/db/_credentials 2.py +0 -124
  42. package/src/db/_episodic 2.py +0 -762
  43. package/src/db/_evolution 2.py +0 -54
  44. package/src/db/_fts 2.py +0 -406
  45. package/src/db/_goal_profiles 2.py +0 -376
  46. package/src/db/_hot_context 2.py +0 -660
  47. package/src/db/_outcomes 2.py +0 -800
  48. package/src/db/_personal_scripts 2.py +0 -582
  49. package/src/db/_sessions 2.py +0 -330
  50. package/src/db/_tasks 2.py +0 -91
  51. package/src/db/_watchers 2.py +0 -173
  52. package/src/doctor/formatters 2.py +0 -52
  53. package/src/doctor/models 2.py +0 -69
  54. package/src/doctor/planes 2.py +0 -87
  55. package/src/doctor/providers/__init__ 2.py +0 -1
  56. package/src/doctor/providers/deep 2.py +0 -367
  57. package/src/evolution_cycle 2.py +0 -519
  58. package/src/hooks/auto_capture 2.py +0 -208
  59. package/src/hooks/caffeinate-guard 2.sh +0 -8
  60. package/src/hooks/capture-session 2.sh +0 -21
  61. package/src/hooks/capture-tool-logs 2.sh +0 -158
  62. package/src/hooks/daily-briefing-check 2.sh +0 -33
  63. package/src/hooks/heartbeat-enforcement 2.py +0 -90
  64. package/src/hooks/heartbeat-posttool 2.sh +0 -18
  65. package/src/hooks/inbox-hook 2.sh +0 -76
  66. package/src/hooks/post-compact 2.sh +0 -152
  67. package/src/hooks/pre-compact 2.sh +0 -169
  68. package/src/hooks/protocol-guardrail 2.sh +0 -10
  69. package/src/hooks/protocol-pretool-guardrail 2.sh +0 -9
  70. package/src/hooks/session-stop 2.sh +0 -52
  71. package/src/kg_populate 2.py +0 -292
  72. package/src/maintenance 2.py +0 -53
  73. package/src/memory_backends 2.py +0 -71
  74. package/src/migrate_embeddings 2.py +0 -124
  75. package/src/nexo_sdk 2.py +0 -103
  76. package/src/observability 2.py +0 -199
  77. package/src/plugin_loader 2.py +0 -217
  78. package/src/plugins/__init__ 2.py +0 -0
  79. package/src/plugins/artifact_registry 2.py +0 -450
  80. package/src/plugins/backup 2.py +0 -127
  81. package/src/plugins/claims_tools 2.py +0 -119
  82. package/src/plugins/cognitive_memory 2.py +0 -609
  83. package/src/plugins/core_rules 2.py +0 -252
  84. package/src/plugins/cortex 2.py +0 -1155
  85. package/src/plugins/entities 2.py +0 -67
  86. package/src/plugins/episodic_memory 2.py +0 -560
  87. package/src/plugins/evolution 2.py +0 -167
  88. package/src/plugins/goal_engine 2.py +0 -142
  89. package/src/plugins/guard 2.py +0 -862
  90. package/src/plugins/impact 2.py +0 -29
  91. package/src/plugins/knowledge_graph_tools 2.py +0 -137
  92. package/src/plugins/media_memory_tools 2.py +0 -98
  93. package/src/plugins/memory_export 2.py +0 -196
  94. package/src/plugins/outcomes 2.py +0 -130
  95. package/src/plugins/personal_scripts 2.py +0 -117
  96. package/src/plugins/preferences 2.py +0 -47
  97. package/src/plugins/protocol 2.py +0 -1449
  98. package/src/plugins/simple_api 2.py +0 -106
  99. package/src/plugins/skills 2.py +0 -341
  100. package/src/plugins/state_watchers 2.py +0 -79
  101. package/src/plugins/update 2.py +0 -986
  102. package/src/plugins/user_state_tools 2.py +0 -43
  103. package/src/plugins/workflow 2.py +0 -588
  104. package/src/protocol_settings 2.py +0 -59
  105. package/src/public_contribution 2.py +0 -466
  106. package/src/public_evolution_queue 2.py +0 -241
  107. package/src/requirements 2.txt +0 -14
  108. package/src/retroactive_learnings 2.py +0 -373
  109. package/src/rules/__init__ 2.py +0 -0
  110. package/src/rules/core-rules 2.json +0 -331
  111. package/src/rules/migrate 2.py +0 -207
  112. package/src/runtime_power 2.py +0 -874
  113. package/src/script_registry 2.py +0 -1559
  114. package/src/scripts/check-context 2.py +0 -272
  115. package/src/scripts/deep-sleep/apply_findings 2.py +0 -2327
  116. package/src/scripts/deep-sleep/collect 2.py +0 -928
  117. package/src/scripts/deep-sleep/extract 2.py +0 -330
  118. package/src/scripts/deep-sleep/extract-prompt 2.md +0 -285
  119. package/src/scripts/deep-sleep/synthesize 2.py +0 -312
  120. package/src/scripts/deep-sleep/synthesize-prompt 2.md +0 -336
  121. package/src/scripts/nexo-agent-run 2.py +0 -75
  122. package/src/scripts/nexo-auto-update 2.py +0 -6
  123. package/src/scripts/nexo-backup 2.sh +0 -25
  124. package/src/scripts/nexo-brain-activation 2.sh +0 -140
  125. package/src/scripts/nexo-catchup 2.py +0 -300
  126. package/src/scripts/nexo-cognitive-decay 2.py +0 -257
  127. package/src/scripts/nexo-cortex-cycle 2.py +0 -293
  128. package/src/scripts/nexo-cron-wrapper 2.sh +0 -53
  129. package/src/scripts/nexo-daily-self-audit 2.py +0 -2161
  130. package/src/scripts/nexo-dashboard 2.sh +0 -29
  131. package/src/scripts/nexo-deep-sleep 2.sh +0 -86
  132. package/src/scripts/nexo-evolution-run 2.py +0 -1664
  133. package/src/scripts/nexo-followup-hygiene 2.py +0 -139
  134. package/src/scripts/nexo-hook-record 2.py +0 -42
  135. package/src/scripts/nexo-immune 2.py +0 -936
  136. package/src/scripts/nexo-impact-scorer 2.py +0 -117
  137. package/src/scripts/nexo-inbox-hook 2.sh +0 -74
  138. package/src/scripts/nexo-install 2.py +0 -6
  139. package/src/scripts/nexo-learning-housekeep 2.py +0 -401
  140. package/src/scripts/nexo-learning-validator 2.py +0 -266
  141. package/src/scripts/nexo-migrate 2.py +0 -260
  142. package/src/scripts/nexo-outcome-checker 2.py +0 -127
  143. package/src/scripts/nexo-postmortem-consolidator 2.py +0 -456
  144. package/src/scripts/nexo-pre-commit 2.py +0 -120
  145. package/src/scripts/nexo-prevent-sleep 2.sh +0 -35
  146. package/src/scripts/nexo-proactive-dashboard 2.py +0 -354
  147. package/src/scripts/nexo-reflection 2.py +0 -256
  148. package/src/scripts/nexo-runtime-preflight 2.py +0 -274
  149. package/src/scripts/nexo-sleep 2.py +0 -631
  150. package/src/scripts/nexo-snapshot-restore 2.sh +0 -35
  151. package/src/scripts/nexo-sync-clients 2.py +0 -16
  152. package/src/scripts/nexo-synthesis 2.py +0 -475
  153. package/src/scripts/nexo-tcc-approve 2.sh +0 -79
  154. package/src/scripts/nexo-update 2.sh +0 -306
  155. package/src/scripts/nexo-watchdog 2.sh +0 -1207
  156. package/src/scripts/nexo-watchdog-smoke 2.py +0 -119
  157. package/src/scripts/rehydrate_learnings_from_archive 2.py +0 -245
  158. package/src/server 2.py +0 -1296
  159. package/src/skills/run-nexo-audit-phase/guide 2.md +0 -43
  160. package/src/skills/run-nexo-audit-phase/skill 2.json +0 -59
  161. package/src/skills/run-nexo-core-fix-cycle/guide 2.md +0 -17
  162. package/src/skills/run-nexo-core-fix-cycle/script 2.py +0 -276
  163. package/src/skills/run-nexo-core-fix-cycle/skill 2.json +0 -58
  164. package/src/skills/run-release-final-audit/guide 2.md +0 -16
  165. package/src/skills/run-release-final-audit/script 2.py +0 -259
  166. package/src/skills/run-release-final-audit/skill 2.json +0 -77
  167. package/src/skills/run-runtime-doctor/guide 2.md +0 -12
  168. package/src/skills/run-runtime-doctor/script 2.py +0 -21
  169. package/src/skills/run-runtime-doctor/skill 2.json +0 -25
  170. package/src/skills_runtime 2.py +0 -932
  171. package/src/state_watchers_runtime 2.py +0 -475
  172. package/src/storage_router 2.py +0 -32
  173. package/src/system_catalog 2.py +0 -786
  174. package/src/tools_coordination 2.py +0 -103
  175. package/src/tools_credentials 2.py +0 -68
  176. package/src/tools_drive 2.py +0 -487
  177. package/src/tools_hot_context 2.py +0 -163
  178. package/src/tools_learnings 2.py +0 -612
  179. package/src/tools_menu 2.py +0 -229
  180. package/src/tools_reminders 2.py +0 -88
  181. package/src/tools_reminders_crud 2.py +0 -363
  182. package/src/tools_sessions 2.py +0 -1054
  183. package/src/tools_system_catalog 2.py +0 -19
  184. package/src/tools_task_history 2.py +0 -57
  185. package/src/tools_transcripts 2.py +0 -98
  186. package/src/transcript_utils 2.py +0 -412
  187. package/src/user_context 2.py +0 -46
  188. package/src/user_data_portability 2.py +0 -328
  189. package/src/user_state_model 2.py +0 -170
  190. package/templates/CLAUDE.md 2.template +0 -108
  191. package/templates/CODEX.AGENTS.md 2.template +0 -66
  192. package/templates/launchagents/README 2.md +0 -132
  193. package/templates/launchagents/com.nexo.auto-close-sessions 2.plist +0 -39
  194. package/templates/launchagents/com.nexo.catchup 2.plist +0 -39
  195. package/templates/launchagents/com.nexo.cognitive-decay 2.plist +0 -40
  196. package/templates/launchagents/com.nexo.dashboard 2.plist +0 -43
  197. package/templates/launchagents/com.nexo.deep-sleep 2.plist +0 -43
  198. package/templates/launchagents/com.nexo.evolution 2.plist +0 -44
  199. package/templates/launchagents/com.nexo.followup-hygiene 2.plist +0 -45
  200. package/templates/launchagents/com.nexo.immune 2.plist +0 -41
  201. package/templates/launchagents/com.nexo.postmortem 2.plist +0 -45
  202. package/templates/launchagents/com.nexo.self-audit 2.plist +0 -47
  203. package/templates/launchagents/com.nexo.synthesis 2.plist +0 -45
  204. package/templates/launchagents/com.nexo.watchdog 2.plist +0 -37
  205. package/templates/nexo_helper 2.py +0 -301
  206. package/templates/openclaw 2.json +0 -13
  207. package/templates/plugin-template 2.py +0 -40
  208. package/templates/script-template 2.py +0 -59
  209. package/templates/script-template 2.sh +0 -13
  210. package/templates/skill-script-template 2.py +0 -48
  211. package/templates/skill-template 2.md +0 -33
@@ -1,75 +0,0 @@
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())
@@ -1,6 +0,0 @@
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)
@@ -1,25 +0,0 @@
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
@@ -1,140 +0,0 @@
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
@@ -1,300 +0,0 @@
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()