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,475 @@
1
+ from __future__ import annotations
2
+ """Runtime evaluation for persistent state watchers."""
3
+
4
+ import json
5
+ import os
6
+ import sqlite3
7
+ import subprocess
8
+ from datetime import datetime, timedelta, timezone
9
+ from pathlib import Path
10
+ from urllib import error, request
11
+
12
+
13
+ def _nexo_home() -> Path:
14
+ return Path(os.environ.get("NEXO_HOME", str(Path.home() / ".nexo")))
15
+
16
+
17
+ def _db_path() -> Path:
18
+ explicit = os.environ.get("NEXO_TEST_DB") or os.environ.get("NEXO_DB")
19
+ if explicit:
20
+ return Path(explicit)
21
+ return _nexo_home() / "data" / "nexo.db"
22
+
23
+
24
+ def _summary_file() -> Path:
25
+ return _nexo_home() / "operations" / "state-watchers-status.json"
26
+
27
+
28
+ def _manifest_file() -> Path:
29
+ return _nexo_home() / "crons" / "manifest.json"
30
+
31
+
32
+ def _now_iso() -> str:
33
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
34
+
35
+
36
+ def _parse_dt(value: str | None) -> datetime | None:
37
+ text = str(value or "").strip()
38
+ if not text:
39
+ return None
40
+ normalized = text.replace("Z", "+00:00")
41
+ for candidate in (normalized, normalized + "T00:00:00+00:00"):
42
+ try:
43
+ parsed = datetime.fromisoformat(candidate)
44
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
45
+ except Exception:
46
+ continue
47
+ for fmt in ("%Y-%m-%d", "%Y-%m-%d %H:%M:%S"):
48
+ try:
49
+ parsed = datetime.strptime(text, fmt)
50
+ return parsed.replace(tzinfo=timezone.utc)
51
+ except Exception:
52
+ continue
53
+ return None
54
+
55
+
56
+ def _load_manifest() -> list[dict]:
57
+ manifest_file = _manifest_file()
58
+ if not manifest_file.is_file():
59
+ return []
60
+ try:
61
+ payload = json.loads(manifest_file.read_text())
62
+ except Exception:
63
+ return []
64
+ crons = payload.get("crons")
65
+ return crons if isinstance(crons, list) else []
66
+
67
+
68
+ def _load_last_cron_run(cron_id: str) -> datetime | None:
69
+ db_path = _db_path()
70
+ if not db_path.is_file():
71
+ return None
72
+ conn = sqlite3.connect(str(db_path))
73
+ try:
74
+ row = conn.execute(
75
+ "SELECT started_at FROM cron_runs WHERE cron_id = ? ORDER BY started_at DESC LIMIT 1",
76
+ (cron_id,),
77
+ ).fetchone()
78
+ except Exception:
79
+ return None
80
+ finally:
81
+ conn.close()
82
+ if not row or not row[0]:
83
+ return None
84
+ return _parse_dt(str(row[0]))
85
+
86
+
87
+ def _evaluate_repo_drift(watcher: dict) -> dict:
88
+ repo_path = Path(str(watcher.get("target") or "")).expanduser()
89
+ if not repo_path.exists():
90
+ return {"health": "critical", "summary": f"repo path missing: {repo_path}", "evidence": [str(repo_path)]}
91
+ try:
92
+ inside = subprocess.run(
93
+ ["git", "rev-parse", "--is-inside-work-tree"],
94
+ cwd=str(repo_path),
95
+ capture_output=True,
96
+ text=True,
97
+ timeout=5,
98
+ )
99
+ except Exception as exc:
100
+ return {"health": "critical", "summary": f"git probe failed: {exc}", "evidence": [str(repo_path)]}
101
+ if inside.returncode != 0 or inside.stdout.strip() != "true":
102
+ return {"health": "critical", "summary": f"not a git repo: {repo_path}", "evidence": [inside.stderr.strip() or inside.stdout.strip()]}
103
+
104
+ branch = subprocess.run(
105
+ ["git", "rev-parse", "--abbrev-ref", "HEAD"],
106
+ cwd=str(repo_path),
107
+ capture_output=True,
108
+ text=True,
109
+ timeout=5,
110
+ )
111
+ status = subprocess.run(
112
+ ["git", "status", "--porcelain"],
113
+ cwd=str(repo_path),
114
+ capture_output=True,
115
+ text=True,
116
+ timeout=5,
117
+ )
118
+ config = watcher.get("config") or {}
119
+ expected_branch = str(config.get("expected_branch") or "").strip()
120
+ dirty = bool(status.stdout.strip())
121
+ health = "healthy"
122
+ evidence = [f"branch={branch.stdout.strip() or 'unknown'}", f"dirty={dirty}"]
123
+ summary = f"repo clean at {repo_path}"
124
+ if expected_branch and branch.stdout.strip() and branch.stdout.strip() != expected_branch:
125
+ health = "degraded"
126
+ summary = f"repo branch drifted from {expected_branch}"
127
+ evidence.append(f"expected_branch={expected_branch}")
128
+ if dirty and not bool(config.get("allow_dirty")):
129
+ health = "degraded" if health == "healthy" else health
130
+ summary = f"repo has uncommitted drift at {repo_path}"
131
+ evidence.extend(status.stdout.strip().splitlines()[:5])
132
+ return {"health": health, "summary": summary, "evidence": evidence}
133
+
134
+
135
+ def _cron_threshold_seconds(cron_payload: dict) -> int | None:
136
+ if cron_payload.get("interval_seconds"):
137
+ return max(int(cron_payload["interval_seconds"]) * 2, 900)
138
+ if cron_payload.get("schedule"):
139
+ return 36 * 3600
140
+ if cron_payload.get("run_at_load"):
141
+ return None
142
+ return 24 * 3600
143
+
144
+
145
+ def _evaluate_cron_drift(watcher: dict) -> dict:
146
+ cron_id = str(watcher.get("target") or "").strip()
147
+ manifest = _load_manifest()
148
+ cron_payload = next((item for item in manifest if str(item.get("id") or "").strip() == cron_id), None)
149
+ if not cron_payload:
150
+ return {"health": "critical", "summary": f"cron missing from manifest: {cron_id}", "evidence": [str(_manifest_file())]}
151
+ threshold = _cron_threshold_seconds(cron_payload)
152
+ if threshold is None:
153
+ return {"health": "healthy", "summary": f"cron {cron_id} is run_at_load-only", "evidence": ["no periodic freshness expected"]}
154
+ last_run = _load_last_cron_run(cron_id)
155
+ if not last_run:
156
+ return {"health": "critical", "summary": f"cron {cron_id} has never run", "evidence": [f"threshold_seconds={threshold}"]}
157
+ age = (datetime.now(timezone.utc) - last_run).total_seconds()
158
+ if age > threshold * 2:
159
+ health = "critical"
160
+ elif age > threshold:
161
+ health = "degraded"
162
+ else:
163
+ health = "healthy"
164
+ return {
165
+ "health": health,
166
+ "summary": f"cron {cron_id} freshness checked",
167
+ "evidence": [f"age_seconds={int(age)}", f"threshold_seconds={threshold}", f"last_run={last_run.isoformat()}"],
168
+ }
169
+
170
+
171
+ def _evaluate_api_health(watcher: dict) -> dict:
172
+ url = str(watcher.get("target") or "").strip()
173
+ config = watcher.get("config") or {}
174
+ timeout = float(config.get("timeout_seconds") or 3)
175
+ allowed_min = int(config.get("allowed_min") or 200)
176
+ allowed_max = int(config.get("allowed_max") or 399)
177
+ method = str(config.get("method") or "GET").upper()
178
+ req = request.Request(url, method=method)
179
+ try:
180
+ with request.urlopen(req, timeout=timeout) as resp:
181
+ code = int(getattr(resp, "status", 200))
182
+ except error.HTTPError as exc:
183
+ code = int(exc.code)
184
+ except Exception as exc:
185
+ return {"health": "critical", "summary": f"API health probe failed for {url}", "evidence": [str(exc)]}
186
+ health = "healthy" if allowed_min <= code <= allowed_max else "critical"
187
+ return {
188
+ "health": health,
189
+ "summary": f"API {url} returned {code}",
190
+ "evidence": [f"status_code={code}", f"allowed={allowed_min}-{allowed_max}"],
191
+ }
192
+
193
+
194
+ def _evaluate_environment_drift(watcher: dict) -> dict:
195
+ config = watcher.get("config") or {}
196
+ mode = str(config.get("mode") or "env_var").strip().lower()
197
+ target = str(watcher.get("target") or "").strip()
198
+ if mode == "env_var":
199
+ current = os.environ.get(target, "")
200
+ expected = str(config.get("expected_value") or "").strip()
201
+ if not current:
202
+ return {"health": "critical", "summary": f"env var missing: {target}", "evidence": [target]}
203
+ if expected and current != expected:
204
+ return {"health": "degraded", "summary": f"env var drift: {target}", "evidence": [f"expected={expected}", f"current={current}"]}
205
+ return {"health": "healthy", "summary": f"env var present: {target}", "evidence": [target]}
206
+ path = Path(target).expanduser()
207
+ if mode == "dir_exists":
208
+ healthy = path.is_dir()
209
+ else:
210
+ healthy = path.exists()
211
+ return {
212
+ "health": "healthy" if healthy else "critical",
213
+ "summary": f"{mode} {'OK' if healthy else 'missing'} for {path}",
214
+ "evidence": [str(path)],
215
+ }
216
+
217
+
218
+ def _evaluate_expiry(watcher: dict) -> dict:
219
+ config = watcher.get("config") or {}
220
+ due_at = _parse_dt(str(config.get("due_at") or watcher.get("target") or ""))
221
+ if not due_at:
222
+ return {"health": "critical", "summary": f"expiry watcher missing due_at: {watcher.get('watcher_id')}", "evidence": []}
223
+ warn_days = int(config.get("warn_days") or 21)
224
+ critical_days = int(config.get("critical_days") or 7)
225
+ remaining = due_at - datetime.now(timezone.utc)
226
+ days = remaining.total_seconds() / 86400
227
+ if days <= critical_days:
228
+ health = "critical"
229
+ elif days <= warn_days:
230
+ health = "degraded"
231
+ else:
232
+ health = "healthy"
233
+ return {
234
+ "health": health,
235
+ "summary": f"expiry watcher '{watcher.get('title')}' due in {days:.1f} days",
236
+ "evidence": [f"due_at={due_at.isoformat()}", f"warn_days={warn_days}", f"critical_days={critical_days}"],
237
+ }
238
+
239
+
240
+ def evaluate_state_watcher(watcher: dict) -> dict:
241
+ watcher_type = str(watcher.get("watcher_type") or "").strip().lower()
242
+ if watcher_type == "repo_drift":
243
+ result = _evaluate_repo_drift(watcher)
244
+ elif watcher_type == "cron_drift":
245
+ result = _evaluate_cron_drift(watcher)
246
+ elif watcher_type == "api_health":
247
+ result = _evaluate_api_health(watcher)
248
+ elif watcher_type == "environment_drift":
249
+ result = _evaluate_environment_drift(watcher)
250
+ elif watcher_type == "expiry":
251
+ result = _evaluate_expiry(watcher)
252
+ else:
253
+ result = {"health": "critical", "summary": f"unsupported watcher type: {watcher_type}", "evidence": []}
254
+ return {
255
+ "watcher_id": watcher.get("watcher_id", ""),
256
+ "title": watcher.get("title", ""),
257
+ "watcher_type": watcher_type,
258
+ "target": watcher.get("target", ""),
259
+ "severity": watcher.get("severity", "warn"),
260
+ "checked_at": _now_iso(),
261
+ **result,
262
+ }
263
+
264
+
265
+ def _list_watchers(*, status: str) -> list[dict]:
266
+ db_path = _db_path()
267
+ if not db_path.is_file():
268
+ return []
269
+ conn = sqlite3.connect(str(db_path))
270
+ try:
271
+ conn.row_factory = sqlite3.Row
272
+ clauses = []
273
+ params = []
274
+ if status:
275
+ clauses.append("status = ?")
276
+ params.append(status)
277
+ where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
278
+ try:
279
+ rows = conn.execute(
280
+ f"""SELECT watcher_id, watcher_type, title, target, severity, status, config, last_health, last_result, last_checked_at
281
+ FROM state_watchers
282
+ {where}
283
+ ORDER BY updated_at DESC, watcher_id DESC""",
284
+ tuple(params),
285
+ ).fetchall()
286
+ except sqlite3.OperationalError:
287
+ return []
288
+ finally:
289
+ conn.close()
290
+ watchers = []
291
+ for row in rows:
292
+ watcher = dict(row)
293
+ try:
294
+ watcher["config"] = json.loads(watcher.get("config") or "{}")
295
+ except Exception:
296
+ watcher["config"] = {}
297
+ watchers.append(watcher)
298
+ return watchers
299
+
300
+
301
+ def _persist_result(result: dict) -> None:
302
+ db_path = _db_path()
303
+ if not db_path.is_file():
304
+ return
305
+ conn = sqlite3.connect(str(db_path))
306
+ try:
307
+ conn.execute(
308
+ """UPDATE state_watchers
309
+ SET last_health = ?, last_result = ?, last_checked_at = ?, updated_at = datetime('now')
310
+ WHERE watcher_id = ?""",
311
+ (
312
+ result["health"],
313
+ json.dumps(result, ensure_ascii=False),
314
+ result["checked_at"],
315
+ result["watcher_id"],
316
+ ),
317
+ )
318
+ conn.commit()
319
+ finally:
320
+ conn.close()
321
+
322
+
323
+ def _open_watcher_followup(result: dict) -> dict:
324
+ """Open or refresh a NF-WATCHER-{id} followup when a watcher fires.
325
+
326
+ Closes Fase 3 item 5 of NEXO-AUDIT-2026-04-11. Until this helper, state
327
+ watchers only updated their own row in `state_watchers` and wrote a
328
+ summary file. A watcher could go critical and stay critical for days
329
+ without ever surfacing to the user.
330
+
331
+ Idempotent: uses INSERT OR REPLACE on a deterministic id derived from
332
+ the watcher_id, so consecutive runs that hit the same problem refresh
333
+ the followup in place rather than duplicating it. The followup is
334
+ automatically resolved next time the watcher reports healthy (the cron
335
+ that wires `run_state_watchers` will hit the resolve path).
336
+
337
+ Returns: {action: 'opened'|'refreshed'|'skipped'|'failed', followup_id, reason}
338
+ """
339
+ health = (result.get("health") or "").strip().lower()
340
+ watcher_id = (result.get("watcher_id") or "").strip()
341
+ if not watcher_id:
342
+ return {"action": "skipped", "reason": "missing watcher_id"}
343
+ if health not in {"degraded", "critical"}:
344
+ return {"action": "skipped", "reason": f"health={health}"}
345
+
346
+ followup_id = f"NF-WATCHER-{watcher_id}"
347
+ severity_map = {"degraded": "warn", "critical": "error"}
348
+ severity = severity_map.get(health, "warn")
349
+ priority_map = {"degraded": "high", "critical": "critical"}
350
+ priority = priority_map.get(health, "high")
351
+ title = (result.get("title") or watcher_id).strip()
352
+ summary = (result.get("summary") or "").strip() or "(no summary)"
353
+ target = (result.get("target") or "").strip()
354
+ watcher_type = (result.get("watcher_type") or "").strip()
355
+
356
+ description_lines = [
357
+ f"State watcher {watcher_id} reports {health.upper()} ({severity}).",
358
+ f"Title: {title}",
359
+ f"Type: {watcher_type}" + (f" / Target: {target}" if target else ""),
360
+ "",
361
+ f"Summary: {summary}",
362
+ ]
363
+ evidence = result.get("evidence") or []
364
+ if isinstance(evidence, list) and evidence:
365
+ description_lines.append("")
366
+ description_lines.append("Evidence:")
367
+ for ev in evidence[:5]:
368
+ description_lines.append(f" - {str(ev)[:200]}")
369
+ description_lines.append("")
370
+ description_lines.append(
371
+ "Investigate the watcher target and either fix the underlying drift "
372
+ "or update the watcher's threshold. The followup will auto-resolve "
373
+ "next time the watcher reports healthy."
374
+ )
375
+ description = "\n".join(description_lines)
376
+ verification = (
377
+ f"sqlite3 ~/.nexo/data/nexo.db \"SELECT last_health, last_result "
378
+ f"FROM state_watchers WHERE watcher_id = '{watcher_id}'\""
379
+ )
380
+
381
+ db_path = _db_path()
382
+ if not db_path.is_file():
383
+ return {"action": "failed", "followup_id": followup_id, "reason": "db not found"}
384
+
385
+ now_epoch = datetime.now().timestamp()
386
+ conn = sqlite3.connect(str(db_path))
387
+ try:
388
+ existing = conn.execute(
389
+ "SELECT id, status FROM followups WHERE id = ?", (followup_id,)
390
+ ).fetchone()
391
+ was_pending = bool(existing) and (existing[1] == "PENDING")
392
+ try:
393
+ conn.execute(
394
+ "INSERT OR REPLACE INTO followups (id, description, date, status, "
395
+ "verification, created_at, updated_at, priority) "
396
+ "VALUES (?, ?, NULL, 'PENDING', ?, ?, ?, ?)",
397
+ (followup_id, description, verification, now_epoch, now_epoch, priority),
398
+ )
399
+ conn.commit()
400
+ except sqlite3.OperationalError:
401
+ return {"action": "failed", "followup_id": followup_id, "reason": "followups table missing"}
402
+ finally:
403
+ conn.close()
404
+
405
+ return {
406
+ "action": "refreshed" if was_pending else "opened",
407
+ "followup_id": followup_id,
408
+ "severity": severity,
409
+ }
410
+
411
+
412
+ def _resolve_watcher_followup(watcher_id: str) -> dict:
413
+ """Auto-resolve a NF-WATCHER-{id} followup when the watcher recovers.
414
+
415
+ Idempotent: a no-op when the followup does not exist or is already
416
+ resolved. Called from run_state_watchers when a watcher reports healthy
417
+ after previously being degraded/critical.
418
+ """
419
+ if not watcher_id:
420
+ return {"action": "skipped", "reason": "missing watcher_id"}
421
+ db_path = _db_path()
422
+ if not db_path.is_file():
423
+ return {"action": "skipped", "reason": "db not found"}
424
+ followup_id = f"NF-WATCHER-{watcher_id}"
425
+ conn = sqlite3.connect(str(db_path))
426
+ try:
427
+ existing = conn.execute(
428
+ "SELECT id, status FROM followups WHERE id = ?", (followup_id,)
429
+ ).fetchone()
430
+ if not existing:
431
+ return {"action": "skipped", "reason": "no followup"}
432
+ if existing[1] != "PENDING":
433
+ return {"action": "skipped", "reason": f"already {existing[1]}"}
434
+ conn.execute(
435
+ "UPDATE followups SET status = 'COMPLETED', updated_at = ? "
436
+ "WHERE id = ? AND status = 'PENDING'",
437
+ (datetime.now().timestamp(), followup_id),
438
+ )
439
+ conn.commit()
440
+ finally:
441
+ conn.close()
442
+ return {"action": "resolved", "followup_id": followup_id}
443
+
444
+
445
+ def run_state_watchers(*, persist: bool = True, status: str = "active") -> dict:
446
+ watchers = _list_watchers(status=status)
447
+ results = [evaluate_state_watcher(watcher) for watcher in watchers]
448
+ counts = {"healthy": 0, "degraded": 0, "critical": 0, "unknown": 0}
449
+ followup_actions: list[dict] = []
450
+ for result in results:
451
+ counts[result["health"]] = counts.get(result["health"], 0) + 1
452
+ if persist:
453
+ _persist_result(result)
454
+ # Surface degraded/critical as a followup, auto-resolve when healthy.
455
+ try:
456
+ if result["health"] in {"degraded", "critical"}:
457
+ action = _open_watcher_followup(result)
458
+ else:
459
+ action = _resolve_watcher_followup(result.get("watcher_id", ""))
460
+ if action.get("action") not in {"skipped", None}:
461
+ followup_actions.append(action)
462
+ except Exception:
463
+ pass # Best-effort surfacing
464
+ summary = {
465
+ "generated_at": _now_iso(),
466
+ "watcher_count": len(results),
467
+ "counts": counts,
468
+ "watchers": results,
469
+ "followup_actions": followup_actions,
470
+ }
471
+ if persist:
472
+ summary_file = _summary_file()
473
+ summary_file.parent.mkdir(parents=True, exist_ok=True)
474
+ summary_file.write_text(json.dumps(summary, indent=2, ensure_ascii=False))
475
+ return summary
@@ -0,0 +1,32 @@
1
+ """Storage Router — DB path abstraction for future multi-tenant support."""
2
+
3
+ import os
4
+
5
+ NEXO_HOME = os.environ.get("NEXO_HOME", os.path.expanduser("~/.nexo"))
6
+
7
+
8
+ class StorageRouter:
9
+ def __init__(self, tenant_id: str = "default"):
10
+ self.tenant_id = tenant_id
11
+
12
+ def nexo_db_path(self) -> str:
13
+ if self.tenant_id == "default":
14
+ data_dir = os.path.join(NEXO_HOME, "data")
15
+ os.makedirs(data_dir, exist_ok=True)
16
+ return os.path.join(data_dir, "nexo.db")
17
+ return os.path.join(NEXO_HOME, "tenants", self.tenant_id, "nexo.db")
18
+
19
+ def cognitive_db_path(self) -> str:
20
+ if self.tenant_id == "default":
21
+ data_dir = os.path.join(NEXO_HOME, "data")
22
+ os.makedirs(data_dir, exist_ok=True)
23
+ return os.path.join(data_dir, "cognitive.db")
24
+ return os.path.join(NEXO_HOME, "tenants", self.tenant_id, "cognitive.db")
25
+
26
+
27
+ _default_router = StorageRouter("default")
28
+
29
+ def get_router(tenant_id: str = "default") -> StorageRouter:
30
+ if tenant_id == "default":
31
+ return _default_router
32
+ return StorageRouter(tenant_id)