nexo-brain 2.6.21 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +72 -20
- package/hooks/hooks.json +79 -0
- package/package.json +1 -1
- package/src/agent_runner.py +296 -8
- package/src/cli.py +209 -4
- package/src/client_preferences.py +115 -0
- package/src/client_sync.py +202 -2
- package/src/cognitive/__init__.py +1 -1
- package/src/cognitive/_search.py +39 -19
- package/src/dashboard/app.py +264 -0
- package/src/dashboard/templates/base.html +4 -0
- package/src/dashboard/templates/dashboard.html +59 -1
- package/src/dashboard/templates/protocol.html +199 -0
- package/src/db/__init__.py +23 -1
- package/src/db/_learnings.py +31 -4
- package/src/db/_personal_scripts.py +12 -0
- package/src/db/_protocol.py +303 -0
- package/src/db/_schema.py +248 -0
- package/src/db/_watchers.py +173 -0
- package/src/db/_workflow.py +952 -0
- package/src/doctor/providers/runtime.py +1095 -3
- package/src/evolution_cycle.py +62 -0
- package/src/hook_guardrails.py +308 -0
- package/src/hooks/protocol-guardrail.sh +10 -0
- package/src/nexo_sdk.py +103 -0
- package/src/plugins/cognitive_memory.py +18 -0
- package/src/plugins/cortex.py +55 -35
- package/src/plugins/guard.py +132 -16
- package/src/plugins/protocol.py +911 -0
- package/src/plugins/schedule.py +40 -6
- package/src/plugins/simple_api.py +103 -0
- package/src/plugins/skills.py +67 -0
- package/src/plugins/state_watchers.py +79 -0
- package/src/plugins/workflow.py +588 -0
- package/src/public_contribution.py +86 -12
- package/src/script_registry.py +142 -0
- package/src/scripts/deep-sleep/apply_findings.py +482 -2
- package/src/scripts/deep-sleep/collect.py +49 -4
- package/src/scripts/nexo-agent-run.py +2 -0
- package/src/scripts/nexo-daily-self-audit.py +843 -5
- package/src/scripts/nexo-evolution-run.py +343 -1
- package/src/server.py +92 -6
- package/src/skills_runtime.py +151 -0
- package/src/state_watchers_runtime.py +334 -0
- package/src/tools_learnings.py +345 -7
- package/src/tools_sessions.py +183 -0
- package/templates/CLAUDE.md.template +9 -1
- package/templates/CODEX.AGENTS.md.template +10 -2
package/src/skills_runtime.py
CHANGED
|
@@ -18,6 +18,7 @@ from db import (
|
|
|
18
18
|
approve_skill,
|
|
19
19
|
collect_skill_improvement_candidates,
|
|
20
20
|
collect_scriptable_skill_candidates,
|
|
21
|
+
create_skill,
|
|
21
22
|
get_featured_skills,
|
|
22
23
|
get_skill,
|
|
23
24
|
get_skill_execution_spec,
|
|
@@ -32,6 +33,7 @@ from script_registry import doctor_script
|
|
|
32
33
|
|
|
33
34
|
NEXO_HOME = Path(os.environ.get("NEXO_HOME", str(Path.home() / ".nexo")))
|
|
34
35
|
NEXO_CODE = Path(os.environ.get("NEXO_CODE", str(Path(__file__).resolve().parent)))
|
|
36
|
+
VALID_LEVELS = {"trace", "draft", "published", "stable", "archived"}
|
|
35
37
|
|
|
36
38
|
|
|
37
39
|
def _parse_params(params) -> dict:
|
|
@@ -160,6 +162,155 @@ def get_featured_skill_summaries(limit: int = 5) -> list[dict]:
|
|
|
160
162
|
return featured
|
|
161
163
|
|
|
162
164
|
|
|
165
|
+
def _skill_json_list(skill: dict, key: str) -> list:
|
|
166
|
+
try:
|
|
167
|
+
value = json.loads(skill.get(key, "[]"))
|
|
168
|
+
except json.JSONDecodeError:
|
|
169
|
+
value = []
|
|
170
|
+
return value if isinstance(value, list) else []
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def test_skill(skill_id: str, params=None, mode: str = "auto", context: str = "") -> dict:
|
|
174
|
+
result = apply_skill(skill_id, params=params, mode=mode, dry_run=True, context=context or "skill_test")
|
|
175
|
+
result["tested"] = True
|
|
176
|
+
result["test_kind"] = "dry_run"
|
|
177
|
+
return result
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def promote_skill(skill_id: str, target_level: str = "published", reason: str = "") -> dict:
|
|
181
|
+
_ensure_ready()
|
|
182
|
+
sync_skill_directories()
|
|
183
|
+
skill = get_skill(skill_id)
|
|
184
|
+
if not skill:
|
|
185
|
+
return {"ok": False, "error": f"Skill {skill_id} not found"}
|
|
186
|
+
clean_target = str(target_level or "published").strip().lower()
|
|
187
|
+
if clean_target not in VALID_LEVELS:
|
|
188
|
+
return {"ok": False, "error": f"Unsupported target_level: {target_level}"}
|
|
189
|
+
if clean_target == "archived":
|
|
190
|
+
return {"ok": False, "error": "Use retire_skill to archive skills explicitly"}
|
|
191
|
+
updated = update_skill(skill_id, level=clean_target)
|
|
192
|
+
if "error" in updated:
|
|
193
|
+
return {"ok": False, "error": updated["error"]}
|
|
194
|
+
return {
|
|
195
|
+
"ok": True,
|
|
196
|
+
"skill_id": skill_id,
|
|
197
|
+
"previous_level": skill.get("level", ""),
|
|
198
|
+
"level": updated.get("level", clean_target),
|
|
199
|
+
"reason": str(reason or "").strip(),
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def retire_skill(skill_id: str, replacement_id: str = "", reason: str = "") -> dict:
|
|
204
|
+
_ensure_ready()
|
|
205
|
+
sync_skill_directories()
|
|
206
|
+
skill = get_skill(skill_id)
|
|
207
|
+
if not skill:
|
|
208
|
+
return {"ok": False, "error": f"Skill {skill_id} not found"}
|
|
209
|
+
replacement = None
|
|
210
|
+
clean_replacement = str(replacement_id or "").strip()
|
|
211
|
+
if clean_replacement:
|
|
212
|
+
replacement = get_skill(clean_replacement)
|
|
213
|
+
if not replacement:
|
|
214
|
+
return {"ok": False, "error": f"Replacement skill {clean_replacement} not found"}
|
|
215
|
+
updated = update_skill(skill_id, level="archived")
|
|
216
|
+
if "error" in updated:
|
|
217
|
+
return {"ok": False, "error": updated["error"]}
|
|
218
|
+
return {
|
|
219
|
+
"ok": True,
|
|
220
|
+
"skill_id": skill_id,
|
|
221
|
+
"level": updated.get("level", "archived"),
|
|
222
|
+
"replacement_id": clean_replacement,
|
|
223
|
+
"reason": str(reason or "").strip(),
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def compose_skills(
|
|
228
|
+
*,
|
|
229
|
+
new_skill_id: str,
|
|
230
|
+
name: str,
|
|
231
|
+
component_ids: list[str],
|
|
232
|
+
description: str = "",
|
|
233
|
+
level: str = "draft",
|
|
234
|
+
mode: str = "guide",
|
|
235
|
+
tags: list[str] | None = None,
|
|
236
|
+
trigger_patterns: list[str] | None = None,
|
|
237
|
+
) -> dict:
|
|
238
|
+
_ensure_ready()
|
|
239
|
+
sync_skill_directories()
|
|
240
|
+
if get_skill(new_skill_id):
|
|
241
|
+
return {"ok": False, "error": f"Skill {new_skill_id} already exists"}
|
|
242
|
+
components = []
|
|
243
|
+
for skill_id in component_ids:
|
|
244
|
+
skill = get_skill(skill_id)
|
|
245
|
+
if not skill:
|
|
246
|
+
return {"ok": False, "error": f"Component skill {skill_id} not found"}
|
|
247
|
+
components.append(skill)
|
|
248
|
+
if not components:
|
|
249
|
+
return {"ok": False, "error": "At least one component skill is required"}
|
|
250
|
+
|
|
251
|
+
merged_steps: list[str] = []
|
|
252
|
+
merged_gotchas: list[str] = []
|
|
253
|
+
merged_tags = set(tags or [])
|
|
254
|
+
merged_triggers = set(trigger_patterns or [])
|
|
255
|
+
linked_learnings = set()
|
|
256
|
+
source_sessions = set()
|
|
257
|
+
content_lines = [f"# {name}", "", description or "Composite skill built from existing NEXO skills.", "", "## Components"]
|
|
258
|
+
for skill in components:
|
|
259
|
+
content_lines.append(f"- {skill['id']}: {skill['name']}")
|
|
260
|
+
for step in _skill_json_list(skill, "steps"):
|
|
261
|
+
if step and step not in merged_steps:
|
|
262
|
+
merged_steps.append(step)
|
|
263
|
+
for gotcha in _skill_json_list(skill, "gotchas"):
|
|
264
|
+
if gotcha and gotcha not in merged_gotchas:
|
|
265
|
+
merged_gotchas.append(gotcha)
|
|
266
|
+
for trigger in _skill_json_list(skill, "trigger_patterns"):
|
|
267
|
+
if trigger:
|
|
268
|
+
merged_triggers.add(trigger)
|
|
269
|
+
for tag in _skill_json_list(skill, "tags"):
|
|
270
|
+
if tag:
|
|
271
|
+
merged_tags.add(tag)
|
|
272
|
+
for item in _skill_json_list(skill, "linked_learnings"):
|
|
273
|
+
if item:
|
|
274
|
+
linked_learnings.add(item)
|
|
275
|
+
for item in _skill_json_list(skill, "source_sessions"):
|
|
276
|
+
if item:
|
|
277
|
+
source_sessions.add(item)
|
|
278
|
+
|
|
279
|
+
if merged_steps:
|
|
280
|
+
content_lines.extend(["", "## Steps"])
|
|
281
|
+
for index, step in enumerate(merged_steps, 1):
|
|
282
|
+
content_lines.append(f"{index}. {step}")
|
|
283
|
+
if merged_gotchas:
|
|
284
|
+
content_lines.extend(["", "## Gotchas"])
|
|
285
|
+
for gotcha in merged_gotchas:
|
|
286
|
+
content_lines.append(f"- {gotcha}")
|
|
287
|
+
|
|
288
|
+
created = create_skill(
|
|
289
|
+
skill_id=new_skill_id,
|
|
290
|
+
name=name,
|
|
291
|
+
description=description or f"Composite skill built from {', '.join(component_ids)}",
|
|
292
|
+
level=level,
|
|
293
|
+
tags=sorted(merged_tags),
|
|
294
|
+
trigger_patterns=sorted(merged_triggers),
|
|
295
|
+
source_sessions=sorted(source_sessions),
|
|
296
|
+
linked_learnings=sorted(linked_learnings),
|
|
297
|
+
steps=merged_steps,
|
|
298
|
+
gotchas=merged_gotchas,
|
|
299
|
+
content="\n".join(content_lines).strip() + "\n",
|
|
300
|
+
mode=mode,
|
|
301
|
+
source_kind="personal",
|
|
302
|
+
)
|
|
303
|
+
if "error" in created:
|
|
304
|
+
return {"ok": False, "error": created["error"]}
|
|
305
|
+
return {
|
|
306
|
+
"ok": True,
|
|
307
|
+
"skill_id": new_skill_id,
|
|
308
|
+
"component_ids": component_ids,
|
|
309
|
+
"level": created.get("level", level),
|
|
310
|
+
"mode": created.get("mode", mode),
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
|
|
163
314
|
def apply_skill(skill_id: str, params=None, mode: str = "auto", dry_run: bool = False, context: str = "") -> dict:
|
|
164
315
|
_ensure_ready()
|
|
165
316
|
sync_skill_directories()
|
|
@@ -0,0 +1,334 @@
|
|
|
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 UTC, datetime, timedelta
|
|
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(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=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=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
|
+
row = conn.execute(
|
|
74
|
+
"SELECT started_at FROM cron_runs WHERE cron_id = ? ORDER BY started_at DESC LIMIT 1",
|
|
75
|
+
(cron_id,),
|
|
76
|
+
).fetchone()
|
|
77
|
+
conn.close()
|
|
78
|
+
if not row or not row[0]:
|
|
79
|
+
return None
|
|
80
|
+
return _parse_dt(str(row[0]))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _evaluate_repo_drift(watcher: dict) -> dict:
|
|
84
|
+
repo_path = Path(str(watcher.get("target") or "")).expanduser()
|
|
85
|
+
if not repo_path.exists():
|
|
86
|
+
return {"health": "critical", "summary": f"repo path missing: {repo_path}", "evidence": [str(repo_path)]}
|
|
87
|
+
try:
|
|
88
|
+
inside = subprocess.run(
|
|
89
|
+
["git", "rev-parse", "--is-inside-work-tree"],
|
|
90
|
+
cwd=str(repo_path),
|
|
91
|
+
capture_output=True,
|
|
92
|
+
text=True,
|
|
93
|
+
timeout=5,
|
|
94
|
+
)
|
|
95
|
+
except Exception as exc:
|
|
96
|
+
return {"health": "critical", "summary": f"git probe failed: {exc}", "evidence": [str(repo_path)]}
|
|
97
|
+
if inside.returncode != 0 or inside.stdout.strip() != "true":
|
|
98
|
+
return {"health": "critical", "summary": f"not a git repo: {repo_path}", "evidence": [inside.stderr.strip() or inside.stdout.strip()]}
|
|
99
|
+
|
|
100
|
+
branch = subprocess.run(
|
|
101
|
+
["git", "rev-parse", "--abbrev-ref", "HEAD"],
|
|
102
|
+
cwd=str(repo_path),
|
|
103
|
+
capture_output=True,
|
|
104
|
+
text=True,
|
|
105
|
+
timeout=5,
|
|
106
|
+
)
|
|
107
|
+
status = subprocess.run(
|
|
108
|
+
["git", "status", "--porcelain"],
|
|
109
|
+
cwd=str(repo_path),
|
|
110
|
+
capture_output=True,
|
|
111
|
+
text=True,
|
|
112
|
+
timeout=5,
|
|
113
|
+
)
|
|
114
|
+
config = watcher.get("config") or {}
|
|
115
|
+
expected_branch = str(config.get("expected_branch") or "").strip()
|
|
116
|
+
dirty = bool(status.stdout.strip())
|
|
117
|
+
health = "healthy"
|
|
118
|
+
evidence = [f"branch={branch.stdout.strip() or 'unknown'}", f"dirty={dirty}"]
|
|
119
|
+
summary = f"repo clean at {repo_path}"
|
|
120
|
+
if expected_branch and branch.stdout.strip() and branch.stdout.strip() != expected_branch:
|
|
121
|
+
health = "degraded"
|
|
122
|
+
summary = f"repo branch drifted from {expected_branch}"
|
|
123
|
+
evidence.append(f"expected_branch={expected_branch}")
|
|
124
|
+
if dirty and not bool(config.get("allow_dirty")):
|
|
125
|
+
health = "degraded" if health == "healthy" else health
|
|
126
|
+
summary = f"repo has uncommitted drift at {repo_path}"
|
|
127
|
+
evidence.extend(status.stdout.strip().splitlines()[:5])
|
|
128
|
+
return {"health": health, "summary": summary, "evidence": evidence}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _cron_threshold_seconds(cron_payload: dict) -> int | None:
|
|
132
|
+
if cron_payload.get("interval_seconds"):
|
|
133
|
+
return max(int(cron_payload["interval_seconds"]) * 2, 900)
|
|
134
|
+
if cron_payload.get("schedule"):
|
|
135
|
+
return 36 * 3600
|
|
136
|
+
if cron_payload.get("run_at_load"):
|
|
137
|
+
return None
|
|
138
|
+
return 24 * 3600
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _evaluate_cron_drift(watcher: dict) -> dict:
|
|
142
|
+
cron_id = str(watcher.get("target") or "").strip()
|
|
143
|
+
manifest = _load_manifest()
|
|
144
|
+
cron_payload = next((item for item in manifest if str(item.get("id") or "").strip() == cron_id), None)
|
|
145
|
+
if not cron_payload:
|
|
146
|
+
return {"health": "critical", "summary": f"cron missing from manifest: {cron_id}", "evidence": [str(_manifest_file())]}
|
|
147
|
+
threshold = _cron_threshold_seconds(cron_payload)
|
|
148
|
+
if threshold is None:
|
|
149
|
+
return {"health": "healthy", "summary": f"cron {cron_id} is run_at_load-only", "evidence": ["no periodic freshness expected"]}
|
|
150
|
+
last_run = _load_last_cron_run(cron_id)
|
|
151
|
+
if not last_run:
|
|
152
|
+
return {"health": "critical", "summary": f"cron {cron_id} has never run", "evidence": [f"threshold_seconds={threshold}"]}
|
|
153
|
+
age = (datetime.now(UTC) - last_run).total_seconds()
|
|
154
|
+
if age > threshold * 2:
|
|
155
|
+
health = "critical"
|
|
156
|
+
elif age > threshold:
|
|
157
|
+
health = "degraded"
|
|
158
|
+
else:
|
|
159
|
+
health = "healthy"
|
|
160
|
+
return {
|
|
161
|
+
"health": health,
|
|
162
|
+
"summary": f"cron {cron_id} freshness checked",
|
|
163
|
+
"evidence": [f"age_seconds={int(age)}", f"threshold_seconds={threshold}", f"last_run={last_run.isoformat()}"],
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _evaluate_api_health(watcher: dict) -> dict:
|
|
168
|
+
url = str(watcher.get("target") or "").strip()
|
|
169
|
+
config = watcher.get("config") or {}
|
|
170
|
+
timeout = float(config.get("timeout_seconds") or 3)
|
|
171
|
+
allowed_min = int(config.get("allowed_min") or 200)
|
|
172
|
+
allowed_max = int(config.get("allowed_max") or 399)
|
|
173
|
+
method = str(config.get("method") or "GET").upper()
|
|
174
|
+
req = request.Request(url, method=method)
|
|
175
|
+
try:
|
|
176
|
+
with request.urlopen(req, timeout=timeout) as resp:
|
|
177
|
+
code = int(getattr(resp, "status", 200))
|
|
178
|
+
except error.HTTPError as exc:
|
|
179
|
+
code = int(exc.code)
|
|
180
|
+
except Exception as exc:
|
|
181
|
+
return {"health": "critical", "summary": f"API health probe failed for {url}", "evidence": [str(exc)]}
|
|
182
|
+
health = "healthy" if allowed_min <= code <= allowed_max else "critical"
|
|
183
|
+
return {
|
|
184
|
+
"health": health,
|
|
185
|
+
"summary": f"API {url} returned {code}",
|
|
186
|
+
"evidence": [f"status_code={code}", f"allowed={allowed_min}-{allowed_max}"],
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _evaluate_environment_drift(watcher: dict) -> dict:
|
|
191
|
+
config = watcher.get("config") or {}
|
|
192
|
+
mode = str(config.get("mode") or "env_var").strip().lower()
|
|
193
|
+
target = str(watcher.get("target") or "").strip()
|
|
194
|
+
if mode == "env_var":
|
|
195
|
+
current = os.environ.get(target, "")
|
|
196
|
+
expected = str(config.get("expected_value") or "").strip()
|
|
197
|
+
if not current:
|
|
198
|
+
return {"health": "critical", "summary": f"env var missing: {target}", "evidence": [target]}
|
|
199
|
+
if expected and current != expected:
|
|
200
|
+
return {"health": "degraded", "summary": f"env var drift: {target}", "evidence": [f"expected={expected}", f"current={current}"]}
|
|
201
|
+
return {"health": "healthy", "summary": f"env var present: {target}", "evidence": [target]}
|
|
202
|
+
path = Path(target).expanduser()
|
|
203
|
+
if mode == "dir_exists":
|
|
204
|
+
healthy = path.is_dir()
|
|
205
|
+
else:
|
|
206
|
+
healthy = path.exists()
|
|
207
|
+
return {
|
|
208
|
+
"health": "healthy" if healthy else "critical",
|
|
209
|
+
"summary": f"{mode} {'OK' if healthy else 'missing'} for {path}",
|
|
210
|
+
"evidence": [str(path)],
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _evaluate_expiry(watcher: dict) -> dict:
|
|
215
|
+
config = watcher.get("config") or {}
|
|
216
|
+
due_at = _parse_dt(str(config.get("due_at") or watcher.get("target") or ""))
|
|
217
|
+
if not due_at:
|
|
218
|
+
return {"health": "critical", "summary": f"expiry watcher missing due_at: {watcher.get('watcher_id')}", "evidence": []}
|
|
219
|
+
warn_days = int(config.get("warn_days") or 21)
|
|
220
|
+
critical_days = int(config.get("critical_days") or 7)
|
|
221
|
+
remaining = due_at - datetime.now(UTC)
|
|
222
|
+
days = remaining.total_seconds() / 86400
|
|
223
|
+
if days <= critical_days:
|
|
224
|
+
health = "critical"
|
|
225
|
+
elif days <= warn_days:
|
|
226
|
+
health = "degraded"
|
|
227
|
+
else:
|
|
228
|
+
health = "healthy"
|
|
229
|
+
return {
|
|
230
|
+
"health": health,
|
|
231
|
+
"summary": f"expiry watcher '{watcher.get('title')}' due in {days:.1f} days",
|
|
232
|
+
"evidence": [f"due_at={due_at.isoformat()}", f"warn_days={warn_days}", f"critical_days={critical_days}"],
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def evaluate_state_watcher(watcher: dict) -> dict:
|
|
237
|
+
watcher_type = str(watcher.get("watcher_type") or "").strip().lower()
|
|
238
|
+
if watcher_type == "repo_drift":
|
|
239
|
+
result = _evaluate_repo_drift(watcher)
|
|
240
|
+
elif watcher_type == "cron_drift":
|
|
241
|
+
result = _evaluate_cron_drift(watcher)
|
|
242
|
+
elif watcher_type == "api_health":
|
|
243
|
+
result = _evaluate_api_health(watcher)
|
|
244
|
+
elif watcher_type == "environment_drift":
|
|
245
|
+
result = _evaluate_environment_drift(watcher)
|
|
246
|
+
elif watcher_type == "expiry":
|
|
247
|
+
result = _evaluate_expiry(watcher)
|
|
248
|
+
else:
|
|
249
|
+
result = {"health": "critical", "summary": f"unsupported watcher type: {watcher_type}", "evidence": []}
|
|
250
|
+
return {
|
|
251
|
+
"watcher_id": watcher.get("watcher_id", ""),
|
|
252
|
+
"title": watcher.get("title", ""),
|
|
253
|
+
"watcher_type": watcher_type,
|
|
254
|
+
"target": watcher.get("target", ""),
|
|
255
|
+
"severity": watcher.get("severity", "warn"),
|
|
256
|
+
"checked_at": _now_iso(),
|
|
257
|
+
**result,
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _list_watchers(*, status: str) -> list[dict]:
|
|
262
|
+
db_path = _db_path()
|
|
263
|
+
if not db_path.is_file():
|
|
264
|
+
return []
|
|
265
|
+
conn = sqlite3.connect(str(db_path))
|
|
266
|
+
conn.row_factory = sqlite3.Row
|
|
267
|
+
clauses = []
|
|
268
|
+
params = []
|
|
269
|
+
if status:
|
|
270
|
+
clauses.append("status = ?")
|
|
271
|
+
params.append(status)
|
|
272
|
+
where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
|
|
273
|
+
try:
|
|
274
|
+
rows = conn.execute(
|
|
275
|
+
f"""SELECT watcher_id, watcher_type, title, target, severity, status, config, last_health, last_result, last_checked_at
|
|
276
|
+
FROM state_watchers
|
|
277
|
+
{where}
|
|
278
|
+
ORDER BY updated_at DESC, watcher_id DESC""",
|
|
279
|
+
tuple(params),
|
|
280
|
+
).fetchall()
|
|
281
|
+
except sqlite3.OperationalError:
|
|
282
|
+
conn.close()
|
|
283
|
+
return []
|
|
284
|
+
conn.close()
|
|
285
|
+
watchers = []
|
|
286
|
+
for row in rows:
|
|
287
|
+
watcher = dict(row)
|
|
288
|
+
try:
|
|
289
|
+
watcher["config"] = json.loads(watcher.get("config") or "{}")
|
|
290
|
+
except Exception:
|
|
291
|
+
watcher["config"] = {}
|
|
292
|
+
watchers.append(watcher)
|
|
293
|
+
return watchers
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _persist_result(result: dict) -> None:
|
|
297
|
+
db_path = _db_path()
|
|
298
|
+
if not db_path.is_file():
|
|
299
|
+
return
|
|
300
|
+
conn = sqlite3.connect(str(db_path))
|
|
301
|
+
conn.execute(
|
|
302
|
+
"""UPDATE state_watchers
|
|
303
|
+
SET last_health = ?, last_result = ?, last_checked_at = ?, updated_at = datetime('now')
|
|
304
|
+
WHERE watcher_id = ?""",
|
|
305
|
+
(
|
|
306
|
+
result["health"],
|
|
307
|
+
json.dumps(result, ensure_ascii=False),
|
|
308
|
+
result["checked_at"],
|
|
309
|
+
result["watcher_id"],
|
|
310
|
+
),
|
|
311
|
+
)
|
|
312
|
+
conn.commit()
|
|
313
|
+
conn.close()
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def run_state_watchers(*, persist: bool = True, status: str = "active") -> dict:
|
|
317
|
+
watchers = _list_watchers(status=status)
|
|
318
|
+
results = [evaluate_state_watcher(watcher) for watcher in watchers]
|
|
319
|
+
counts = {"healthy": 0, "degraded": 0, "critical": 0, "unknown": 0}
|
|
320
|
+
for result in results:
|
|
321
|
+
counts[result["health"]] = counts.get(result["health"], 0) + 1
|
|
322
|
+
if persist:
|
|
323
|
+
_persist_result(result)
|
|
324
|
+
summary = {
|
|
325
|
+
"generated_at": _now_iso(),
|
|
326
|
+
"watcher_count": len(results),
|
|
327
|
+
"counts": counts,
|
|
328
|
+
"watchers": results,
|
|
329
|
+
}
|
|
330
|
+
if persist:
|
|
331
|
+
summary_file = _summary_file()
|
|
332
|
+
summary_file.parent.mkdir(parents=True, exist_ok=True)
|
|
333
|
+
summary_file.write_text(json.dumps(summary, indent=2, ensure_ascii=False))
|
|
334
|
+
return summary
|