nexo-brain 5.3.20 → 5.3.21

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 (210) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/package.json +1 -1
  3. package/src/auto_update.py +11 -8
  4. package/src/dashboard/static/favicon 2.svg +32 -0
  5. package/src/dashboard/static/nexo-logo 2.png +0 -0
  6. package/src/dashboard/static/nexo-logo 2.svg +40 -0
  7. package/src/dashboard/static/style 2.css +2458 -0
  8. package/src/dashboard/templates/adaptive 2.html +118 -0
  9. package/src/dashboard/templates/artifacts 2.html +133 -0
  10. package/src/dashboard/templates/backups 2.html +136 -0
  11. package/src/dashboard/templates/base 2.html +417 -0
  12. package/src/dashboard/templates/calendar 2.html +591 -0
  13. package/src/dashboard/templates/chat 2.html +356 -0
  14. package/src/dashboard/templates/claims 2.html +259 -0
  15. package/src/dashboard/templates/cortex 2.html +321 -0
  16. package/src/dashboard/templates/credentials 2.html +128 -0
  17. package/src/dashboard/templates/crons 2.html +370 -0
  18. package/src/dashboard/templates/dashboard 2.html +494 -0
  19. package/src/dashboard/templates/dreams 2.html +252 -0
  20. package/src/dashboard/templates/email 2.html +160 -0
  21. package/src/dashboard/templates/evolution 2.html +189 -0
  22. package/src/dashboard/templates/feed 2.html +249 -0
  23. package/src/dashboard/templates/followup_health 2.html +170 -0
  24. package/src/dashboard/templates/graph 2.html +201 -0
  25. package/src/dashboard/templates/guard 2.html +259 -0
  26. package/src/dashboard/templates/inbox 2.html +251 -0
  27. package/src/dashboard/templates/memory 2.html +420 -0
  28. package/src/dashboard/templates/operations 2.html +608 -0
  29. package/src/dashboard/templates/plugins 2.html +185 -0
  30. package/src/dashboard/templates/protocol 2.html +199 -0
  31. package/src/dashboard/templates/rules 2.html +246 -0
  32. package/src/dashboard/templates/sentiment 2.html +247 -0
  33. package/src/dashboard/templates/sessions 2.html +218 -0
  34. package/src/dashboard/templates/skills 2.html +329 -0
  35. package/src/dashboard/templates/somatic 2.html +73 -0
  36. package/src/dashboard/templates/triggers 2.html +133 -0
  37. package/src/dashboard/templates/trust 2.html +360 -0
  38. package/src/db/__init__ 2.py +259 -0
  39. package/src/db/_core 2.py +437 -0
  40. package/src/db/_credentials 2.py +124 -0
  41. package/src/db/_episodic 2.py +762 -0
  42. package/src/db/_evolution 2.py +54 -0
  43. package/src/db/_fts 2.py +406 -0
  44. package/src/db/_goal_profiles 2.py +376 -0
  45. package/src/db/_hot_context 2.py +660 -0
  46. package/src/db/_outcomes 2.py +800 -0
  47. package/src/db/_personal_scripts 2.py +582 -0
  48. package/src/db/_sessions 2.py +330 -0
  49. package/src/db/_tasks 2.py +91 -0
  50. package/src/db/_watchers 2.py +173 -0
  51. package/src/doctor/formatters 2.py +52 -0
  52. package/src/doctor/models 2.py +69 -0
  53. package/src/doctor/planes 2.py +87 -0
  54. package/src/doctor/providers/__init__ 2.py +1 -0
  55. package/src/doctor/providers/deep 2.py +367 -0
  56. package/src/evolution_cycle 2.py +519 -0
  57. package/src/hooks/auto_capture 2.py +208 -0
  58. package/src/hooks/caffeinate-guard 2.sh +8 -0
  59. package/src/hooks/capture-session 2.sh +21 -0
  60. package/src/hooks/capture-tool-logs 2.sh +158 -0
  61. package/src/hooks/daily-briefing-check 2.sh +33 -0
  62. package/src/hooks/heartbeat-enforcement 2.py +90 -0
  63. package/src/hooks/heartbeat-posttool 2.sh +18 -0
  64. package/src/hooks/inbox-hook 2.sh +76 -0
  65. package/src/hooks/post-compact 2.sh +152 -0
  66. package/src/hooks/pre-compact 2.sh +169 -0
  67. package/src/hooks/protocol-guardrail 2.sh +10 -0
  68. package/src/hooks/protocol-pretool-guardrail 2.sh +9 -0
  69. package/src/hooks/session-stop 2.sh +52 -0
  70. package/src/kg_populate 2.py +292 -0
  71. package/src/maintenance 2.py +53 -0
  72. package/src/memory_backends 2.py +71 -0
  73. package/src/migrate_embeddings 2.py +124 -0
  74. package/src/nexo_sdk 2.py +103 -0
  75. package/src/observability 2.py +199 -0
  76. package/src/plugin_loader 2.py +217 -0
  77. package/src/plugins/__init__ 2.py +0 -0
  78. package/src/plugins/artifact_registry 2.py +450 -0
  79. package/src/plugins/backup 2.py +127 -0
  80. package/src/plugins/claims_tools 2.py +119 -0
  81. package/src/plugins/cognitive_memory 2.py +609 -0
  82. package/src/plugins/core_rules 2.py +252 -0
  83. package/src/plugins/cortex 2.py +1155 -0
  84. package/src/plugins/entities 2.py +67 -0
  85. package/src/plugins/episodic_memory 2.py +560 -0
  86. package/src/plugins/evolution 2.py +167 -0
  87. package/src/plugins/goal_engine 2.py +142 -0
  88. package/src/plugins/guard 2.py +862 -0
  89. package/src/plugins/impact 2.py +29 -0
  90. package/src/plugins/knowledge_graph_tools 2.py +137 -0
  91. package/src/plugins/media_memory_tools 2.py +98 -0
  92. package/src/plugins/memory_export 2.py +196 -0
  93. package/src/plugins/outcomes 2.py +130 -0
  94. package/src/plugins/personal_scripts 2.py +117 -0
  95. package/src/plugins/preferences 2.py +47 -0
  96. package/src/plugins/protocol 2.py +1449 -0
  97. package/src/plugins/simple_api 2.py +106 -0
  98. package/src/plugins/skills 2.py +341 -0
  99. package/src/plugins/state_watchers 2.py +79 -0
  100. package/src/plugins/update 2.py +986 -0
  101. package/src/plugins/user_state_tools 2.py +43 -0
  102. package/src/plugins/workflow 2.py +588 -0
  103. package/src/protocol_settings 2.py +59 -0
  104. package/src/public_contribution 2.py +466 -0
  105. package/src/public_evolution_queue 2.py +241 -0
  106. package/src/requirements 2.txt +14 -0
  107. package/src/retroactive_learnings 2.py +373 -0
  108. package/src/rules/__init__ 2.py +0 -0
  109. package/src/rules/core-rules 2.json +331 -0
  110. package/src/rules/migrate 2.py +207 -0
  111. package/src/runtime_power 2.py +874 -0
  112. package/src/script_registry 2.py +1559 -0
  113. package/src/scripts/check-context 2.py +272 -0
  114. package/src/scripts/deep-sleep/apply_findings 2.py +2327 -0
  115. package/src/scripts/deep-sleep/collect 2.py +928 -0
  116. package/src/scripts/deep-sleep/extract 2.py +330 -0
  117. package/src/scripts/deep-sleep/extract-prompt 2.md +285 -0
  118. package/src/scripts/deep-sleep/synthesize 2.py +312 -0
  119. package/src/scripts/deep-sleep/synthesize-prompt 2.md +336 -0
  120. package/src/scripts/nexo-agent-run 2.py +75 -0
  121. package/src/scripts/nexo-auto-update 2.py +6 -0
  122. package/src/scripts/nexo-backup 2.sh +25 -0
  123. package/src/scripts/nexo-brain-activation 2.sh +140 -0
  124. package/src/scripts/nexo-catchup 2.py +300 -0
  125. package/src/scripts/nexo-cognitive-decay 2.py +257 -0
  126. package/src/scripts/nexo-cortex-cycle 2.py +293 -0
  127. package/src/scripts/nexo-cron-wrapper 2.sh +53 -0
  128. package/src/scripts/nexo-daily-self-audit 2.py +2161 -0
  129. package/src/scripts/nexo-dashboard 2.sh +29 -0
  130. package/src/scripts/nexo-deep-sleep 2.sh +86 -0
  131. package/src/scripts/nexo-evolution-run 2.py +1664 -0
  132. package/src/scripts/nexo-followup-hygiene 2.py +139 -0
  133. package/src/scripts/nexo-hook-record 2.py +42 -0
  134. package/src/scripts/nexo-immune 2.py +936 -0
  135. package/src/scripts/nexo-impact-scorer 2.py +117 -0
  136. package/src/scripts/nexo-inbox-hook 2.sh +74 -0
  137. package/src/scripts/nexo-install 2.py +6 -0
  138. package/src/scripts/nexo-learning-housekeep 2.py +401 -0
  139. package/src/scripts/nexo-learning-validator 2.py +266 -0
  140. package/src/scripts/nexo-migrate 2.py +260 -0
  141. package/src/scripts/nexo-outcome-checker 2.py +127 -0
  142. package/src/scripts/nexo-postmortem-consolidator 2.py +456 -0
  143. package/src/scripts/nexo-pre-commit 2.py +120 -0
  144. package/src/scripts/nexo-prevent-sleep 2.sh +35 -0
  145. package/src/scripts/nexo-proactive-dashboard 2.py +354 -0
  146. package/src/scripts/nexo-reflection 2.py +256 -0
  147. package/src/scripts/nexo-runtime-preflight 2.py +274 -0
  148. package/src/scripts/nexo-sleep 2.py +631 -0
  149. package/src/scripts/nexo-snapshot-restore 2.sh +35 -0
  150. package/src/scripts/nexo-sync-clients 2.py +16 -0
  151. package/src/scripts/nexo-synthesis 2.py +475 -0
  152. package/src/scripts/nexo-tcc-approve 2.sh +79 -0
  153. package/src/scripts/nexo-update 2.sh +306 -0
  154. package/src/scripts/nexo-watchdog 2.sh +1207 -0
  155. package/src/scripts/nexo-watchdog-smoke 2.py +119 -0
  156. package/src/scripts/rehydrate_learnings_from_archive 2.py +245 -0
  157. package/src/server 2.py +1296 -0
  158. package/src/skills/run-nexo-audit-phase/guide 2.md +43 -0
  159. package/src/skills/run-nexo-audit-phase/skill 2.json +59 -0
  160. package/src/skills/run-nexo-core-fix-cycle/guide 2.md +17 -0
  161. package/src/skills/run-nexo-core-fix-cycle/script 2.py +276 -0
  162. package/src/skills/run-nexo-core-fix-cycle/skill 2.json +58 -0
  163. package/src/skills/run-release-final-audit/guide 2.md +16 -0
  164. package/src/skills/run-release-final-audit/script 2.py +259 -0
  165. package/src/skills/run-release-final-audit/skill 2.json +77 -0
  166. package/src/skills/run-runtime-doctor/guide 2.md +12 -0
  167. package/src/skills/run-runtime-doctor/script 2.py +21 -0
  168. package/src/skills/run-runtime-doctor/skill 2.json +25 -0
  169. package/src/skills_runtime 2.py +932 -0
  170. package/src/state_watchers_runtime 2.py +475 -0
  171. package/src/storage_router 2.py +32 -0
  172. package/src/system_catalog 2.py +786 -0
  173. package/src/tools_coordination 2.py +103 -0
  174. package/src/tools_credentials 2.py +68 -0
  175. package/src/tools_drive 2.py +487 -0
  176. package/src/tools_hot_context 2.py +163 -0
  177. package/src/tools_learnings 2.py +612 -0
  178. package/src/tools_menu 2.py +229 -0
  179. package/src/tools_reminders 2.py +88 -0
  180. package/src/tools_reminders_crud 2.py +363 -0
  181. package/src/tools_sessions 2.py +1054 -0
  182. package/src/tools_system_catalog 2.py +19 -0
  183. package/src/tools_task_history 2.py +57 -0
  184. package/src/tools_transcripts 2.py +98 -0
  185. package/src/transcript_utils 2.py +412 -0
  186. package/src/user_context 2.py +46 -0
  187. package/src/user_data_portability 2.py +328 -0
  188. package/src/user_state_model 2.py +170 -0
  189. package/templates/CLAUDE.md 2.template +108 -0
  190. package/templates/CODEX.AGENTS.md 2.template +66 -0
  191. package/templates/launchagents/README 2.md +132 -0
  192. package/templates/launchagents/com.nexo.auto-close-sessions 2.plist +39 -0
  193. package/templates/launchagents/com.nexo.catchup 2.plist +39 -0
  194. package/templates/launchagents/com.nexo.cognitive-decay 2.plist +40 -0
  195. package/templates/launchagents/com.nexo.dashboard 2.plist +43 -0
  196. package/templates/launchagents/com.nexo.deep-sleep 2.plist +43 -0
  197. package/templates/launchagents/com.nexo.evolution 2.plist +44 -0
  198. package/templates/launchagents/com.nexo.followup-hygiene 2.plist +45 -0
  199. package/templates/launchagents/com.nexo.immune 2.plist +41 -0
  200. package/templates/launchagents/com.nexo.postmortem 2.plist +45 -0
  201. package/templates/launchagents/com.nexo.self-audit 2.plist +47 -0
  202. package/templates/launchagents/com.nexo.synthesis 2.plist +45 -0
  203. package/templates/launchagents/com.nexo.watchdog 2.plist +37 -0
  204. package/templates/nexo_helper 2.py +301 -0
  205. package/templates/openclaw 2.json +13 -0
  206. package/templates/plugin-template 2.py +40 -0
  207. package/templates/script-template 2.py +59 -0
  208. package/templates/script-template 2.sh +13 -0
  209. package/templates/skill-script-template 2.py +48 -0
  210. package/templates/skill-template 2.md +33 -0
