nexo-brain 1.2.3 → 1.4.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.
Files changed (29) hide show
  1. package/README.md +10 -5
  2. package/package.json +1 -1
  3. package/src/__pycache__/evolution_cycle.cpython-314.pyc +0 -0
  4. package/src/cognitive.py +45 -0
  5. package/src/evolution_cycle.py +266 -0
  6. package/src/plugins/guard.py +235 -1
  7. package/src/scripts/__pycache__/check-context.cpython-314.pyc +0 -0
  8. package/src/scripts/__pycache__/nexo-auto-update.cpython-314.pyc +0 -0
  9. package/src/scripts/__pycache__/nexo-catchup.cpython-314.pyc +0 -0
  10. package/src/scripts/__pycache__/nexo-cognitive-decay.cpython-314.pyc +0 -0
  11. package/src/scripts/__pycache__/nexo-daily-self-audit.cpython-314.pyc +0 -0
  12. package/src/scripts/__pycache__/nexo-evolution-run.cpython-314.pyc +0 -0
  13. package/src/scripts/__pycache__/nexo-immune.cpython-314.pyc +0 -0
  14. package/src/scripts/__pycache__/nexo-learning-validator.cpython-314.pyc +0 -0
  15. package/src/scripts/__pycache__/nexo-postmortem-consolidator.cpython-314.pyc +0 -0
  16. package/src/scripts/__pycache__/nexo-reflection.cpython-314.pyc +0 -0
  17. package/src/scripts/__pycache__/nexo-sleep.cpython-314.pyc +0 -0
  18. package/src/scripts/__pycache__/nexo-synthesis.cpython-314.pyc +0 -0
  19. package/src/scripts/check-context.py +257 -0
  20. package/src/scripts/nexo-catchup.py +59 -5
  21. package/src/scripts/nexo-cognitive-decay.py +8 -0
  22. package/src/scripts/nexo-daily-self-audit.py +168 -183
  23. package/src/scripts/nexo-evolution-run.py +584 -0
  24. package/src/scripts/nexo-immune.py +108 -91
  25. package/src/scripts/nexo-learning-validator.py +226 -0
  26. package/src/scripts/nexo-postmortem-consolidator.py +230 -414
  27. package/src/scripts/nexo-sleep.py +283 -503
  28. package/src/scripts/nexo-synthesis.py +141 -432
  29. package/src/tools_sessions.py +20 -12
