Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(machina): Phase C -- migrate `pnpm run start` and `pnpm run dev`
trohitg46c3bb16b972
diff --git a/machina/cli.py b/machina/cli.pyindex 1d4968d3..f13131d8 100644--- a/machina/cli.py+++ b/machina/cli.py@@ -10,6 +10,8 @@ import typerfrom machina.commands.build import build_commandfrom machina.commands.clean import clean_command+from machina.commands.dev import dev_command+from machina.commands.start import start_commandfrom machina.commands.stop import stop_command@@ -26,6 +28,12 @@ def _root() -> None:"""Marks the Typer app as a multi-command group."""+app.command("start", help="Start all services in production mode (static client + uvicorn + temporal).")(+ start_command+)+app.command("dev", help="Start all services in dev mode (Vite HMR + uvicorn + temporal).")(+ dev_command+)app.command("stop", help="Stop all MachinaOS services and free configured ports.")(stop_command)diff --git a/machina/commands/dev.py b/machina/commands/dev.pynew file mode 100644index 00000000..795d8824--- /dev/null+++ b/machina/commands/dev.py@@ -0,0 +1,128 @@+"""``machina dev`` -- replaces ``scripts/dev.js``.++Development launcher: validates the build, frees ports, clears the+Vite dep cache (fixes "Outdated Optimize Dep" errors), then spawns+Vite + uvicorn + temporal-server under ``Manager.run()``.++uvicorn ``--reload``-style restarts (exit code 1) used to cascade-kill+the frontend under ``concurrently --kill-others``. Our supervisor+treats each service independently, so a backend reload doesn't touch+the Vite process.+"""++from __future__ import annotations++import asyncio+import os+import shutil+from pathlib import Path++import typer++from machina.colors import console+from machina.config import load_config+from machina.platform_ import platform_name, project_root+from machina.ports import kill_port+from machina.supervisor import Manager, ServiceSpec+++def _validate_build(root: Path) -> None:+ if not (root / "node_modules").exists() or not (root / "server" / ".venv").exists():+ console.print('[red]Error: Project not built. Run "machina build" first.[/]')+ raise typer.Exit(code=1)+++def _has_vite(root: Path) -> bool:+ return (+ (root / "node_modules" / "vite").exists()+ or (root / "client" / "node_modules" / "vite").exists()+ )+++def _clear_vite_cache(root: Path) -> None:+ cache = root / "client" / "node_modules" / ".vite"+ if not cache.exists():+ return+ try:+ shutil.rmtree(cache)+ console.print("Cleared Vite cache")+ except OSError as exc:+ console.print(f"[yellow]Warning: Could not clear Vite cache: {exc}[/]")+++def _build_specs(root: Path, cfg, *, daemon: bool, use_vite: bool) -> list[ServiceSpec]:+ static_client = root / "scripts" / "serve-client.js"+ server_dir = root / "server"++ if use_vite:+ client_spec = ServiceSpec(+ name="client",+ argv=["pnpm", "run", "client:start"],+ cwd=root,+ ready_port=cfg.ports.client,+ ready_timeout=60.0,+ )+ else:+ client_spec = ServiceSpec(+ name="client",+ argv=["node", str(static_client)],+ cwd=root,+ ready_port=cfg.ports.client,+ )++ backend_host = "0.0.0.0" if daemon else "127.0.0.1"+ server_spec = ServiceSpec(+ name="server",+ argv=[+ "uv", "run", "uvicorn", "main:app",+ "--host", backend_host,+ "--port", str(cfg.ports.backend),+ "--log-level", "warning",+ ],+ cwd=server_dir,+ ready_port=cfg.ports.backend,+ )++ return [+ client_spec,+ server_spec,+ ServiceSpec(+ name="temporal",+ argv=["temporal-server", "api"],+ cwd=root,+ ready_port=cfg.ports.temporal,+ ),+ ]+++def dev_command(+ daemon: bool = typer.Option(+ False, "--daemon", help="Bind backend to 0.0.0.0 instead of 127.0.0.1.",+ ),+) -> None:+ root = project_root()+ cfg = load_config()+ os.environ.setdefault("PYTHONUTF8", "1")++ _validate_build(root)++ console.print("\n[bold]=== MachinaOS Starting ===[/]\n")+ console.print(f"Platform: {platform_name()}")+ console.print(f"Mode: {'Daemon (uvicorn)' if daemon else 'Development (uvicorn)'}")+ console.print(f"Ports: {', '.join(str(p) for p in cfg.ports.all())}")++ console.print("Freeing ports...")+ for port in cfg.ports.all():+ kill_port(port)++ _clear_vite_cache(root)++ use_vite = _has_vite(root)+ console.print(f"Client: {'Vite dev server' if use_vite else 'Static server'}")+ console.print()++ manager = Manager()+ manager.add_all(_build_specs(root, cfg, daemon=daemon, use_vite=use_vite))+ rc = asyncio.run(manager.run())+ if rc != 0:+ raise typer.Exit(code=rc)diff --git a/machina/commands/start.py b/machina/commands/start.pynew file mode 100644index 00000000..83a375bd--- /dev/null+++ b/machina/commands/start.py@@ -0,0 +1,181 @@+"""``machina start`` -- replaces ``scripts/start.js``.++Production launcher: validates the build exists, runs the sqlalchemy+preflight probe (Windows Defender workaround), frees configured ports,+then spawns the static client + uvicorn + temporal-server (unless+already running) under ``Manager.run()``.++WhatsApp's edgymeow Go binary is supervised by the Python backend+(``server/nodes/whatsapp/_runtime.py``) so it does NOT appear here.+"""++from __future__ import annotations++import asyncio+import json+import os+import subprocess+import sys+import time+from pathlib import Path++import typer++from machina.colors import console+from machina.config import load_config+from machina.platform_ import IS_WINDOWS, IS_WSL, platform_name, project_root+from machina.ports import kill_port+from machina.supervisor import Manager, RestartPolicy, ServiceSpec+++def _venv_python(root: Path) -> Path | None:+ for candidate in (+ root / "server" / ".venv" / "Scripts" / "python.exe",+ root / "server" / ".venv" / "bin" / "python",+ ):+ if candidate.exists():+ return candidate+ return None+++def _sqlalchemy_preflight(root: Path) -> None:+ """Time-boxed sqlalchemy import probe.++ On Windows, Defender's minifilter driver (MpFilter.sys) sometimes+ caches stale "pending scan" entries that block .pyd LoadLibrary+ calls even after exclusions are added. Catching it here gives a+ clear remediation message instead of letting uvicorn hang silently.+ See ``docs-internal/errors.md`` #1 / #1a.+ """+ py = _venv_python(root)+ if py is None:+ return+ started = time.monotonic()+ try:+ subprocess.run(+ [str(py), "-c", "import sqlalchemy"],+ timeout=15,+ check=True,+ capture_output=True,+ )+ except (subprocess.TimeoutExpired, subprocess.CalledProcessError):+ elapsed = time.monotonic() - started+ console.print(f"[red]Error: Python venv health check failed ({elapsed:.1f}s).[/]")+ console.print(" sqlalchemy import hung or crashed.")+ console.print(" Likely cause: Windows Defender scan cache or stale kernel state.")+ console.print(" Fix options:")+ console.print(" 1. Restart-Service WinDefend (admin PowerShell)")+ console.print(" 2. Reboot the machine")+ console.print(f" 3. Add {root / 'server' / '.venv'} to Defender exclusions")+ console.print(" See docs-internal/errors.md #1 / #1a for details.")+ raise typer.Exit(code=1)+ elapsed = time.monotonic() - started+ if elapsed > 5.0:+ console.print(+ f"[yellow]Warning: sqlalchemy import took {elapsed:.1f}s "+ "(expected <1s). See docs-internal/errors.md #1.[/]"+ )+++def _temporal_running() -> bool:+ """Check whether ``temporal-server`` is already up via its CLI."""+ try:+ out = subprocess.run(+ ["temporal-server", "status"],+ capture_output=True,+ text=True,+ timeout=5,+ )+ return any(token in out.stdout for token in ("running", "UP", "up"))+ except (FileNotFoundError, subprocess.TimeoutExpired):+ return False+++def _validate_build(root: Path) -> None:+ if not (root / "node_modules").exists() or not (root / "server" / ".venv").exists():+ console.print('[red]Error: Project not built. Run "machina build" first.[/]')+ raise typer.Exit(code=1)+ if not (root / "client" / "dist" / "index.html").exists():+ console.print('[red]Error: Client not built. Run "machina build" first.[/]')+ raise typer.Exit(code=1)+++def _read_version(root: Path) -> str:+ try:+ pkg = json.loads((root / "package.json").read_text(encoding="utf-8"))+ return pkg.get("version", "0.0.0")+ except (OSError, json.JSONDecodeError):+ return "0.0.0"+++def _build_specs(root: Path, cfg, *, temporal_running: bool) -> list[ServiceSpec]:+ static_client = root / "scripts" / "serve-client.js"+ server_dir = root / "server"++ # Match the existing behaviour: production uses python:start+ # (bind 127.0.0.1) on Windows/WSL, python:daemon (bind 0.0.0.0)+ # on POSIX.+ backend_host = "127.0.0.1" if (IS_WINDOWS or IS_WSL) else "0.0.0.0"+ backend_argv = [+ "uv", "run", "uvicorn", "main:app",+ "--host", backend_host,+ "--port", str(cfg.ports.backend),+ "--log-level", "warning",+ ]++ specs: list[ServiceSpec] = [+ ServiceSpec(+ name="client",+ argv=["node", str(static_client)],+ cwd=root,+ ready_port=cfg.ports.client,+ ),+ ServiceSpec(+ name="server",+ argv=backend_argv,+ cwd=server_dir,+ ready_port=cfg.ports.backend,+ ),+ ]+ if not temporal_running:+ specs.append(+ ServiceSpec(+ name="temporal",+ argv=["temporal-server", "api"],+ cwd=root,+ ready_port=cfg.ports.temporal,+ )+ )+ return specs+++def start_command() -> None:+ root = project_root()+ cfg = load_config()+ os.environ.setdefault("PYTHONUTF8", "1")++ _validate_build(root)+ _sqlalchemy_preflight(root)++ temporal_running = _temporal_running()+ if temporal_running:+ console.print("[dim]Temporal already running, skipping[/]")++ console.print("Freeing ports...")+ for port in cfg.ports.all():+ kill_port(port)+ console.print("Ports ready")++ version = _read_version(root)+ console.print()+ console.print(f" [bold]MachinaOS[/] v{version}")+ console.print(f" Frontend: http://localhost:{cfg.ports.client}")+ console.print(f" Backend: http://localhost:{cfg.ports.backend}")+ console.print(f" Platform: {platform_name()}")+ console.print()++ manager = Manager()+ manager.add_all(_build_specs(root, cfg, temporal_running=temporal_running))+ rc = asyncio.run(manager.run())+ if rc != 0:+ raise typer.Exit(code=rc)diff --git a/machina/tests/test_dev.py b/machina/tests/test_dev.pynew file mode 100644index 00000000..e54dc5a6--- /dev/null+++ b/machina/tests/test_dev.py@@ -0,0 +1,77 @@+"""Smoke tests for ``machina.commands.dev``."""++from __future__ import annotations++from pathlib import Path++from machina.commands import dev+from machina.config import Config, Ports+++def _cfg() -> Config:+ return Config(+ raw={},+ ports=Ports(client=3000, backend=3010, whatsapp=9400, nodejs=3020, temporal=7233),+ )+++def test_has_vite_false_when_missing(tmp_path: Path):+ assert dev._has_vite(tmp_path) is False+++def test_has_vite_true_when_in_root_node_modules(tmp_path: Path):+ (tmp_path / "node_modules" / "vite").mkdir(parents=True)+ assert dev._has_vite(tmp_path) is True+++def test_has_vite_true_when_in_client_node_modules(tmp_path: Path):+ (tmp_path / "client" / "node_modules" / "vite").mkdir(parents=True)+ assert dev._has_vite(tmp_path) is True+++def test_clear_vite_cache_no_op_when_missing(tmp_path: Path):+ # Just shouldn't raise.+ dev._clear_vite_cache(tmp_path)+++def test_clear_vite_cache_removes_present(tmp_path: Path):+ cache = tmp_path / "client" / "node_modules" / ".vite"+ cache.mkdir(parents=True)+ (cache / "deps.json").write_text("{}")+ dev._clear_vite_cache(tmp_path)+ assert not cache.exists()+++def test_build_specs_dev_uses_vite_when_available(tmp_path: Path):+ cfg = _cfg()+ specs = dev._build_specs(tmp_path, cfg, daemon=False, use_vite=True)+ by_name = {s.name: s for s in specs}+ assert by_name["client"].argv[:3] == ["pnpm", "run", "client:start"]+++def test_build_specs_dev_falls_back_to_static_without_vite(tmp_path: Path):+ cfg = _cfg()+ specs = dev._build_specs(tmp_path, cfg, daemon=False, use_vite=False)+ by_name = {s.name: s for s in specs}+ assert by_name["client"].argv[0] == "node"+ assert "serve-client.js" in by_name["client"].argv[1]+++def test_build_specs_daemon_binds_0_0_0_0(tmp_path: Path):+ cfg = _cfg()+ specs = dev._build_specs(tmp_path, cfg, daemon=True, use_vite=True)+ server_argv = next(s for s in specs if s.name == "server").argv+ assert "0.0.0.0" in server_argv+++def test_build_specs_non_daemon_binds_127_0_0_1(tmp_path: Path):+ cfg = _cfg()+ specs = dev._build_specs(tmp_path, cfg, daemon=False, use_vite=True)+ server_argv = next(s for s in specs if s.name == "server").argv+ assert "127.0.0.1" in server_argv+++def test_build_specs_dev_always_includes_temporal(tmp_path: Path):+ cfg = _cfg()+ specs = dev._build_specs(tmp_path, cfg, daemon=False, use_vite=True)+ assert any(s.name == "temporal" for s in specs)diff --git a/machina/tests/test_start.py b/machina/tests/test_start.pynew file mode 100644index 00000000..1cdd5ea2--- /dev/null+++ b/machina/tests/test_start.py@@ -0,0 +1,60 @@+"""Smoke tests for ``machina.commands.start``."""++from __future__ import annotations++from pathlib import Path+from unittest.mock import patch++from machina.commands import start+from machina.config import Config, Ports+++def _cfg() -> Config:+ return Config(+ raw={},+ ports=Ports(client=3000, backend=3010, whatsapp=9400, nodejs=3020, temporal=7233),+ )+++def test_venv_python_returns_none_when_missing(tmp_path: Path):+ assert start._venv_python(tmp_path) is None+++def test_venv_python_finds_windows_layout(tmp_path: Path):+ win_py = tmp_path / "server" / ".venv" / "Scripts" / "python.exe"+ win_py.parent.mkdir(parents=True)+ win_py.write_text("")+ assert start._venv_python(tmp_path) == win_py+++def test_venv_python_finds_posix_layout(tmp_path: Path):+ posix_py = tmp_path / "server" / ".venv" / "bin" / "python"+ posix_py.parent.mkdir(parents=True)+ posix_py.write_text("")+ assert start._venv_python(tmp_path) == posix_py+++def test_temporal_running_false_when_cli_missing():+ with patch.object(start.subprocess, "run", side_effect=FileNotFoundError):+ assert start._temporal_running() is False+++def test_build_specs_skips_temporal_when_already_running(tmp_path: Path):+ cfg = _cfg()+ specs = start._build_specs(tmp_path, cfg, temporal_running=True)+ assert {s.name for s in specs} == {"client", "server"}+++def test_build_specs_includes_temporal_when_not_running(tmp_path: Path):+ cfg = _cfg()+ specs = start._build_specs(tmp_path, cfg, temporal_running=False)+ assert {s.name for s in specs} == {"client", "server", "temporal"}+++def test_build_specs_assigns_ready_ports(tmp_path: Path):+ cfg = _cfg()+ specs = start._build_specs(tmp_path, cfg, temporal_running=False)+ by_name = {s.name: s for s in specs}+ assert by_name["client"].ready_port == 3000+ assert by_name["server"].ready_port == 3010+ assert by_name["temporal"].ready_port == 7233diff --git a/package.json b/package.jsonindex 4f9a51fb..0bf1571e 100644--- a/package.json+++ b/package.json@@ -60,9 +60,9 @@"client"],"scripts": {- "start": "node scripts/start.js",- "dev": "node scripts/dev.js",- "start:temporal": "cross-env TEMPORAL_ENABLED=true node scripts/start.js",+ "start": "python -m machina start",+ "dev": "python -m machina dev",+ "start:temporal": "cross-env TEMPORAL_ENABLED=true python -m machina start","client:start": "cd client && npm run start","python:start": "cd server && uv run uvicorn main:app --host 127.0.0.1 --port 3010 --log-level warning","python:daemon": "cd server && uv run uvicorn main:app --host 0.0.0.0 --port 3010 --log-level warning",diff --git a/scripts/dev.js b/scripts/dev.jsdeleted file mode 100644index 71762e7e..00000000--- a/scripts/dev.js+++ /dev/null@@ -1,147 +0,0 @@-#!/usr/bin/env node-/**- * Development server for MachinaOS.- * Vite HMR, uvicorn hot-reload, full log output.- * Usage: machina dev [--daemon]- *- * WhatsApp's edgymeow Go binary is supervised by the Python backend- * (see server/nodes/whatsapp/_runtime.py) — no separate npm script.- */-import { spawn } from 'child_process';-import { existsSync, rmSync } from 'fs';-import { resolve } from 'path';-import {- ROOT,- getPlatformName,- loadEnvConfig,- ensureEnvFile,- killPort,- createLogger,- waitForTcpPort,- installPerfMeasureLogger,-} from './utils.js';--const START_TIME = Date.now();-const log = createLogger(START_TIME);--// Install the perf observer once: every performance.measure entry from-// this process (including the ones emitted by waitForTcpPort) is logged-// as a structured "[perf] <name> <ms>" line. Standard Node lib only.-installPerfMeasureLogger(log);--// Parse command line arguments-const args = process.argv.slice(2);-const isDaemonMode = args.includes('--daemon');--async function main() {- // Check if build has been run- const rootNodeModules = resolve(ROOT, 'node_modules');- const pythonVenv = resolve(ROOT, 'server', '.venv');- if (!existsSync(rootNodeModules) || !existsSync(pythonVenv)) {- console.error('\nError: Project not built. Run "npm run build" first.\n');- process.exit(1);- }-- const config = loadEnvConfig();- process.env.PYTHONUTF8 = '1';-- console.log('\n=== MachinaOS Starting ===\n');- log(`Platform: ${getPlatformName()}`);- log(`Mode: ${isDaemonMode ? 'Daemon (uvicorn)' : 'Development (uvicorn)'}`);- log(`Ports: ${config.allPorts.join(', ')}`);- log(`Temporal: enabled`);-- // Create .env if not exists- if (ensureEnvFile()) {- log('Ensured .env file exists');- }-- // Free ports- log('Freeing ports...');- for (const port of config.allPorts) {- const result = await killPort(port);- if (result.killed.length > 0) {- log(` Port ${port}: ${result.portFree ? 'Freed' : 'Warning - could not free'} (PIDs: ${result.killed.join(', ')})`);- } else {- log(` Port ${port}: Already free`);- }- }-- // Clear Vite dependency cache to prevent "Outdated Optimize Dep" errors- const viteCachePath = resolve(ROOT, 'client', 'node_modules', '.vite');- if (existsSync(viteCachePath)) {- try {- rmSync(viteCachePath, { recursive: true, force: true });- log('Cleared Vite cache');- } catch (err) {- log(`Warning: Could not clear Vite cache: ${err.message}`);- }- }-- // Start services- log('Spawning services...');-- const clientDist = resolve(ROOT, 'client', 'dist', 'index.html');- const hasVite = existsSync(resolve(ROOT, 'node_modules', 'vite'))- || existsSync(resolve(ROOT, 'client', 'node_modules', 'vite'));- const isProduction = existsSync(clientDist) && !hasVite;- log(`Client: ${isProduction ? 'Static server' : 'Vite dev server'}`);-- const services = [];- if (isProduction) {- services.push(`"node ${resolve(ROOT, 'scripts', 'serve-client.js').replace(/\\/g, '/')}"`);- } else {- services.push('"pnpm run client:start"');- }- services.push(isDaemonMode ? '"pnpm run python:daemon"' : '"pnpm run python:start"');- services.push('"pnpm run temporal:start"');- // Worker runs embedded in the backend (main.py TemporalWorkerManager)-- // No --kill-others: uvicorn hot-reloads (exit code 1) would cascade-kill frontend- const proc = spawn('pnpm', ['exec', 'concurrently', '--raw', ...services], {- cwd: ROOT,- stdio: ['inherit', 'pipe', 'pipe'],- shell: true,- env: { ...process.env, FORCE_COLOR: '1' }- });-- // Pass-through stdout/stderr so each service's logs reach the terminal.- proc.stdout.on('data', (data) => process.stdout.write(data));- proc.stderr.on('data', (data) => process.stderr.write(data));-- // Detect ready state by probing TCP ports (the same primitive used by- // the wait-on package, Vercel CLI dev scripts, etc.). Replaces the- // previous stdout regex-matching, which trailed actual readiness by- // ~2s due to line-buffered stdout flush + Temporal worker startup- // gating the "Worker started" log line.- const readyTargets = [- { name: 'Client', port: config.clientPort },- { name: 'Backend', port: config.backendPort },- ];- readyTargets.push({ name: 'Temporal', port: config.ports.temporal });-- Promise.all(- readyTargets.map(async ({ name, port }) => {- // Pass `name` so the perf observer emits ``tcp.wait.<service>``- // entries instead of port-numbered ones. Timing comes from the- // observer (single source), not inline scaffolding here.- const ok = await waitForTcpPort(port, { name: name.toLowerCase() });- log(ok ? `${name} ready (port ${port})` : `${name} did not become ready (port ${port})`);- return ok;- })- ).then((results) => {- if (results.every(Boolean)) {- log(`All services ready -- http://localhost:${config.clientPort}`);- console.log('');- }- });-- process.on('SIGINT', () => proc.kill('SIGINT'));- process.on('SIGTERM', () => proc.kill('SIGTERM'));- proc.on('close', (code) => {- console.log('\nServices stopped.');- process.exit(code || 0);- });-}--main().catch(console.error);diff --git a/scripts/postinstall.js b/scripts/postinstall.jsindex e610b2b1..e3937a0d 100755--- a/scripts/postinstall.js+++ b/scripts/postinstall.js@@ -19,8 +19,6 @@ function fixPermissions() {const files = [resolve(ROOT, 'bin/cli.js'),- resolve(ROOT, 'scripts/start.js'),- resolve(ROOT, 'scripts/dev.js'),resolve(ROOT, 'scripts/install.js'),resolve(ROOT, 'install.sh'),];diff --git a/scripts/start.js b/scripts/start.jsdeleted file mode 100755index dd38d8d7..00000000--- a/scripts/start.js+++ /dev/null@@ -1,218 +0,0 @@-#!/usr/bin/env node-/**- * Production start script for MachinaOS.- * Clean output by default, --verbose for full logs.- * Usage: machina start [--verbose|-v]- *- * WhatsApp's edgymeow Go binary is supervised by the Python backend- * (see server/nodes/whatsapp/_runtime.py) — no separate npm script.- */-import { spawn, execSync } from 'child_process';-import { existsSync, readFileSync } from 'fs';-import { resolve } from 'path';-import {- ROOT,- isWindows,- isWSL,- loadEnvConfig,- ensureEnvFile,- killPort,- createLogger,- waitForTcpPort,- installPerfMeasureLogger,-} from './utils.js';--const START_TIME = Date.now();-const log = createLogger(START_TIME);--// One PerformanceObserver per process — every performance.measure entry-// (including those from waitForTcpPort) is logged as a structured-// "[perf] <name> <ms>" line. Standard Node lib only.-installPerfMeasureLogger(log);--const args = process.argv.slice(2);-const isVerbose = args.includes('--verbose') || args.includes('-v');--function getVersion() {- try {- const pkg = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf-8'));- return pkg.version || '0.0.0';- } catch {- return '0.0.0';- }-}--async function main() {- // Validate build- if (!existsSync(resolve(ROOT, 'node_modules')) || !existsSync(resolve(ROOT, 'server', '.venv'))) {- console.error('Error: Project not built. Run "machina build" first.');- process.exit(1);- }- if (!existsSync(resolve(ROOT, 'client', 'dist', 'index.html'))) {- console.error('Error: Client not built. Run "machina build" first.');- process.exit(1);- }-- // Preflight: time-boxed sqlalchemy import probe.- // On Windows, Defender's minifilter driver (MpFilter.sys) can cache stale- // "pending scan" entries that block .pyd LoadLibrary calls even after- // adding exclusions. See docs-internal/errors.md #1 and #1a.- const pyExe = resolve(ROOT, 'server', '.venv', 'Scripts', isWindows ? 'python.exe' : 'python');- const pyFallback = resolve(ROOT, 'server', '.venv', 'bin', 'python');- const py = existsSync(pyExe) ? pyExe : pyFallback;- if (existsSync(py)) {- const probeStart = Date.now();- try {- execSync(`"${py}" -c "import sqlalchemy"`, { timeout: 15000, stdio: 'pipe' });- const elapsed = Date.now() - probeStart;- if (elapsed > 5000) {- console.warn(`Warning: sqlalchemy import took ${(elapsed / 1000).toFixed(1)}s (expected <1s).`);- console.warn(' See docs-internal/errors.md #1 for Windows Defender remediation.');- }- } catch (e) {- const elapsed = Date.now() - probeStart;- console.error(`Error: Python venv health check failed (${(elapsed / 1000).toFixed(1)}s).`);- console.error(' sqlalchemy import hung or crashed.');- console.error(' Likely cause: Windows Defender scan cache or stale kernel state.');- console.error(' Fix options:');- console.error(' 1. Restart-Service WinDefend (admin PowerShell)');- console.error(' 2. Reboot the machine');- console.error(' 3. Add D:\\...\\server\\.venv to Defender exclusions');- console.error(' See docs-internal/errors.md #1 and #1a for details.');- process.exit(1);- }- }-- const config = loadEnvConfig();- process.env.PYTHONUTF8 = '1';- ensureEnvFile();-- // Check if Temporal is already running via CLI- // (temporal api exits immediately if already up, which triggers- // --kill-others and kills all services)- let temporalRunning = false;- try {- const status = execSync('temporal status', { encoding: 'utf-8', timeout: 5000, stdio: 'pipe' });- temporalRunning = /running|UP/i.test(status);- } catch {- temporalRunning = false;- }-- if (temporalRunning) {- log('Temporal already running, skipping');- }-- // Free app ports- log('Freeing ports...');- for (const port of config.allPorts) {- await killPort(port);- }- log('Ports ready');-- // Services: static client, backend (uvicorn), temporal.- // WhatsApp's edgymeow Go binary is spawned lazily by the Python backend- // (see server/nodes/whatsapp/_runtime.py) so the session DB lives under- // data_dir. Disable via WHATSAPP_RUNTIME_ENABLED=false in .env.- const services = [];- services.push(`"node ${resolve(ROOT, 'scripts', 'serve-client.js').replace(/\\/g, '/')}"`);- services.push((isWindows || isWSL) ? '"pnpm run python:start"' : '"pnpm run python:daemon"');- if (!temporalRunning) services.push('"pnpm run temporal:start"');- // Worker runs embedded in the backend (main.py TemporalWorkerManager)-- // Ready-detection via TCP port probes (same primitive used by the- // wait-on package and most production multi-service launchers).- // Replaces stdout regex-grep, which trailed actual readiness by ~2s- // due to line-buffered stdout flush. See scripts/utils.js:waitForTcpPort.- const readyTargets = [- { name: 'Client', port: config.clientPort },- { name: 'Backend', port: config.backendPort },- ];- if (!temporalRunning) {- readyTargets.push({ name: 'Temporal', port: config.ports.temporal });- }-- function startReadyProbes() {- Promise.all(- readyTargets.map(async ({ name, port }) => {- // Pass `name` so the perf observer emits ``tcp.wait.<service>``- // entries instead of port-numbered ones.- const ok = await waitForTcpPort(port, { name: name.toLowerCase() });- log(ok ? `${name} ready (port ${port})` : `${name} did not become ready (port ${port})`);- return ok;- })- ).then((results) => {- if (results.every(Boolean)) {- log('All services ready');- }- });- }-- if (isVerbose) {- console.log('\n=== MachinaOS Starting (verbose) ===\n');- const proc = spawn('pnpm', ['exec', 'concurrently', '--raw', '--kill-others', ...services], {- cwd: ROOT,- stdio: ['inherit', 'pipe', 'pipe'],- shell: true,- env: { ...process.env, FORCE_COLOR: '1' },- });-- proc.stdout.on('data', (data) => process.stdout.write(data));- proc.stderr.on('data', (data) => process.stderr.write(data));-- startReadyProbes();-- process.on('SIGINT', () => proc.kill('SIGINT'));- process.on('SIGTERM', () => proc.kill('SIGTERM'));- proc.on('close', (code) => process.exit(code || 0));- } else {- // Clean banner- const version = getVersion();- console.log(`\n MachinaOS v${version}`);- console.log(` Frontend: http://localhost:${config.clientPort}`);- console.log(` Backend: http://localhost:${config.backendPort}`);- console.log(` Use --verbose for full logs\n`);-- const serviceNames = ['client', 'server'];- if (!temporalRunning) serviceNames.push('temporal');-- const proc = spawn('pnpm', [- 'exec', 'concurrently', '--kill-others',- '-n', serviceNames.join(','),- '-c', 'blue,green,yellow,magenta',- ...services,- ], {- cwd: ROOT,- stdio: ['inherit', 'pipe', 'pipe'],- shell: true,- env: { ...process.env, FORCE_COLOR: '1' },- });-- // Show only essential output: errors and warnings (ready signals- // come from TCP probes via startReadyProbes(), not stdout grep).- const essential = /error|fatal|exception|failed|address already in use/i;-- proc.stdout.on('data', (data) => {- const text = data.toString();- for (const line of text.split('\n')) {- const trimmed = line.trim();- if (trimmed && essential.test(trimmed)) {- process.stdout.write(line + '\n');- }- }- });-- // Always show stderr- proc.stderr.on('data', (data) => process.stderr.write(data));-- startReadyProbes();-- process.on('SIGINT', () => proc.kill('SIGINT'));- process.on('SIGTERM', () => proc.kill('SIGTERM'));- proc.on('close', (code) => {- console.log('\nServices stopped.');- process.exit(code || 0);- });- }-}--main().catch(console.error);