nexo-brain 5.3.26 → 5.3.28

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