@@ -0,0 +1,582 @@
1
+ from __future__ import annotations
2
+ """NEXO DB — Personal scripts registry.
3
+
4
+ Filesystem remains the source of truth for personal scripts in NEXO_HOME/scripts/.
5
+ SQLite stores operational metadata so NEXO can reason about what scripts exist,
6
+ what they do, and which schedules/plists are attached to them.
7
+ """
8
+
9
+ import datetime
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+
14
+ from db._core import get_db
15
+ from runtime_home import resolve_nexo_home
16
+
17
+
18
+ NEXO_HOME = resolve_nexo_home()
19
+
20
+
21
+ def _now_text() -> str:
22
+ return datetime.datetime.now().isoformat(timespec="seconds")
23
+
24
+
25
+ def _canonical_scripts_dir() -> Path:
26
+ home = resolve_nexo_home(os.environ.get("NEXO_HOME", str(NEXO_HOME)))
27
+ return home / "scripts"
28
+
29
+
30
+ def _normalize_script_path(path: str | Path) -> str:
31
+ candidate = Path(path).expanduser()
32
+ try:
33
+ relative = candidate.resolve(strict=False).relative_to(_canonical_scripts_dir().resolve(strict=False))
34
+ except Exception:
35
+ return str(candidate)
36
+ return str(_canonical_scripts_dir() / relative)
37
+
38
+
39
+ def _row_to_dict(row) -> dict:
40
+ return dict(row) if row is not None else {}
41
+
42
+
43
+ def _json_load(value, default):
44
+ if value in ("", None):
45
+ return default
46
+ if isinstance(value, (dict, list)):
47
+ return value
48
+ try:
49
+ parsed = json.loads(value)
50
+ except Exception:
51
+ return default
52
+ return parsed if isinstance(parsed, type(default)) else default
53
+
54
+
55
+ def _json_dump(value, default):
56
+ if value in ("", None):
57
+ value = default
58
+ if isinstance(value, str):
59
+ try:
60
+ parsed = json.loads(value)
61
+ value = parsed
62
+ except Exception:
63
+ return json.dumps(default, ensure_ascii=False)
64
+ return json.dumps(value, ensure_ascii=False)
65
+
66
+
67
+ def _safe_slug(value: str) -> str:
68
+ chars: list[str] = []
69
+ for ch in value.lower():
70
+ if ch.isalnum():
71
+ chars.append(ch)
72
+ elif ch in {"-", "_"}:
73
+ chars.append("-")
74
+ slug = "".join(chars).strip("-")
75
+ return slug or "script"
76
+
77
+
78
+ def _ensure_script_id(conn, name: str, path: str) -> str:
79
+ path = _normalize_script_path(path)
80
+ existing = conn.execute(
81
+ "SELECT id FROM personal_scripts WHERE path = ? LIMIT 1",
82
+ (path,),
83
+ ).fetchone()
84
+ if existing:
85
+ return existing["id"]
86
+
87
+ base = f"ps-{_safe_slug(name)}"
88
+ candidate = base
89
+ suffix = 2
90
+ while conn.execute("SELECT 1 FROM personal_scripts WHERE id = ?", (candidate,)).fetchone():
91
+ candidate = f"{base}-{suffix}"
92
+ suffix += 1
93
+ return candidate
94
+
95
+
96
+ def upsert_personal_script(
97
+ *,
98
+ name: str,
99
+ path: str,
100
+ description: str = "",
101
+ runtime: str = "unknown",
102
+ metadata: dict | None = None,
103
+ created_by: str = "manual",
104
+ source: str = "filesystem",
105
+ enabled: bool = True,
106
+ has_inline_metadata: bool = False,
107
+ ) -> dict:
108
+ conn = get_db()
109
+ path = _normalize_script_path(path)
110
+ script_id = _ensure_script_id(conn, name, path)
111
+ now = _now_text()
112
+ conn.execute(
113
+ """
114
+ INSERT INTO personal_scripts (
115
+ id, name, path, description, runtime, metadata_json, created_by, source,
116
+ enabled, has_inline_metadata, last_synced_at, created_at, updated_at
117
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
118
+ ON CONFLICT(path) DO UPDATE SET
119
+ name = excluded.name,
120
+ description = excluded.description,
121
+ runtime = excluded.runtime,
122
+ metadata_json = excluded.metadata_json,
123
+ created_by = COALESCE(NULLIF(personal_scripts.created_by, ''), excluded.created_by),
124
+ source = excluded.source,
125
+ enabled = excluded.enabled,
126
+ has_inline_metadata = excluded.has_inline_metadata,
127
+ last_synced_at = excluded.last_synced_at,
128
+ updated_at = excluded.updated_at
129
+ """,
130
+ (
131
+ script_id,
132
+ name,
133
+ path,
134
+ description,
135
+ runtime,
136
+ _json_dump(metadata or {}, {}),
137
+ created_by,
138
+ source,
139
+ 1 if enabled else 0,
140
+ 1 if has_inline_metadata else 0,
141
+ now,
142
+ now,
143
+ now,
144
+ ),
145
+ )
146
+ row = conn.execute("SELECT * FROM personal_scripts WHERE path = ?", (path,)).fetchone()
147
+ return hydrate_personal_script(_row_to_dict(row))
148
+
149
+
150
+ def delete_missing_personal_scripts(active_paths: list[str]) -> int:
151
+ conn = get_db()
152
+ normalized_paths = [_normalize_script_path(path) for path in active_paths]
153
+ if normalized_paths:
154
+ placeholders = ",".join("?" for _ in normalized_paths)
155
+ rows = conn.execute(
156
+ f"SELECT id FROM personal_scripts WHERE path NOT IN ({placeholders})",
157
+ tuple(normalized_paths),
158
+ ).fetchall()
159
+ else:
160
+ rows = conn.execute("SELECT id FROM personal_scripts").fetchall()
161
+
162
+ count = len(rows)
163
+ for row in rows:
164
+ conn.execute("DELETE FROM personal_scripts WHERE id = ?", (row["id"],))
165
+ return count
166
+
167
+
168
+ def register_personal_script_schedule(
169
+ *,
170
+ script_path: str,
171
+ cron_id: str,
172
+ schedule_type: str,
173
+ schedule_value: str,
174
+ schedule_label: str = "",
175
+ launchd_label: str = "",
176
+ plist_path: str = "",
177
+ description: str = "",
178
+ enabled: bool = True,
179
+ ) -> dict | None:
180
+ conn = get_db()
181
+ script_path = _normalize_script_path(script_path)
182
+ script = conn.execute(
183
+ "SELECT id FROM personal_scripts WHERE path = ?",
184
+ (script_path,),
185
+ ).fetchone()
186
+ if not script:
187
+ return None
188
+
189
+ now = _now_text()
190
+ conn.execute(
191
+ """
192
+ INSERT INTO personal_script_schedules (
193
+ script_id, cron_id, schedule_type, schedule_value, schedule_label,
194
+ launchd_label, plist_path, description, enabled, last_synced_at, created_at, updated_at
195
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
196
+ ON CONFLICT(cron_id) DO UPDATE SET
197
+ script_id = excluded.script_id,
198
+ schedule_type = excluded.schedule_type,
199
+ schedule_value = excluded.schedule_value,
200
+ schedule_label = excluded.schedule_label,
201
+ launchd_label = excluded.launchd_label,
202
+ plist_path = excluded.plist_path,
203
+ description = excluded.description,
204
+ enabled = excluded.enabled,
205
+ last_synced_at = excluded.last_synced_at,
206
+ updated_at = excluded.updated_at
207
+ """,
208
+ (
209
+ script["id"],
210
+ cron_id,
211
+ schedule_type,
212
+ schedule_value,
213
+ schedule_label,
214
+ launchd_label,
215
+ plist_path,
216
+ description,
217
+ 1 if enabled else 0,
218
+ now,
219
+ now,
220
+ now,
221
+ ),
222
+ )
223
+ row = conn.execute(
224
+ "SELECT * FROM personal_script_schedules WHERE cron_id = ?",
225
+ (cron_id,),
226
+ ).fetchone()
227
+ return hydrate_personal_schedule(_row_to_dict(row))
228
+
229
+
230
+ def delete_missing_personal_schedules(active_cron_ids: list[str]) -> int:
231
+ conn = get_db()
232
+ if active_cron_ids:
233
+ placeholders = ",".join("?" for _ in active_cron_ids)
234
+ rows = conn.execute(
235
+ f"SELECT cron_id FROM personal_script_schedules WHERE cron_id NOT IN ({placeholders})",
236
+ tuple(active_cron_ids),
237
+ ).fetchall()
238
+ else:
239
+ rows = conn.execute("SELECT cron_id FROM personal_script_schedules").fetchall()
240
+
241
+ count = len(rows)
242
+ for row in rows:
243
+ conn.execute("DELETE FROM personal_script_schedules WHERE cron_id = ?", (row["cron_id"],))
244
+ return count
245
+
246
+
247
+ def list_personal_script_schedules(script_id: str = "", include_disabled: bool = True) -> list[dict]:
248
+ conn = get_db()
249
+ clauses = []
250
+ params: list = []
251
+ if script_id:
252
+ clauses.append("script_id = ?")
253
+ params.append(script_id)
254
+ if not include_disabled:
255
+ clauses.append("enabled = 1")
256
+ where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
257
+ rows = conn.execute(
258
+ f"SELECT * FROM personal_script_schedules {where} ORDER BY cron_id ASC",
259
+ tuple(params),
260
+ ).fetchall()
261
+ return [hydrate_personal_schedule(_row_to_dict(row)) for row in rows]
262
+
263
+
264
+ def get_personal_script_schedule(cron_id: str) -> dict | None:
265
+ conn = get_db()
266
+ row = conn.execute(
267
+ "SELECT * FROM personal_script_schedules WHERE cron_id = ?",
268
+ (cron_id,),
269
+ ).fetchone()
270
+ return hydrate_personal_schedule(_row_to_dict(row)) if row else None
271
+
272
+
273
+ def delete_personal_script_schedule(cron_id: str) -> int:
274
+ conn = get_db()
275
+ result = conn.execute(
276
+ "DELETE FROM personal_script_schedules WHERE cron_id = ?",
277
+ (cron_id,),
278
+ )
279
+ return int(result.rowcount or 0)
280
+
281
+
282
+ def hydrate_personal_schedule(row: dict) -> dict:
283
+ if not row:
284
+ return {}
285
+ row["enabled"] = bool(row.get("enabled", 1))
286
+ return row
287
+
288
+
289
+ def _latest_cron_runs_by_id(cron_ids: list[str]) -> dict[str, dict]:
290
+ conn = get_db()
291
+ if not cron_ids:
292
+ return {}
293
+ placeholders = ",".join("?" for _ in cron_ids)
294
+ rows = conn.execute(
295
+ f"""
296
+ SELECT c1.cron_id, c1.started_at, c1.exit_code
297
+ FROM cron_runs c1
298
+ JOIN (
299
+ SELECT cron_id, MAX(id) AS max_id
300
+ FROM cron_runs
301
+ WHERE cron_id IN ({placeholders})
302
+ GROUP BY cron_id
303
+ ) latest ON latest.max_id = c1.id
304
+ """,
305
+ tuple(cron_ids),
306
+ ).fetchall()
307
+ return {
308
+ row["cron_id"]: {
309
+ "started_at": row["started_at"],
310
+ "exit_code": row["exit_code"],
311
+ }
312
+ for row in rows
313
+ }
314
+
315
+
316
+ def hydrate_personal_script(row: dict) -> dict:
317
+ if not row:
318
+ return {}
319
+ row["enabled"] = bool(row.get("enabled", 1))
320
+ row["has_inline_metadata"] = bool(row.get("has_inline_metadata", 0))
321
+ row["metadata"] = _json_load(row.pop("metadata_json", "{}"), {})
322
+ return row
323
+
324
+
325
+ def list_personal_scripts(include_disabled: bool = True) -> list[dict]:
326
+ conn = get_db()
327
+ where = "" if include_disabled else "WHERE enabled = 1"
328
+ rows = conn.execute(
329
+ f"SELECT * FROM personal_scripts {where} ORDER BY name COLLATE NOCASE ASC"
330
+ ).fetchall()
331
+ scripts = [hydrate_personal_script(_row_to_dict(row)) for row in rows]
332
+ if not scripts:
333
+ return []
334
+
335
+ schedules_by_script: dict[str, list[dict]] = {}
336
+ cron_ids: list[str] = []
337
+ for schedule in list_personal_script_schedules(include_disabled=include_disabled):
338
+ schedules_by_script.setdefault(schedule["script_id"], []).append(schedule)
339
+ cron_ids.append(schedule["cron_id"])
340
+
341
+ latest_runs = _latest_cron_runs_by_id(cron_ids)
342
+ for script in scripts:
343
+ script_schedules = schedules_by_script.get(script["id"], [])
344
+ for schedule in script_schedules:
345
+ latest = latest_runs.get(schedule["cron_id"])
346
+ if latest:
347
+ schedule["last_run_at"] = latest["started_at"]
348
+ schedule["last_exit_code"] = latest["exit_code"]
349
+ script["schedules"] = script_schedules
350
+ script["has_schedule"] = bool(script_schedules)
351
+ latest = None
352
+ for schedule in script_schedules:
353
+ started_at = schedule.get("last_run_at")
354
+ if started_at and (latest is None or started_at > latest.get("started_at", "")):
355
+ latest = {"started_at": started_at, "exit_code": schedule.get("last_exit_code")}
356
+ if latest:
357
+ script["last_run_at"] = latest["started_at"]
358
+ script["last_exit_code"] = latest["exit_code"]
359
+ return scripts
360
+
361
+
362
+ def get_personal_script(name_or_path: str) -> dict | None:
363
+ conn = get_db()
364
+ normalized_path = _normalize_script_path(name_or_path)
365
+ row = conn.execute(
366
+ """
367
+ SELECT * FROM personal_scripts
368
+ WHERE path = ? OR name = ?
369
+ ORDER BY path = ? DESC
370
+ LIMIT 1
371
+ """,
372
+ (normalized_path, name_or_path, normalized_path),
373
+ ).fetchone()
374
+ if not row:
375
+ return None
376
+ script = hydrate_personal_script(_row_to_dict(row))
377
+ script["schedules"] = list_personal_script_schedules(script["id"])
378
+ script["has_schedule"] = bool(script["schedules"])
379
+ return script
380
+
381
+
382
+ def delete_personal_script(name_or_path: str) -> int:
383
+ conn = get_db()
384
+ normalized_path = _normalize_script_path(name_or_path)
385
+ result = conn.execute(
386
+ "DELETE FROM personal_scripts WHERE path = ? OR name = ? OR id = ?",
387
+ (normalized_path, name_or_path, name_or_path),
388
+ )
389
+ return int(result.rowcount or 0)
390
+
391
+
392
+ def record_personal_script_run(name_or_path: str, exit_code: int, run_at: str | None = None) -> None:
393
+ conn = get_db()
394
+ run_at = run_at or _now_text()
395
+ normalized_path = _normalize_script_path(name_or_path)
396
+ conn.execute(
397
+ """
398
+ UPDATE personal_scripts
399
+ SET last_run_at = ?, last_exit_code = ?, updated_at = ?
400
+ WHERE path = ? OR name = ?
401
+ """,
402
+ (run_at, exit_code, _now_text(), normalized_path, name_or_path),
403
+ )
404
+
405
+
406
+ def sync_personal_scripts_registry(
407
+ script_records: list[dict],
408
+ schedule_records: list[dict] | None = None,
409
+ *,
410
+ prune_missing: bool = True,
411
+ ) -> dict:
412
+ schedule_records = schedule_records or []
413
+ active_paths: list[str] = []
414
+ upserted = 0
415
+ scheduled = 0
416
+
417
+ for record in script_records:
418
+ path = _normalize_script_path(record["path"])
419
+ active_paths.append(path)
420
+ upsert_personal_script(
421
+ name=record.get("name") or Path(path).stem,
422
+ path=path,
423
+ description=record.get("description", ""),
424
+ runtime=record.get("runtime", "unknown"),
425
+ metadata=record.get("metadata", {}),
426
+ created_by=record.get("created_by", "manual"),
427
+ source=record.get("source", "filesystem"),
428
+ enabled=record.get("enabled", True),
429
+ has_inline_metadata=bool(record.get("metadata")),
430
+ )
431
+ upserted += 1
432
+
433
+ pruned_scripts = delete_missing_personal_scripts(active_paths) if prune_missing else 0
434
+
435
+ active_cron_ids: list[str] = []
436
+ for schedule in schedule_records:
437
+ cron_id = schedule.get("cron_id")
438
+ script_path = schedule.get("script_path")
439
+ if not cron_id or not script_path:
440
+ continue
441
+ active_cron_ids.append(cron_id)
442
+ registered = register_personal_script_schedule(
443
+ script_path=script_path,
444
+ cron_id=cron_id,
445
+ schedule_type=schedule.get("schedule_type", ""),
446
+ schedule_value=schedule.get("schedule_value", ""),
447
+ schedule_label=schedule.get("schedule_label", ""),
448
+ launchd_label=schedule.get("launchd_label", ""),
449
+ plist_path=schedule.get("plist_path", ""),
450
+ description=schedule.get("description", ""),
451
+ enabled=schedule.get("enabled", True),
452
+ )
453
+ if registered:
454
+ scheduled += 1
455
+
456
+ pruned_schedules = delete_missing_personal_schedules(active_cron_ids) if prune_missing else 0
457
+ return {
458
+ "ok": True,
459
+ "scripts_upserted": upserted,
460
+ "schedules_upserted": scheduled,
461
+ "scripts_pruned": pruned_scripts,
462
+ "schedules_pruned": pruned_schedules,
463
+ "registered_scripts": len(list_personal_scripts()),
464
+ }
465
+
466
+
467
+ def get_personal_script_health_report(*, fix: bool = False) -> dict:
468
+ if fix:
469
+ from script_registry import reconcile_personal_scripts
470
+
471
+ reconcile_personal_scripts(dry_run=False)
472
+
473
+ from script_registry import classify_scripts_dir, audit_personal_schedules
474
+
475
+ issues: list[dict] = []
476
+ scripts = list_personal_scripts()
477
+ checked = 0
478
+ audit = audit_personal_schedules()
479
+ audit_by_path: dict[str, list[dict]] = {}
480
+ for schedule in audit.get("schedules", []):
481
+ audit_by_path.setdefault(schedule.get("script_path", ""), []).append(schedule)
482
+
483
+ classified = classify_scripts_dir()
484
+ personal_entries = [entry for entry in classified.get("entries", []) if entry.get("classification") == "personal"]
485
+
486
+ for script in scripts:
487
+ checked += 1
488
+ path = Path(script["path"])
489
+ if not path.is_file():
490
+ issues.append({
491
+ "script_id": script["id"],
492
+ "severity": "error",
493
+ "message": f"missing file: {path}",
494
+ })
495
+ for schedule in script.get("schedules", []):
496
+ checked += 1
497
+ plist_path = schedule.get("plist_path", "")
498
+ if plist_path and not Path(plist_path).is_file():
499
+ issues.append({
500
+ "script_id": script["id"],
501
+ "severity": "warn",
502
+ "message": f"missing managed plist for cron {schedule['cron_id']}: {plist_path}",
503
+ })
504
+
505
+ for entry in personal_entries:
506
+ checked += 1
507
+ declared = entry.get("declared_schedule", {})
508
+ if declared.get("required") and not declared.get("valid"):
509
+ issues.append({
510
+ "script_id": f"declared:{entry['name']}",
511
+ "severity": "error",
512
+ "message": f"invalid declared schedule for {entry['name']}: {declared.get('error', 'invalid metadata')}",
513
+ })
514
+ continue
515
+
516
+ if not declared.get("required"):
517
+ continue
518
+
519
+ managed = [
520
+ item for item in audit_by_path.get(entry["path"], [])
521
+ if item.get("schedule_managed")
522
+ ]
523
+ if managed:
524
+ continue
525
+
526
+ related = audit_by_path.get(entry["path"], [])
527
+ reason = "no schedule discovered"
528
+ if related:
529
+ states = ", ".join(item.get("schedule_state", item.get("schedule_origin", "unknown")) for item in related)
530
+ reason = f"discovered but not managed ({states})"
531
+ issues.append({
532
+ "script_id": f"declared:{entry['name']}",
533
+ "severity": "warn",
534
+ "message": (
535
+ f"missing declared managed schedule for {entry['name']}: "
536
+ f"{declared.get('schedule_label', declared.get('cron_id', ''))} [{reason}]"
537
+ ),
538
+ })
539
+
540
+ for schedule in audit.get("schedules", []):
541
+ checked += 1
542
+ if schedule.get("schedule_managed") and schedule.get("schedule_type") == "keep_alive":
543
+ runtime_state = str(schedule.get("runtime_state", "") or "")
544
+ runtime_summary = str(schedule.get("runtime_summary", "") or runtime_state or "runtime issue")
545
+ if runtime_state in {"degraded", "stale", "duplicated"}:
546
+ severity = "error" if runtime_state == "duplicated" else "warn"
547
+ issues.append({
548
+ "script_id": schedule.get("script_name") or schedule.get("script_path") or schedule.get("cron_id"),
549
+ "severity": severity,
550
+ "message": (
551
+ f"keep_alive runtime {schedule['cron_id']}: {runtime_summary}"
552
+ ),
553
+ })
554
+ if schedule.get("schedule_managed"):
555
+ continue
556
+
557
+ severity = "warn"
558
+ if schedule.get("schedule_origin") == "orphan_schedule":
559
+ severity = "error"
560
+ elif schedule.get("schedule_declared") and schedule.get("schedule_matches_declared") is False:
561
+ severity = "error"
562
+
563
+ label = schedule.get("schedule_label") or schedule.get("schedule_value") or schedule.get("schedule_type")
564
+ problems = "; ".join(schedule.get("problems", [])) or schedule.get("schedule_state", "schedule issue")
565
+ target = schedule.get("script_name") or schedule.get("script_path") or schedule.get("cron_id")
566
+ issues.append({
567
+ "script_id": target,
568
+ "severity": severity,
569
+ "message": (
570
+ f"{schedule.get('schedule_origin', 'schedule')} {schedule['cron_id']} "
571
+ f"({label}) for {target}: {problems}"
572
+ ),
573
+ })
574
+
575
+ return {
576
+ "checked": checked,
577
+ "scripts": len(scripts),
578
+ "schedules": sum(len(script.get("schedules", [])) for script in scripts),
579
+ "issues": issues,
580
+ "fixed": bool(fix),
581
+ "schedule_audit": audit,
582
+ }