nexo-brain 2.3.1 → 2.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.
package/README.md CHANGED
@@ -184,11 +184,11 @@ This means long sessions (8+ hours) feel like one continuous conversation instea
184
184
  "hooks": {
185
185
  "PreCompact": [{
186
186
  "matcher": "*",
187
- "hooks": [{"type": "command", "command": "bash path/to/nexo/src/hooks/pre-compact.sh", "timeout": 10}]
187
+ "hooks": [{"type": "command", "command": "bash $NEXO_HOME/hooks/pre-compact.sh", "timeout": 10}]
188
188
  }],
189
189
  "PostCompact": [{
190
190
  "matcher": "*",
191
- "hooks": [{"type": "command", "command": "bash path/to/nexo/src/hooks/post-compact.sh", "timeout": 10}]
191
+ "hooks": [{"type": "command", "command": "bash $NEXO_HOME/hooks/post-compact.sh", "timeout": 10}]
192
192
  }]
193
193
  }
194
194
  }
@@ -364,7 +364,13 @@ A web interface at `localhost:6174` with 6 interactive pages for visual insight
364
364
  | **Adaptive** | Personality signals, learned weights, and current mode |
365
365
  | **Sessions** | Active and historical sessions with timeline and diary entries |
366
366
 
367
- Built with FastAPI backend and D3.js frontend. Runs as a LaunchAgent, auto-starts with the system.
367
+ Built with FastAPI backend and D3.js frontend. Dashboard files are installed to `NEXO_HOME/dashboard/` but must be started manually:
368
+
369
+ ```bash
370
+ python3 ~/.nexo/dashboard/app.py
371
+ ```
372
+
373
+ This opens `localhost:6174` in your browser. Add `--port 8080` to change the port or `--no-browser` to skip auto-opening.
368
374
 
369
375
  ## Full Orchestration System
370
376
 
@@ -499,9 +505,9 @@ atlas
499
505
 
500
506
  Under the hood, the alias runs:
501
507
  ```bash
502
- claude --append-system-prompt "You are NEXO. Run nexo_startup immediately, load context, greet the user." "."
508
+ claude --dangerously-skip-permissions "."
503
509
  ```
504
- `--append-system-prompt` adds to the default system prompt without replacing it (preserves CLAUDE.md). The `"."` triggers the operator to start immediately.
510
+ `--dangerously-skip-permissions` launches Claude Code with tool-use permissions pre-approved so the operator can act autonomously. The `"."` triggers the operator to start immediately. Operator behavior (startup, context, greeting) is defined in `~/.claude/CLAUDE.md`.
505
511
 
506
512
  That's it. No need to run `claude` manually. Your operator will greet you immediately — adapted to the time of day, resuming from where you left off if there's a previous session. No cold starts, no waiting for your input.
507
513
 
@@ -687,7 +693,7 @@ This replaces OpenClaw's default memory system with NEXO Brain's full cognitive
687
693
 
688
694
  ### Any MCP Client
689
695
 
690
- NEXO Brain works with any application that supports the MCP protocol. Configure it as an MCP server pointing to `server.py` in the code directory, with `NEXO_HOME` env var set.
696
+ NEXO Brain works with any application that supports the MCP protocol. Configure it as an MCP server pointing to `server.py` inside `NEXO_HOME` (default `~/.nexo/server.py`), with the `NEXO_HOME` env var set to the same directory.
691
697
 
692
698
  ## Listed On
693
699
 
package/bin/nexo-brain.js CHANGED
@@ -19,7 +19,7 @@ const fs = require("fs");
19
19
  const path = require("path");
20
20
  const readline = require("readline");
21
21
 