@@ -0,0 +1,584 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ NEXO Evolution — Standalone weekly runner with real execution.
4
+ Cron: 0 3 * * 0 (Sundays 3:00 AM)
5
+
6
+ Runs independently of Cortex. Calls Opus API directly to analyze
7
+ the past week and generate improvement proposals.
8
+
9
+ AUTO proposals are executed: snapshot → apply → validate → commit/rollback.
10
+ PROPOSE proposals are logged for the user's review.
11
+ """
12
+
13
+ import json
14
+ import os
15
+ import py_compile
16
+ import sqlite3
17
+ import subprocess
18
+ import sys
19
+ from datetime import datetime, date, timedelta
20
+ from pathlib import Path
21
+
22
+ # ── Paths ────────────────────────────────────────────────────────────────
23
+ CLAUDE_DIR = Path.home() / ".nexo"
24
+ NEXO_DB = CLAUDE_DIR / "nexo.db"
25
+ CORTEX_DIR = CLAUDE_DIR / "cortex"
26
+ OBJECTIVE_FILE = CORTEX_DIR / "evolution-objective.json"
27
+ LOG_DIR = CLAUDE_DIR / "logs"
28
+ SNAPSHOTS_DIR = CLAUDE_DIR / "snapshots"
29
+ SANDBOX_DIR = CLAUDE_DIR / "sandbox" / "workspace"
30
+ MAX_CONSECUTIVE_FAILURES = 3
31
+ MAX_SNAPSHOTS = 8
32
+
33
+ # ── Safe zones for AUTO execution ────────────────────────────────────────
34
+ # "review" mode (owner): broader zones, but nothing executes without approval
35
+ # "auto" mode (public users): restricted to user scripts and plugins ONLY
36
+ AUTO_SAFE_PREFIXES = [
37
+ str(CLAUDE_DIR / "scripts") + "/",
38
+ str(CLAUDE_DIR / "cortex") + "/",
39
+ str(CLAUDE_DIR / "plugins") + "/",
40
+ str(CLAUDE_DIR / "logs") + "/",
41
+ str(CLAUDE_DIR / "coordination") + "/",
42
+ ]
43
+
44
+ # Public mode: only user-created scripts — NEVER core, cortex, or plugins
45
+ AUTO_SAFE_PREFIXES_PUBLIC = [
46
+ str(CLAUDE_DIR / "scripts") + "/",
47
+ ]
48
+
49
+ # ── Immutable files — NEVER touch (applies to ALL modes) ────────────────
50
+ IMMUTABLE_FILES = {
51
+ "db.py", "server.py", "plugin_loader.py", "nexo-watchdog.sh",
52
+ "cortex-wrapper.py", "CLAUDE.md", "personality.md",
53
+ "the user-profile.md", "evolution_cycle.py",
54
+ # Core cognitive engine — never auto-modified
55
+ "cognitive.py", "knowledge_graph.py", "storage_router.py",
56
+ # Core tools — never auto-modified
57
+ "tools_sessions.py", "tools_coordination.py", "tools_reminders.py",
58
+ "tools_reminders_crud.py", "tools_learnings.py", "tools_credentials.py",
59
+ "tools_task_history.py", "tools_menu.py",
60
+ }
61
+
62
+ # ── Claude CLI path ──────────────────────────────────────────────────────
63
+ CLAUDE_CLI = Path.home() / ".local" / "bin" / "claude"
64
+
65
+ # ── Logging ──────────────────────────────────────────────────────────────
66
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
67
+ LOG_FILE = LOG_DIR / "evolution.log"
68
+
69
+
70
+ def log(msg: str):
71
+ ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
72
+ line = f"[{ts}] {msg}"
73
+ print(line, flush=True)
74
+ with open(LOG_FILE, "a") as f:
75
+ f.write(line + "\n")
76
+
77
+
78
+ # ── Import from evolution_cycle.py ───────────────────────────────────────
79
+ sys.path.insert(0, str(CORTEX_DIR))
80
+ from evolution_cycle import (
81
+ load_objective, save_objective, get_week_data, build_evolution_prompt,
82
+ dry_run_restore_test, max_auto_changes, create_snapshot
83
+ )
84
+
85
+
86
+ # ── Consecutive failure tracking ─────────────────────────────────────────
87
+ def get_consecutive_failures() -> int:
88
+ obj = load_objective()
89
+ return obj.get("consecutive_failures", 0)
90
+
91
+
92
+ def set_consecutive_failures(count: int):
93
+ obj = load_objective()
94
+ obj["consecutive_failures"] = count
95
+ save_objective(obj)
96
+
97
+
98
+ # ── Claude CLI call ──────────────────────────────────────────────────────
99
+ CLI_TIMEOUT = 600 # 10 minutes — Opus needs time for large prompts
100
+
101
+
102
+ def call_claude_cli(prompt: str) -> str:
103
+ """Call claude -p prompt --model opus via subprocess. Returns stdout text."""
104
+ env = os.environ.copy()
105
+ env.pop("CLAUDECODE", None)
106
+ env.pop("CLAUDE_CODE", None)
107
+
108
+ result = subprocess.run(
109
+ [str(CLAUDE_CLI), "-p", prompt, "--model", "opus",
110
+ "--allowedTools", "Read,Write,Edit,Glob,Grep"],
111
+ capture_output=True,
112
+ text=True,
113
+ timeout=CLI_TIMEOUT,
114
+ env=env,
115
+ )
116
+ if result.returncode != 0:
117
+ raise RuntimeError(f"claude CLI exited {result.returncode}: {result.stderr[:500]}")
118
+ return result.stdout
119
+
120
+
121
+ # ── File safety validation ───────────────────────────────────────────────
122
+ def is_safe_path(filepath: str, mode: str = "auto") -> bool:
123
+ """Check if a file path is within safe zones and not immutable.
124
+ mode='auto' (public): restricted to scripts/ and plugins/ only.
125
+ mode='review' (owner): broader zones but nothing executes without approval anyway.
126
+ """
127
+ expanded = str(Path(filepath).expanduser().resolve())
128
+ filename = Path(expanded).name
129
+
130
+ if filename in IMMUTABLE_FILES:
131
+ return False
132
+
133
+ prefixes = AUTO_SAFE_PREFIXES if mode == "review" else AUTO_SAFE_PREFIXES_PUBLIC
134
+ for prefix in prefixes:
135
+ resolved_prefix = str(Path(prefix).expanduser().resolve())
136
+ if expanded.startswith(resolved_prefix):
137
+ return True
138
+
139
+ return False
140
+
141
+
142
+ def validate_syntax(filepath: str) -> tuple[bool, str]:
143
+ """Basic syntax validation for known file types."""
144
+ path = Path(filepath)
145
+ ext = path.suffix
146
+
147
+ if ext == ".py":
148
+ try:
149
+ py_compile.compile(str(path), doraise=True)
150
+ return True, "Python syntax OK"
151
+ except Exception as e:
152
+ return False, f"Validation error: {e}"
153
+
154
+ elif ext == ".sh":
155
+ try:
156
+ result = subprocess.run(
157
+ ["bash", "-n", str(path)],
158
+ capture_output=True, text=True, timeout=10
159
+ )
160
+ if result.returncode == 0:
161
+ return True, "Bash syntax OK"
162
+ return False, f"Bash syntax error: {result.stderr[:200]}"
163
+ except Exception as e:
164
+ return False, f"Validation error: {e}"
165
+
166
+ elif ext == ".json":
167
+ try:
168
+ json.loads(Path(filepath).read_text())
169
+ return True, "JSON valid"
170
+ except Exception as e:
171
+ return False, f"JSON error: {e}"
172
+
173
+ elif ext == ".md":
174
+ return True, "Markdown (no validation needed)"
175
+
176
+ return True, f"No validator for {ext} (accepted)"
177
+
178
+
179
+ # ── Apply a single change operation ──────────────────────────────────────
180
+ def apply_change(change: dict) -> tuple[bool, str]:
181
+ """Apply a single file change operation. Returns (success, message)."""
182
+ filepath = str(Path(change["file"]).expanduser())
183
+ operation = change.get("operation", "")
184
+ content = change.get("content", "")
185
+
186
+ if not is_safe_path(filepath):
187
+ return False, f"BLOCKED: {filepath} is outside safe zones or immutable"
188
+
189
+ try:
190
+ if operation == "create":
191
+ if Path(filepath).exists():
192
+ return False, f"BLOCKED: {filepath} already exists (create requires new file)"
193
+ Path(filepath).parent.mkdir(parents=True, exist_ok=True)
194
+ Path(filepath).write_text(content)
195
+ # Make scripts executable
196
+ if filepath.endswith(".sh") or filepath.endswith(".py"):
197
+ os.chmod(filepath, 0o755)
198
+ return True, f"Created {filepath}"
199
+
200
+ elif operation == "replace":
201
+ search = change.get("search", "")
202
+ if not search:
203
+ return False, "BLOCKED: replace operation requires 'search' field"
204
+ if not Path(filepath).exists():
205
+ return False, f"BLOCKED: {filepath} does not exist"
206
+ original = Path(filepath).read_text()
207
+ count = original.count(search)
208
+ if count == 0:
209
+ return False, f"BLOCKED: search text not found in {filepath}"
210
+ if count > 1:
211
+ return False, f"BLOCKED: search text matches {count} times (must be unique)"
212
+ new_content = original.replace(search, content, 1)
213
+ Path(filepath).write_text(new_content)
214
+ return True, f"Replaced in {filepath}"
215
+
216
+ elif operation == "append":
217
+ if not Path(filepath).exists():
218
+ return False, f"BLOCKED: {filepath} does not exist"
219
+ with open(filepath, "a") as f:
220
+ f.write(content)
221
+ return True, f"Appended to {filepath}"
222
+
223
+ else:
224
+ return False, f"BLOCKED: unknown operation '{operation}'"
225
+
226
+ except Exception as e:
227
+ return False, f"ERROR: {e}"
228
+
229
+
230
+ # ── Execute AUTO proposals ───────────────────────────────────────────────
231
+ def execute_auto_proposal(proposal: dict, cycle_num: int, conn: sqlite3.Connection) -> dict:
232
+ """Execute an AUTO proposal with snapshot/apply/validate/rollback."""
233
+ changes = proposal.get("changes", [])
234
+ if not changes:
235
+ return {"status": "skipped", "reason": "No changes array in proposal"}
236
+
237
+ # Validate all paths first
238
+ for change in changes:
239
+ filepath = str(Path(change["file"]).expanduser())
240
+ if not is_safe_path(filepath):
241
+ return {"status": "blocked", "reason": f"Unsafe path: {filepath}"}
242
+
243
+ # Collect files to snapshot (existing files only)
244
+ files_to_backup = []
245
+ for change in changes:
246
+ filepath = str(Path(change["file"]).expanduser())
247
+ if Path(filepath).exists():
248
+ files_to_backup.append(filepath)
249
+
250
+ # Create snapshot
251
+ snapshot_ref = None
252
+ if files_to_backup:
253
+ snapshot_ref = create_snapshot(files_to_backup)
254
+ log(f" Snapshot created: {snapshot_ref}")
255
+
256
+ # Apply changes
257
+ applied_files = []
258
+ all_results = []
259
+ try:
260
+ for change in changes:
261
+ success, msg = apply_change(change)
262
+ all_results.append(msg)
263
+ log(f" {msg}")
264
+ if not success:
265
+ raise RuntimeError(f"Change failed: {msg}")
266
+ filepath = str(Path(change["file"]).expanduser())
267
+ applied_files.append(filepath)
268
+
269
+ # Validate all modified/created files
270
+ for filepath in applied_files:
271
+ valid, vmsg = validate_syntax(filepath)
272
+ all_results.append(vmsg)
273
+ log(f" Validate: {vmsg}")
274
+ if not valid:
275
+ raise RuntimeError(f"Validation failed: {vmsg}")
276
+
277
+ return {
278
+ "status": "applied",
279
+ "snapshot_ref": snapshot_ref,
280
+ "files_changed": applied_files,
281
+ "test_result": "; ".join(all_results),
282
+ }
283
+
284
+ except RuntimeError as e:
285
+ # Rollback
286
+ log(f" ROLLBACK: {e}")
287
+ if snapshot_ref:
288
+ try:
289
+ restore_script = CLAUDE_DIR / "scripts" / "nexo-snapshot-restore.sh"
290
+ subprocess.run(
291
+ [str(restore_script), snapshot_ref],
292
+ capture_output=True, timeout=15, check=True
293
+ )
294
+ log(f" Restored from snapshot {snapshot_ref}")
295
+ except Exception as re:
296
+ log(f" CRITICAL: Restore failed: {re}")
297
+ else:
298
+ # Remove created files that didn't exist before
299
+ for filepath in applied_files:
300
+ if filepath not in files_to_backup:
301
+ Path(filepath).unlink(missing_ok=True)
302
+ log(f" Removed created file: {filepath}")
303
+
304
+ return {
305
+ "status": "failed",
306
+ "snapshot_ref": snapshot_ref,
307
+ "files_changed": [],
308
+ "test_result": f"ROLLBACK: {e}; " + "; ".join(all_results),
309
+ }
310
+
311
+
312
+ # ── Review followup for owner mode ──────────────────────────────────────
313
+ def _create_review_followup(conn: sqlite3.Connection, cycle_num: int,
314
+ items: list[dict], analysis: str):
315
+ """Create a followup summarizing Evolution proposals for owner review."""
316
+ tomorrow = (date.today() + timedelta(days=1)).isoformat()
317
+ followup_id = f"NF-EVO-C{cycle_num}"
318
+
319
+ public_items = [i for i in items if i.get("scope") == "public"]
320
+ local_items = [i for i in items if i.get("scope") != "public"]
321
+
322
+ lines = [f"Evolution Cycle #{cycle_num} — {len(items)} propuestas para revisar."]
323
+ lines.append(f"Análisis: {analysis[:200]}")
324
+ lines.append("")
325
+
326
+ if public_items:
327
+ lines.append(f"PARA TODOS ({len(public_items)}):")
328
+ for i, item in enumerate(public_items, 1):
329
+ lines.append(f" {i}. [{item['dimension']}] {item['action'][:120]}")
330
+ lines.append(f" Why: {item['reasoning'][:100]}")
331
+ lines.append("")
332
+
333
+ if local_items:
334
+ lines.append(f"SOLO PARA TI ({len(local_items)}):")
335
+ for i, item in enumerate(local_items, 1):
336
+ lines.append(f" {i}. [{item['dimension']}] {item['action'][:120]}")
337
+ lines.append(f" Why: {item['reasoning'][:100]}")
338
+
339
+ description = "\n".join(lines)
340
+
341
+ try:
342
+ now_epoch = datetime.now().timestamp()
343
+ conn.execute(
344
+ "INSERT OR REPLACE INTO followups (id, description, date, status, verification, created_at, updated_at) "
345
+ "VALUES (?, ?, ?, 'pending', ?, ?, ?)",
346
+ (followup_id, description, tomorrow,
347
+ f"SELECT * FROM evolution_log WHERE cycle_number={cycle_num}",
348
+ now_epoch, now_epoch)
349
+ )
350
+ conn.commit()
351
+ log(f" Followup {followup_id} created for {tomorrow}")
352
+ except Exception as e:
353
+ log(f" WARN: Failed to create followup: {e}")
354
+
355
+
356
+ # ── Main run ─────────────────────────────────────────────────────────────
357
+ def run():
358
+ log("=" * 60)
359
+ log("NEXO Evolution cycle starting (standalone, v2 — real execution)")
360
+
361
+ # Check objective
362
+ objective = load_objective()
363
+ if not objective:
364
+ log("ERROR: No evolution-objective.json found")
365
+ return
366
+ if not objective.get("evolution_enabled", True):
367
+ log(f"Evolution DISABLED: {objective.get('disabled_reason', 'unknown')}")
368
+ return
369
+
370
+ # Circuit breaker: consecutive failures
371
+ failures = get_consecutive_failures()
372
+ if failures >= MAX_CONSECUTIVE_FAILURES:
373
+ log(f"CIRCUIT BREAKER: {failures} consecutive failures. Disabling evolution.")
374
+ objective["evolution_enabled"] = False
375
+ objective["disabled_reason"] = f"Circuit breaker: {failures} consecutive failures at {datetime.now().isoformat()}"
376
+ save_objective(objective)
377
+ return
378
+
379
+ # Dry-run restore test
380
+ log("Running restore dry-run test...")
381
+ if not dry_run_restore_test():
382
+ log("CRITICAL: Restore test failed — aborting")
383
+ set_consecutive_failures(failures + 1)
384
+ return
385
+ log("Restore test PASSED")
386
+
387
+ # Gather data
388
+ log("Gathering week data from nexo.db...")
389
+ week_data = get_week_data(str(NEXO_DB))
390
+ log(f" Learnings: {len(week_data.get('learnings', []))}")
391
+ log(f" Decisions: {len(week_data.get('decisions', []))}")
392
+ log(f" Changes: {len(week_data.get('changes', []))}")
393
+ log(f" Diaries: {len(week_data.get('diaries', []))}")
394
+
395
+ # Build prompt
396
+ prompt = build_evolution_prompt(week_data, objective)
397
+ log(f"Prompt built: {len(prompt)} chars")
398
+
399
+ # Call Opus via claude -p
400
+ log("Calling claude -p --model opus...")
401
+ try:
402
+ raw_response = call_claude_cli(prompt)
403
+ except Exception as e:
404
+ log(f"claude CLI call failed: {e}")
405
+ set_consecutive_failures(failures + 1)
406
+ return
407
+
408
+ log(f"Response received: {len(raw_response)} chars")
409
+
410
+ # Parse JSON
411
+ try:
412
+ text = raw_response
413
+ if "```json" in text:
414
+ text = text.split("```json")[1].split("```")[0]
415
+ elif "```" in text:
416
+ text = text.split("```")[1].split("```")[0]
417
+ response = json.loads(text.strip())
418
+ except Exception as e:
419
+ log(f"JSON parse failed: {e}")
420
+ log(f"Raw (first 500): {raw_response[:500]}")
421
+ set_consecutive_failures(failures + 1)
422
+ return
423
+
424
+ # Reset consecutive failures on successful parse
425
+ set_consecutive_failures(0)
426
+
427
+ log(f"Analysis: {response.get('analysis', 'N/A')[:200]}")
428
+
429
+ # Log patterns
430
+ for p in response.get("patterns", []):
431
+ log(f" Pattern [{p.get('type', '?')}]: {p.get('description', '')[:100]} (freq: {p.get('frequency', '?')})")
432
+
433
+ # Process proposals
434
+ proposals = response.get("proposals", [])
435
+ cycle_num = objective.get("total_evolutions", 0) + 1
436
+ max_auto = max_auto_changes(objective.get("total_evolutions", 0))
437
+ auto_count = 0
438
+ auto_applied = 0
439
+ evolution_mode = objective.get("evolution_mode", "auto") # "auto" (public) or "review" (owner)
440
+
441
+ conn = sqlite3.connect(str(NEXO_DB), timeout=10)
442
+ conn.execute("PRAGMA busy_timeout=5000")
443
+
444
+ # In "review" mode: log everything as pending_review, create followup
445
+ # In "auto" mode: execute AUTO proposals, log PROPOSE as proposed
446
+ review_items = []
447
+
448
+ for p in proposals:
449
+ classification = p.get("classification", "propose")
450
+ dimension = p.get("dimension", "other")
451
+ action = p.get("action", "")
452
+ reasoning = p.get("reasoning", "")
453
+ scope = p.get("scope", "local") # "public" or "local"
454
+
455
+ if evolution_mode == "review":
456
+ # Owner mode: nothing executes, everything queued for review
457
+ log(f" QUEUED [{scope}]: {action[:80]}")
458
+ conn.execute(
459
+ "INSERT INTO evolution_log (cycle_number, dimension, proposal, classification, "
460
+ "reasoning, status) VALUES (?, ?, ?, ?, ?, ?)",
461
+ (cycle_num, dimension, action, classification, reasoning, "pending_review")
462
+ )
463
+ review_items.append({
464
+ "dimension": dimension,
465
+ "action": action,
466
+ "reasoning": reasoning,
467
+ "scope": scope,
468
+ "classification": classification,
469
+ })
470
+
471
+ elif classification == "auto" and auto_count < max_auto:
472
+ # Public mode: execute AUTO proposals
473
+ auto_count += 1
474
+ log(f" AUTO #{auto_count}/{max_auto}: {action[:80]}")
475
+
476
+ result = execute_auto_proposal(p, cycle_num, conn)
477
+ status = result["status"]
478
+
479
+ conn.execute(
480
+ "INSERT INTO evolution_log (cycle_number, dimension, proposal, classification, "
481
+ "reasoning, status, files_changed, snapshot_ref, test_result) "
482
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
483
+ (cycle_num, dimension, action, "auto", reasoning, status,
484
+ json.dumps(result.get("files_changed", [])),
485
+ result.get("snapshot_ref", ""),
486
+ result.get("test_result", ""))
487
+ )
488
+
489
+ if status == "applied":
490
+ auto_applied += 1
491
+ log(f" APPLIED successfully")
492
+ elif status == "blocked":
493
+ log(f" BLOCKED: {result.get('test_result', '')}")
494
+ elif status == "skipped":
495
+ log(f" SKIPPED: {result.get('reason', '')}")
496
+ else:
497
+ log(f" FAILED: {result.get('test_result', '')[:100]}")
498
+
499
+ else:
500
+ # PROPOSE or over auto limit
501
+ if classification == "auto" and auto_count >= max_auto:
502
+ log(f" AUTO→PROPOSE (over limit {max_auto}): {action[:80]}")
503
+ classification = "propose"
504
+ else:
505
+ log(f" PROPOSE: {action[:80]}")
506
+
507
+ conn.execute(
508
+ "INSERT INTO evolution_log (cycle_number, dimension, proposal, classification, "
509
+ "reasoning, status) VALUES (?, ?, ?, ?, ?, ?)",
510
+ (cycle_num, dimension, action, classification, reasoning, "proposed")
511
+ )
512
+
513
+ conn.commit()
514
+
515
+ # In review mode: create followup for owner
516
+ if evolution_mode == "review" and review_items:
517
+ _create_review_followup(conn, cycle_num, review_items, response.get("analysis", ""))
518
+
519
+ # Update metrics
520
+ scores = response.get("dimension_scores", {})
521
+ evidence = response.get("score_evidence", {})
522
+ current = week_data.get("current_metrics", {})
523
+
524
+ for dim, score in scores.items():
525
+ if isinstance(score, (int, float)) and 0 <= score <= 100:
526
+ prev = current.get(dim, {}).get("score", 0)
527
+ delta = int(score) - prev
528
+ conn.execute(
529
+ "INSERT INTO evolution_metrics (dimension, score, evidence, delta) VALUES (?, ?, ?, ?)",
530
+ (dim, int(score), json.dumps(evidence.get(dim, "")), delta)
531
+ )
532
+
533
+ conn.commit()
534
+ conn.close()
535
+
536
+ # Update objective
537
+ objective["last_evolution"] = str(date.today())
538
+ objective["total_evolutions"] = cycle_num
539
+ objective["total_proposals_made"] = objective.get("total_proposals_made", 0) + len(proposals)
540
+ objective["total_auto_applied"] = objective.get("total_auto_applied", 0) + auto_applied
541
+ for dim, score in scores.items():
542
+ if dim in objective.get("dimensions", {}) and isinstance(score, (int, float)):
543
+ objective["dimensions"][dim]["current"] = int(score)
544
+
545
+ objective.setdefault("history", []).insert(0, {
546
+ "cycle": cycle_num,
547
+ "date": str(date.today()),
548
+ "proposals": len(proposals),
549
+ "auto_count": auto_count,
550
+ "auto_applied": auto_applied,
551
+ "analysis": response.get("analysis", "")[:200]
552
+ })
553
+ objective["history"] = objective["history"][:12]
554
+
555
+ save_objective(objective)
556
+
557
+ log(f"Evolution cycle #{cycle_num} COMPLETE: {len(proposals)} proposals "
558
+ f"({auto_count} auto, {auto_applied} applied, "
559
+ f"{len(proposals) - auto_count} propose)")
560
+ log("=" * 60)
561
+
562
+
563
+ def _update_catchup_state():
564
+ """Register successful run for catch-up."""
565
+ try:
566
+ import json as _json
567
+ from pathlib import Path as _Path
568
+ _state_file = _Path.home() / ".nexo" / "operations" / ".catchup-state.json"
569
+ _state = _json.loads(_state_file.read_text()) if _state_file.exists() else {}
570
+ _state["evolution"] = datetime.now().isoformat()
571
+ _state_file.write_text(_json.dumps(_state, indent=2))
572
+ except Exception:
573
+ pass
574
+
575
+
576
+ if __name__ == "__main__":
577
+ try:
578
+ run()
579
+ _update_catchup_state()
580
+ except Exception as e:
581
+ log(f"FATAL: {e}")
582
+ import traceback
583
+ log(traceback.format_exc())
584
+ sys.exit(1)