nexo-brain 2.3.1 → 2.3.2
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/bin/nexo-brain.js +92 -9
- package/bin/postinstall.js +22 -15
- package/package.json +2 -2
- package/src/auto_update.py +193 -5
- package/src/crons/sync.py +5 -0
- package/src/db/_schema.py +11 -1
- package/src/hooks/capture-tool-logs.sh +23 -6
- package/src/hooks/session-start.sh +4 -3
- package/src/plugins/update.py +376 -26
- package/src/scripts/nexo-catchup.py +29 -4
- package/src/scripts/nexo-daily-self-audit.py +21 -1
- package/src/scripts/nexo-evolution-run.py +21 -1
- package/src/scripts/nexo-postmortem-consolidator.py +34 -9
- package/src/scripts/nexo-sleep.py +32 -10
- package/src/scripts/nexo-synthesis.py +29 -9
- package/src/scripts/nexo-update.sh +109 -7
- package/src/scripts/nexo-watchdog.sh +103 -47
- package/src/server.py +65 -1
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 =
|
|
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
|
-
//
|
|
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 === "
|
|
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")
|
|
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,7 +1870,12 @@ ${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
|
|
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
|
package/bin/postinstall.js
CHANGED
|
@@ -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
|
-
|
|
18
|
-
|
|
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
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
+
if (installed.version === pkg.version) {
|
|
26
|
+
// Same version, nothing to do
|
|
27
|
+
process.exit(0);
|
|
28
|
+
}
|
|
25
29
|
|
|
26
|
-
|
|
30
|
+
console.log(`\n NEXO Brain: upgrading v${installed.version} → v${pkg.version}...`);
|
|
27
31
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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(
|
|
37
|
-
console.
|
|
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.
|
|
3
|
+
"version": "2.3.2",
|
|
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
|
|
50
|
+
"postinstall": "node bin/postinstall.js"
|
|
51
51
|
},
|
|
52
52
|
"engines": {
|
|
53
53
|
"node": ">=18"
|
package/src/auto_update.py
CHANGED
|
@@ -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
|
|
175
|
-
"""
|
|
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
|
|
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"):
|
package/src/db/_schema.py
CHANGED
|
@@ -399,6 +399,7 @@ def run_migrations(conn=None):
|
|
|
399
399
|
|
|
400
400
|
applied = {r[0] for r in conn.execute("SELECT version FROM schema_migrations").fetchall()}
|
|
401
401
|
|
|
402
|
+
failed = []
|
|
402
403
|
for version, name, fn in MIGRATIONS:
|
|
403
404
|
if version not in applied:
|
|
404
405
|
try:
|
|
@@ -409,9 +410,18 @@ def run_migrations(conn=None):
|
|
|
409
410
|
)
|
|
410
411
|
conn.commit()
|
|
411
412
|
except Exception as e:
|
|
412
|
-
|
|
413
|
+
conn.rollback()
|
|
413
414
|
import sys
|
|
414
415
|
print(f"[MIGRATION] v{version} ({name}) failed: {e}", file=sys.stderr)
|
|
416
|
+
failed.append((version, name, str(e)))
|
|
417
|
+
# Stop on first failure — don't run subsequent migrations
|
|
418
|
+
# against a potentially inconsistent schema
|
|
419
|
+
break
|
|
420
|
+
|
|
421
|
+
if failed:
|
|
422
|
+
raise RuntimeError(
|
|
423
|
+
f"Migration failed: v{failed[0][0]} ({failed[0][1]}): {failed[0][2]}"
|
|
424
|
+
)
|
|
415
425
|
|
|
416
426
|
return len(MIGRATIONS) - len(applied)
|
|
417
427
|
|
|
@@ -41,8 +41,12 @@ record = {
|
|
|
41
41
|
print(json.dumps(record))
|
|
42
42
|
" >> "$LOG_FILE" 2>/dev/null
|
|
43
43
|
|
|
44
|
-
# ── Layer 1: Auto-diary every 10 tool calls
|
|
45
|
-
|
|
44
|
+
# ── Layer 1: Auto-diary every 10 tool calls (session-scoped) ─────────
|
|
45
|
+
# Extract session_id for per-session counters (prevents cross-terminal contamination)
|
|
46
|
+
SESSION_ID=$(echo "$INPUT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('session_id','global'))" 2>/dev/null || echo "global")
|
|
47
|
+
COUNTER_DIR="$NEXO_HOME/operations/counters"
|
|
48
|
+
mkdir -p "$COUNTER_DIR"
|
|
49
|
+
COUNTER_FILE="$COUNTER_DIR/.tool-call-count-${SESSION_ID}"
|
|
46
50
|
NEXO_DB="$NEXO_HOME/data/nexo.db"
|
|
47
51
|
|
|
48
52
|
# Increment counter (atomic: read+write in one step)
|
|
@@ -86,12 +90,25 @@ if not entries:
|
|
|
86
90
|
|
|
87
91
|
tools_summary = ', '.join(entries[-10:])
|
|
88
92
|
|
|
89
|
-
# Get
|
|
93
|
+
# Get session by claude session_id (scoped), fallback to most recent
|
|
94
|
+
session_id = '$SESSION_ID'
|
|
90
95
|
conn = sqlite3.connect(db_path, timeout=2)
|
|
91
96
|
conn.row_factory = sqlite3.Row
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
97
|
+
|
|
98
|
+
# Try to find NEXO SID mapped to this claude session_id
|
|
99
|
+
row = None
|
|
100
|
+
if session_id and session_id != 'global':
|
|
101
|
+
row = conn.execute(
|
|
102
|
+
'SELECT sid, task FROM sessions WHERE claude_session_id = ? LIMIT 1',
|
|
103
|
+
(session_id,)
|
|
104
|
+
).fetchone()
|
|
105
|
+
|
|
106
|
+
# Fallback: most recent active session
|
|
107
|
+
if not row:
|
|
108
|
+
row = conn.execute(
|
|
109
|
+
'SELECT sid, task FROM sessions ORDER BY last_update_epoch DESC LIMIT 1'
|
|
110
|
+
).fetchone()
|
|
111
|
+
|
|
95
112
|
if not row:
|
|
96
113
|
conn.close()
|
|
97
114
|
sys.exit(0)
|
|
@@ -92,10 +92,11 @@ try:
|
|
|
92
92
|
|
|
93
93
|
try:
|
|
94
94
|
rows = db.execute(
|
|
95
|
-
'SELECT sid, task,
|
|
96
|
-
'WHERE
|
|
95
|
+
'SELECT sid, task, started_epoch FROM sessions '
|
|
96
|
+
'WHERE (strftime(\"%s\",\"now\") - last_update_epoch) < 900'
|
|
97
97
|
).fetchall()
|
|
98
|
-
|
|
98
|
+
from datetime import datetime as _dt
|
|
99
|
+
sessions = [{'sid': r['sid'], 'task': r['task'], 'started': _dt.fromtimestamp(r['started_epoch']).strftime('%Y-%m-%d %H:%M') if r['started_epoch'] else '?'} for r in rows]
|
|
99
100
|
except Exception:
|
|
100
101
|
pass
|
|
101
102
|
|