22
- let NEXO_HOME = path.join(require("os").homedir(), ".nexo");
22
+ let NEXO_HOME = process.env.NEXO_HOME || path.join(require("os").homedir(), ".nexo");
23
23
  const CLAUDE_SETTINGS = path.join(
24
24
  require("os").homedir(),
25
25
  ".claude",
@@ -124,6 +124,8 @@ const ALL_CORE_HOOKS = [
124
124
  timeout: 10, purpose: "POSTMORTEM — the most important" },
125
125
  { event: "PostToolUse", key: "capture-tool-logs.sh", script: "capture-tool-logs.sh",
126
126
  timeout: 5, purpose: "Operation capture" },
127
+ { event: "PostToolUse", key: "capture-session.sh", script: "capture-session.sh",
128
+ timeout: 3, purpose: "Sensory register (session_buffer.jsonl)" },
127
129
  { event: "PostToolUse", key: "inbox-hook.sh", script: "inbox-hook.sh",
128
130
  timeout: 5, purpose: "Inter-session messaging" },
129
131
  { event: "PreCompact", key: "pre-compact.sh", script: "pre-compact.sh",
@@ -262,7 +264,7 @@ const DAY_MAP = {
262
264
  */
263
265
  function installAllProcesses(platform, pythonPath, nexoHome, schedule, launchAgentsDir) {
264
266
  const home = require("os").homedir();
265
- const nexoCode = path.join(__dirname, "..");
267
+ const nexoCode = nexoHome;
266
268
  const logsDir = path.join(nexoHome, "logs");
267
269
  fs.mkdirSync(logsDir, { recursive: true });
268
270
 
@@ -436,8 +438,10 @@ ${restartPolicy}
436
438
  count++;
437
439
  continue;
438
440
  } else if (proc.type === "runAtLoad") {
439
- // No timer for runAtLoad runs via MCP startup
440
- fs.writeFileSync(serviceFile, service);
441
+ // runAtLoad: enable as a boot-time oneshot service (like macOS RunAtLoad)
442
+ fs.writeFileSync(serviceFile, service + `\n[Install]\nWantedBy=default.target\n`);
443
+ run(`systemctl --user enable ${serviceName}.service`);
444
+ run(`systemctl --user start ${serviceName}.service`);
441
445
  count++;
442
446
  continue;
443
447
  } else if (proc.type === "interval") {
@@ -477,14 +481,15 @@ WantedBy=timers.target
477
481
  const envLine2 = `NEXO_CODE=${nexoCode}`;
478
482
 
479
483
  for (const proc of ALL_PROCESSES) {
480
- if (proc.type === "runAtLoad") continue; // No cron for runAtLoad
481
484
  const sPath = scriptPath(proc);
482
485
  const interp = interpreterPath(proc);
483
486
  const s = getSchedule(proc);
484
487
  const logPath = path.join(logsDir, `${proc.name}-stdout.log`);
485
488
 
486
489
  let cronSpec = "";
487
- if (proc.type === "interval") {
490
+ if (proc.type === "runAtLoad") {
491
+ cronSpec = "@reboot";
492
+ } else if (proc.type === "interval") {
488
493
  cronSpec = `*/${proc.intervalMinutes} * * * *`;
489
494
  } else if (proc.type === "daily") {
490
495
  cronSpec = `${s.minute} ${s.hour} * * *`;
@@ -617,10 +622,11 @@ async function main() {
617
622
  "server.py", "plugin_loader.py",
618
623
  "knowledge_graph.py", "kg_populate.py", "maintenance.py", "storage_router.py",
619
624
  "claim_graph.py", "hnsw_index.py", "evolution_cycle.py", "migrate_embeddings.py",
620
- "auto_close_sessions.py",
625
+ "auto_close_sessions.py", "auto_update.py",
621
626
  "tools_sessions.py", "tools_coordination.py", "tools_reminders.py",
622
627
  "tools_reminders_crud.py", "tools_learnings.py", "tools_credentials.py",
623
628
  "tools_task_history.py", "tools_menu.py",
629
+ "requirements.txt",
624
630
  ];
625
631
  coreFlatFiles.forEach((f) => {
626
632
  const src = path.join(srcDir, f);
@@ -637,6 +643,30 @@ async function main() {
637
643
  });
638
644
  log(" Core files updated.");
639
645
 
646
+ // Reconcile Python dependencies after updating code (mirrors fresh-install logic)
647
+ const migReqFile = path.join(srcDir, "requirements.txt");
648
+ if (fs.existsSync(migReqFile)) {
649
+ const migVenvPy = findVenvPython(NEXO_HOME);
650
+ const migPipPy = migVenvPy || "python3";
651
+ const migPipArgs = ["-m", "pip", "install", "--quiet", "-r", migReqFile];
652
+ if (!migVenvPy) migPipArgs.push("--break-system-packages");
653
+ log(" Reconciling Python dependencies...");
654
+ const migPipResult = spawnSync(migPipPy, migPipArgs, { stdio: "inherit", timeout: 120000 });
655
+ if (migPipResult.status !== 0) {
656
+ log(" WARNING: Failed to reconcile Python deps. Rolling back version...");
657
+ // Restore previous version so next boot retries migration
658
+ fs.writeFileSync(versionFile, JSON.stringify({
659
+ version: installedVersion,
660
+ installed_at: installed.installed_at,
661
+ updated_at: new Date().toISOString(),
662
+ migration_failed: currentVersion,
663
+ }, null, 2));
664
+ log(" Run manually: " + migPipPy + " -m pip install -r src/requirements.txt");
665
+ process.exit(1);
666
+ }
667
+ log(" Python dependencies reconciled.");
668
+ }
669
+
640
670
  // Update plugins (all .py files in plugins/)
641
671
  const pluginsSrc = path.join(srcDir, "plugins");
642
672
  const pluginsDest = path.join(NEXO_HOME, "plugins");
@@ -664,6 +694,14 @@ async function main() {
664
694
  log(" Rules updated.");
665
695
  }
666
696
 
697
+ // Update crons (manifest.json + sync.py — needed by catchup & watchdog)
698
+ const cronsMigSrc = path.join(srcDir, "crons");
699
+ const cronsMigDest = path.join(NEXO_HOME, "crons");
700
+ if (fs.existsSync(cronsMigSrc)) {
701
+ copyDirRec(cronsMigSrc, cronsMigDest);
702
+ log(" Crons updated.");
703
+ }
704
+
667
705
  // Update scripts (all .py, .sh files + subdirectories like deep-sleep/)
668
706
  const scriptsSrc = path.join(srcDir, "scripts");
669
707
  const scriptsDest = path.join(NEXO_HOME, "scripts");
@@ -734,6 +772,28 @@ async function main() {
734
772
  rl.close();
735
773
  return;
736
774
  }
775
+
776
+ // Same version — backfill crons/ if missing (for installs before crons was shipped)
777
+ const cronsDest = path.join(NEXO_HOME, "crons");
778
+ const cronsSrc = path.join(__dirname, "..", "src", "crons");
779
+ if (!fs.existsSync(path.join(cronsDest, "manifest.json")) && fs.existsSync(cronsSrc)) {
780
+ const copyDirRec2 = (src, dest) => {
781
+ fs.mkdirSync(dest, { recursive: true });
782
+ fs.readdirSync(src).forEach(item => {
783
+ if (item === "__pycache__" || item.endsWith(".pyc") || item.endsWith(".db")) return;
784
+ const srcP = path.join(src, item);
785
+ const destP = path.join(dest, item);
786
+ if (fs.statSync(srcP).isDirectory()) copyDirRec2(srcP, destP);
787
+ else fs.copyFileSync(srcP, destP);
788
+ });
789
+ };
790
+ copyDirRec2(cronsSrc, cronsDest);
791
+ log("Backfilled crons/ directory (catchup & watchdog need it).");
792
+ }
793
+
794
+ log(`Already at v${currentVersion}. No migration needed.`);
795
+ rl.close();
796
+ return;
737
797
  } catch (e) {
738
798
  // Version file corrupt — proceed with fresh install
739
799
  }
@@ -782,7 +842,7 @@ async function main() {
782
842
  log("Claude Code not found. Installing...");
783
843
  // Try npx first (no sudo needed), then npm -g as fallback
784
844
  spawnSync("npx", ["-y", "@anthropic-ai/claude-code", "--version"], { stdio: "pipe", timeout: 60000 });
785
- claudeInstalled = run("which claude") || run("npx -y @anthropic-ai/claude-code --version");
845
+ claudeInstalled = run("which claude");
786
846
  if (!claudeInstalled) {
787
847
  // Fallback: npm -g (may need sudo on Linux)
788
848
  const npmCmd = platform === "linux" ? "sudo" : "npm";
@@ -800,6 +860,15 @@ async function main() {
800
860
  } else {
801
861
  log("Claude Code detected.");
802
862
  }
863
+
864
+ // Persist the discovered claude CLI path for scheduled scripts
865
+ const claudeCliPath = run("which claude") || "";
866
+ if (claudeCliPath) {
867
+ const cliPathFile = path.join(NEXO_HOME, "config", "claude-cli-path");
868
+ fs.mkdirSync(path.join(NEXO_HOME, "config"), { recursive: true });
869
+ fs.writeFileSync(cliPathFile, claudeCliPath.trim());
870
+ log(`Claude CLI path saved: ${claudeCliPath.trim()}`);
871
+ }
803
872
  console.log("");
804
873
 
805
874
  // Step 1: Language (P1)
@@ -1236,6 +1305,7 @@ async function main() {
1236
1305
  "evolution_cycle.py",
1237
1306
  "migrate_embeddings.py",
1238
1307
  "auto_close_sessions.py",
1308
+ "auto_update.py",
1239
1309
  "tools_sessions.py",
1240
1310
  "tools_coordination.py",
1241
1311
  "tools_reminders.py",
@@ -1244,6 +1314,7 @@ async function main() {
1244
1314
  "tools_credentials.py",
1245
1315
  "tools_task_history.py",
1246
1316
  "tools_menu.py",
1317
+ "requirements.txt",
1247
1318
  ];
1248
1319
  coreFiles.forEach((f) => {
1249
1320
  const src = path.join(srcDir, f);
@@ -1292,6 +1363,13 @@ async function main() {
1292
1363
  log(" Rules installed.");
1293
1364
  }
1294
1365
 
1366
+ // Crons directory (manifest.json + sync.py — needed by catchup & watchdog)
1367
+ const cronsSrcDir = path.join(srcDir, "crons");
1368
+ if (fs.existsSync(cronsSrcDir)) {
1369
+ copyDirRecursive(cronsSrcDir, path.join(NEXO_HOME, "crons"));
1370
+ log(" Crons installed.");
1371
+ }
1372
+
1295
1373
  // Hooks directory
1296
1374
  const hooksSrcDir = path.join(srcDir, "hooks");
1297
1375
  if (fs.existsSync(hooksSrcDir)) {
@@ -1792,27 +1870,43 @@ ${doScan ? `- Stack: ${Object.keys(profileData.code.languages || {}).slice(0, 5)
1792
1870
  // Step 8: Create shell alias so user can just type the operator's name
1793
1871
  log("Creating shell alias...");
1794
1872
  const aliasName = operatorName.toLowerCase();
1795
- const aliasLine = `alias ${aliasName}='claude --dangerously-skip-permissions "."'`;
1873
+ const savedCliPath = (() => {
1874
+ const p = path.join(NEXO_HOME, "config", "claude-cli-path");
1875
+ try { return fs.readFileSync(p, "utf8").trim(); } catch { return ""; }
1876
+ })();
1877
+ const claudeBin = savedCliPath || run("which claude") || "claude";
1878
+ const aliasLine = `alias ${aliasName}='${claudeBin} --dangerously-skip-permissions "."'`;
1796
1879
  const aliasComment = `# ${operatorName} — start Claude Code with ${operatorName} speaking first`;
1797
1880
 
1798
1881
  // Detect shell and add alias
1799
1882
  const userShell = process.env.SHELL || "/bin/bash";
1800
- const rcFile = userShell.includes("zsh")
1801
- ? path.join(require("os").homedir(), ".zshrc")
1802
- : path.join(require("os").homedir(), ".bash_profile");
1883
+ const homeDir = require("os").homedir();
1884
+ const rcFiles = [];
1803
1885
 
1804
- let rcContent = "";
1805
- if (fs.existsSync(rcFile)) {
1806
- rcContent = fs.readFileSync(rcFile, "utf8");
1886
+ if (userShell.includes("zsh")) {
1887
+ rcFiles.push(path.join(homeDir, ".zshrc"));
1888
+ } else {
1889
+ // Bash: always write to .bash_profile (macOS login shells)
1890
+ rcFiles.push(path.join(homeDir, ".bash_profile"));
1891
+ // Also write to .bashrc (Linux interactive shells) — create if needed
1892
+ const bashrc = path.join(homeDir, ".bashrc");
1893
+ rcFiles.push(bashrc);
1807
1894
  }
1808
1895
 
1809
- if (!rcContent.includes(`alias ${aliasName}=`)) {
1810
- fs.appendFileSync(rcFile, `\n${aliasComment}\n${aliasLine}\n`);
1811
- log(`Added '${aliasName}' alias to ${path.basename(rcFile)}`);
1812
- log(`After setup, open a new terminal and type: ${aliasName}`);
1813
- } else {
1814
- log(`Alias '${aliasName}' already exists in ${path.basename(rcFile)}`);
1896
+ for (const rcFile of rcFiles) {
1897
+ let rcContent = "";
1898
+ if (fs.existsSync(rcFile)) {
1899
+ rcContent = fs.readFileSync(rcFile, "utf8");
1900
+ }
1901
+
1902
+ if (!rcContent.includes(`alias ${aliasName}=`)) {
1903
+ fs.appendFileSync(rcFile, `\n${aliasComment}\n${aliasLine}\n`);
1904
+ log(`Added '${aliasName}' alias to ${path.basename(rcFile)}`);
1905
+ } else {
1906
+ log(`Alias '${aliasName}' already exists in ${path.basename(rcFile)}`);
1907
+ }
1815
1908
  }
1909
+ log(`After setup, open a new terminal and type: ${aliasName}`);
1816
1910
  console.log("");
1817
1911
 
1818
1912
  // Step 9: Generate CLAUDE.md template
@@ -9,32 +9,39 @@
9
9
  const fs = require("fs");
10
10
  const path = require("path");
11
11
 
12
- const NEXO_HOME = path.join(require("os").homedir(), ".nexo");
12
+ const NEXO_HOME = process.env.NEXO_HOME || path.join(require("os").homedir(), ".nexo");
13
13
  const VERSION_FILE = path.join(NEXO_HOME, "version.json");
14
14
 
15
+ if (process.env.NEXO_SKIP_POSTINSTALL === "1") {
16
+ // Called during rollback — skip migration to avoid loops
17
+ process.exit(0);
18
+ }
19
+
15
20
  if (fs.existsSync(VERSION_FILE)) {
16
21
  // Existing installation — run auto-migration silently
17
- try {
18
- const installed = JSON.parse(fs.readFileSync(VERSION_FILE, "utf8"));
19
- const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf8"));
22
+ const installed = JSON.parse(fs.readFileSync(VERSION_FILE, "utf8"));
23
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf8"));
20
24
 
21
- if (installed.version === pkg.version) {
22
- // Same version, nothing to do
23
- process.exit(0);
24
- }
25
+ if (installed.version === pkg.version) {
26
+ // Same version, nothing to do
27
+ process.exit(0);
28
+ }
25
29
 
26
- console.log(`\n NEXO Brain: upgrading v${installed.version} → v${pkg.version}...`);
30
+ console.log(`\n NEXO Brain: upgrading v${installed.version} → v${pkg.version}...`);
27
31
 
28
- // Run the main installer in --yes mode (non-interactive)
29
- // It will detect the existing version and do migration only
30
- const { execSync } = require("child_process");
32
+ // Run the main installer in --yes mode (non-interactive)
33
+ // It will detect the existing version and do migration only
34
+ // Let errors propagate so npm reports the failure correctly
35
+ const { execSync } = require("child_process");
36
+ try {
31
37
  execSync(`node ${path.join(__dirname, "nexo-brain.js")} --yes`, {
32
38
  stdio: "inherit",
33
- env: { ...process.env, NEXO_POSTINSTALL: "1" }
39
+ env: { ...process.env, NEXO_POSTINSTALL: "1", NEXO_HOME: NEXO_HOME }
34
40
  });
35
41
  } catch (e) {
36
- console.error(` NEXO Brain: migration warning — ${e.message}`);
37
- console.log(" Run 'nexo-brain' manually to complete setup.");
42
+ console.error(`\n NEXO Brain: migration FAILED — ${e.message}`);
43
+ console.error(" Run 'nexo-brain' manually to complete setup.");
44
+ process.exit(1);
38
45
  }
39
46
  } else {
40
47
  // Fresh install — just show instructions
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexo-brain",
3
- "version": "2.3.1",
3
+ "version": "2.4.0",
4
4
  "mcpName": "io.github.wazionapps/nexo",
5
5
  "description": "NEXO — Cognitive co-operator for Claude Code. Memory, emotional intelligence, overnight learning (Deep Sleep), cron management, trust scoring, and adaptive calibration.",
6
6
  "bin": {
@@ -47,7 +47,7 @@
47
47
  "url": "git+https://github.com/wazionapps/nexo.git"
48
48
  },
49
49
  "scripts": {
50
- "postinstall": "node bin/postinstall.js 2>/dev/null || true"
50
+ "postinstall": "node bin/postinstall.js"
51
51
  },
52
52
  "engines": {
53
53
  "node": ">=18"
@@ -96,6 +96,130 @@ def _read_package_version() -> str:
96
96
 
97
97
  # ── Hook sync ────────────────────────────────────────────────────────
98
98
 
99
+ def _requirements_hash() -> str:
100
+ """Return a content hash of requirements.txt, or empty string if missing."""
101
+ import hashlib
102
+ req_file = SRC_DIR / "requirements.txt"
103
+ if req_file.exists():
104
+ return hashlib.sha256(req_file.read_bytes()).hexdigest()
105
+ return ""
106
+
107
+
108
+ def _reinstall_pip_deps() -> bool:
109
+ """Reinstall Python deps from requirements.txt. Returns True on success."""
110
+ req_file = SRC_DIR / "requirements.txt"
111
+ if not req_file.exists():
112
+ return True
113
+ venv_pip = NEXO_HOME / ".venv" / "bin" / "pip"
114
+ if not venv_pip.exists():
115
+ venv_pip = NEXO_HOME / ".venv" / "bin" / "pip3"
116
+ try:
117
+ if venv_pip.exists():
118
+ result = subprocess.run(
119
+ [str(venv_pip), "install", "--quiet", "-r", str(req_file)],
120
+ capture_output=True, text=True, timeout=120,
121
+ )
122
+ else:
123
+ result = subprocess.run(
124
+ [sys.executable, "-m", "pip", "install", "--quiet", "-r", str(req_file), "--break-system-packages"],
125
+ capture_output=True, text=True, timeout=120,
126
+ )
127
+ if result.returncode != 0:
128
+ _log(f"pip install failed (exit {result.returncode}): {result.stderr or result.stdout}")
129
+ return False
130
+ _log("Reinstalled Python dependencies after update")
131
+ return True
132
+ except Exception as e:
133
+ _log(f"pip reinstall failed: {e}")
134
+ return False
135
+
136
+
137
+ def _refresh_installed_manifest():
138
+ """Copy source crons/ to NEXO_HOME/crons/ so catchup & watchdog stay current."""
139
+ try:
140
+ import shutil
141
+ src_crons = SRC_DIR / "crons"
142
+ dst_crons = NEXO_HOME / "crons"
143
+ if src_crons.exists():
144
+ dst_crons.mkdir(parents=True, exist_ok=True)
145
+ for f in src_crons.iterdir():
146
+ if f.is_file():
147
+ shutil.copy2(str(f), str(dst_crons / f.name))
148
+ _log("Refreshed installed crons manifest")
149
+ except Exception as e:
150
+ _log(f"Manifest refresh warning: {e}")
151
+
152
+
153
+ def _sync_crons():
154
+ """Sync cron definitions with manifest after a git pull."""
155
+ try:
156
+ cron_sync_path = SRC_DIR / "crons" / "sync.py"
157
+ if cron_sync_path.exists():
158
+ result = subprocess.run(
159
+ [sys.executable, str(cron_sync_path)],
160
+ capture_output=True, text=True, timeout=30,
161
+ env={**os.environ, "NEXO_HOME": str(NEXO_HOME), "NEXO_CODE": str(SRC_DIR)},
162
+ )
163
+ if result.returncode != 0:
164
+ _log(f"Cron sync failed (exit {result.returncode}): {result.stderr or result.stdout}")
165
+ return # Don't refresh manifest if timers weren't actually updated
166
+ _log("Synced cron definitions with manifest")
167
+ # Refresh the installed manifest only after successful sync
168
+ _refresh_installed_manifest()
169
+ except Exception as e:
170
+ _log(f"Cron sync warning: {e}")
171
+
172
+
173
+ def _backup_dbs() -> str | None:
174
+ """Snapshot all .db files before migration. Returns backup dir or None."""
175
+ import sqlite3
176
+ import time as _time
177
+ timestamp = _time.strftime("%Y-%m-%d-%H%M%S")
178
+ backup_dir = NEXO_HOME / "backups" / f"pre-autoupdate-{timestamp}"
179
+
180
+ db_files = list(DATA_DIR.glob("*.db")) if DATA_DIR.is_dir() else []
181
+ db_files += [f for f in NEXO_HOME.glob("*.db") if f.is_file()]
182
+ src_db = SRC_DIR / "nexo.db"
183
+ if src_db.is_file() and src_db not in db_files:
184
+ db_files.append(src_db)
185
+
186
+ if not db_files:
187
+ return None
188
+
189
+ backup_dir.mkdir(parents=True, exist_ok=True)
190
+ for db_file in db_files:
191
+ try:
192
+ src_conn = sqlite3.connect(str(db_file))
193
+ dst_conn = sqlite3.connect(str(backup_dir / db_file.name))
194
+ src_conn.backup(dst_conn)
195
+ dst_conn.close()
196
+ src_conn.close()
197
+ except Exception as e:
198
+ _log(f"DB backup warning ({db_file.name}): {e}")
199
+ return str(backup_dir)
200
+
201
+
202
+ def _restore_dbs(backup_dir: str):
203
+ """Restore .db files from a backup directory."""
204
+ import sqlite3
205
+ bdir = Path(backup_dir)
206
+ if not bdir.is_dir():
207
+ return
208
+ for db_backup in bdir.glob("*.db"):
209
+ for candidate in [DATA_DIR / db_backup.name, NEXO_HOME / db_backup.name, SRC_DIR / db_backup.name]:
210
+ if candidate.is_file():
211
+ try:
212
+ src_conn = sqlite3.connect(str(db_backup))
213
+ dst_conn = sqlite3.connect(str(candidate))
214
+ src_conn.backup(dst_conn)
215
+ dst_conn.close()
216
+ src_conn.close()
217
+ _log(f"Restored DB: {db_backup.name}")
218
+ except Exception as e:
219
+ _log(f"DB restore warning ({db_backup.name}): {e}")
220
+ break
221
+
222
+
99
223
  def _sync_hooks():
100
224
  """Copy hook scripts from src/hooks/ to NEXO_HOME/hooks/ after a git pull."""
101
225
  import shutil
@@ -152,27 +276,89 @@ def _check_git_updates() -> str | None:
152
276
 
153
277
  # We're behind — safe to fast-forward pull
154
278
  old_version = _read_package_version()
279
+ old_req_hash = _requirements_hash()
280
+
281
+ # Save old HEAD for rollback
282
+ rc, old_head, _ = _git("rev-parse", "HEAD")
283
+ if rc != 0:
284
+ return None
285
+
155
286
  rc, pull_out, pull_err = _git("pull", "--ff-only")
156
287
  if rc != 0:
157
288
  _log(f"git pull --ff-only failed: {pull_err}")
158
289
  return None # Don't break anything
159
290
 
160
291
  new_version = _read_package_version()
292
+ new_req_hash = _requirements_hash()
293
+
294
+ # Backup databases before any changes that might run migrations
295
+ db_backup_dir = _backup_dbs()
296
+
297
+ # Reinstall pip deps if requirements.txt content changed (not just version)
298
+ if old_req_hash != new_req_hash:
299
+ if not _reinstall_pip_deps():
300
+ # pip failed — rollback git + DBs to old HEAD
301
+ _log("pip install failed after pull, rolling back git...")
302
+ _git("reset", "--hard", old_head)
303
+ _reinstall_pip_deps() # restore old deps (best-effort)
304
+ if db_backup_dir:
305
+ _restore_dbs(db_backup_dir)
306
+ return None
307
+
308
+ # Verify the new code can be imported before proceeding
309
+ if not _verify_import():
310
+ _log("Import verification failed after pull, rolling back git...")
311
+ _git("reset", "--hard", old_head)
312
+ if old_req_hash != new_req_hash:
313
+ _reinstall_pip_deps() # restore old deps (best-effort)
314
+ if db_backup_dir:
315
+ _restore_dbs(db_backup_dir)
316
+ return None
161
317
 
162
- # Run DB migrations after pull
163
- _run_db_migrations()
318
+ # Run DB migrations after pull — rollback if they fail
319
+ if not _run_db_migrations():
320
+ _log("DB migration failed after pull, rolling back git + DB...")
321
+ _git("reset", "--hard", old_head)
322
+ if old_req_hash != new_req_hash:
323
+ _reinstall_pip_deps()
324
+ if db_backup_dir:
325
+ _restore_dbs(db_backup_dir)
326
+ return None
164
327
 
165
328
  # Sync hooks to NEXO_HOME (nexo-brain.js copies them on install,
166
329
  # but auto-update via git pull bypasses nexo-brain.js)
167
330
  _sync_hooks()
168
331
 
332
+ # Sync cron definitions with manifest
333
+ _sync_crons()
334
+
169
335
  msg = f"Auto-updated: {old_version} -> {new_version}" if old_version != new_version else f"Auto-updated (v{new_version}, new commits)"
170
336
  _log(msg)
171
337
  return msg
172
338
 
173
339
 
174
- def _run_db_migrations():
175
- """Run NEXO's DB schema migrations (from db._schema) after a pull."""
340
+ def _verify_import() -> bool:
341
+ """Verify that the new code can be imported. Returns True on success."""
342
+ try:
343
+ result = subprocess.run(
344
+ [sys.executable, "-c", "import server"],
345
+ cwd=str(SRC_DIR),
346
+ capture_output=True,
347
+ text=True,
348
+ timeout=15,
349
+ )
350
+ if result.returncode != 0:
351
+ _log(f"Import verification failed: {result.stderr or result.stdout}")
352
+ return False
353
+ return True
354
+ except Exception as e:
355
+ _log(f"Import verification error: {e}")
356
+ return False
357
+
358
+
359
+ def _run_db_migrations() -> bool:
360
+ """Run NEXO's DB schema migrations (from db._schema) after a pull.
361
+ Returns True on success, False on failure."""
176
362
  try:
177
363
  from db._schema import run_migrations
178
364
  from db._core import get_db
@@ -180,8 +366,10 @@ def _run_db_migrations():
180
366
  applied = run_migrations(conn)
181
367
  if applied > 0:
182
368
  _log(f"Applied {applied} DB migration(s)")
369
+ return True
183
370
  except Exception as e:
184
- _log(f"DB migration error (continuing): {e}")
371
+ _log(f"DB migration error: {e}")
372
+ return False
185
373
 
186
374
 
187
375
  # ── npm version check (notify only) ─────────────────────────────────
package/src/crons/sync.py CHANGED
@@ -296,6 +296,9 @@ def sync_linux(dry_run: bool = False):
296
296
  service_path = unit_dir / f"nexo-{cron_id}.service"
297
297
  timer_path = unit_dir / f"nexo-{cron_id}.timer"
298
298
 
299
+ stdout_log = LOG_DIR / f"{cron_id}-stdout.log"
300
+ stderr_log = LOG_DIR / f"{cron_id}-stderr.log"
301
+
299
302
  service_content = f"""[Unit]
300
303
  Description=NEXO: {cron.get('description', cron_id)}
301
304
 
@@ -305,6 +308,8 @@ ExecStart={exec_cmd}
305
308
  Environment=NEXO_HOME={NEXO_HOME}
306
309
  Environment=NEXO_CODE={NEXO_CODE}
307
310
  Environment=HOME={Path.home()}
311
+ StandardOutput=append:{stdout_log}
312
+ StandardError=append:{stderr_log}
308
313
  """
309
314
 
310
315
  if cron.get("run_at_load"):
@@ -616,13 +616,20 @@ async def api_ops_execute(fid: str):
616
616
  if not row:
617
617
  return JSONResponse({"error": f"Followup {fid} not found"}, status_code=404)
618
618
  item = dict(row)
619
- description = item["description"].replace('"', '\\"').replace("'", "\\'")
620
619
  if platform.system() != "Darwin":
621
620
  return JSONResponse(
622
621
  {"error": "This operation requires macOS (uses osascript to open Terminal)"},
623
622
  status_code=501,
624
623
  )
625
- script = f'tell application "Terminal" to do script "claude \\"NEXO: execute followup #{fid} — {description}\\""'
624
+ # Security: avoid interpolating user-controlled data into shell commands.
625
+ # Write the followup ID to a temp file and pass a safe, fixed command to osascript.
626
+ import tempfile
627
+ tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".txt", prefix="nexo-followup-", delete=False)
628
+ tmp.write(fid)
629
+ tmp.close()
630
+ # The claude command reads the followup ID from the temp file — no shell interpolation of description
631
+ claude_cmd = f'claude \\"NEXO: execute followup from file $(cat {tmp.name})\\"'
632
+ script = f'tell application "Terminal" to do script "{claude_cmd}"'
626
633
  subprocess.Popen(["osascript", "-e", script])
627
634
  return {"success": True, "followup_id": fid}
628
635