Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(machina): extract buildenv helpers (venv_python + validate_build)
trohitg377f5119e562
diff --git a/machina/buildenv.py b/machina/buildenv.pynew file mode 100644index 00000000..132acf96--- /dev/null+++ b/machina/buildenv.py@@ -0,0 +1,44 @@+"""Build-environment helpers shared by ``start`` / ``dev`` / ``daemon``.++Three commands had near-duplicate copies of "find the venv python" and+"the build artifacts must exist or refuse to start". Lifted here so a+new launcher gets both for free.+"""++from __future__ import annotations++from pathlib import Path++import typer++from machina.colors import console+++def venv_python(root: Path) -> Path | None:+ """Return the project's venv python path, or ``None`` if absent.++ Tries the Windows layout first (``Scripts/python.exe``) then POSIX+ (``bin/python``); the first existing path wins.+ """+ for candidate in (+ root / "server" / ".venv" / "Scripts" / "python.exe",+ root / "server" / ".venv" / "bin" / "python",+ ):+ if candidate.exists():+ return candidate+ return None+++def validate_build(root: Path, *, require_client_dist: bool = False) -> None:+ """Refuse to launch if ``machina build`` hasn't been run.++ Raises ``typer.Exit(1)`` with a remediation hint. ``dev`` allows a+ missing ``client/dist`` (Vite serves the source); ``start`` opts in+ via ``require_client_dist=True``.+ """+ 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 require_client_dist and not (root / "client" / "dist" / "index.html").exists():+ console.print('[red]Error: Client not built. Run "machina build" first.[/]')+ raise typer.Exit(code=1)diff --git a/machina/commands/daemon.py b/machina/commands/daemon.pyindex 7bdbf754..be9a724e 100644--- a/machina/commands/daemon.py+++ b/machina/commands/daemon.py@@ -21,6 +21,7 @@ from pathlib import Pathimport psutilimport typer+from machina.buildenv import venv_pythonfrom machina.colors import consolefrom machina.platform_ import IS_WINDOWS, project_root@@ -38,12 +39,6 @@ _PID_DIR = Path.home() / ".machina"_PID_FILE = _PID_DIR / "machina-backend.pid"-def _venv_python(install_dir: Path) -> Path:- if IS_WINDOWS:- return install_dir / "server" / ".venv" / "Scripts" / "python.exe"- return install_dir / "server" / ".venv" / "bin" / "python"--def _detached_kwargs() -> dict:"""Cross-platform "spawn detached, survive parent exit" kwargs."""if IS_WINDOWS:@@ -103,8 +98,8 @@ def start_command() -> None:root = project_root()server = root / "server"- py = _venv_python(root)- if not py.exists():+ py = venv_python(root)+ if py is None:console.print(f'[red]Python venv not found at {py}.[/] Run "machina build" first.')raise typer.Exit(code=1)diff --git a/machina/commands/dev.py b/machina/commands/dev.pyindex 282294f6..78e34361 100644--- a/machina/commands/dev.py+++ b/machina/commands/dev.py@@ -22,16 +22,11 @@ import typerfrom machina.colors import consolefrom machina.config import load_configfrom machina.platform_ import platform_name, project_root+from machina.buildenv import validate_buildfrom machina.ports import kill_portfrom 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()@@ -104,7 +99,7 @@ def dev_command(cfg = load_config()os.environ.setdefault("PYTHONUTF8", "1")- _validate_build(root)+ validate_build(root)console.print("\n[bold]=== MachinaOS Starting ===[/]\n")console.print(f"Platform: {platform_name()}")diff --git a/machina/commands/start.py b/machina/commands/start.pyindex 1929f195..d12270e6 100644--- a/machina/commands/start.py+++ b/machina/commands/start.py@@ -24,20 +24,11 @@ import typerfrom machina.colors import consolefrom machina.config import load_configfrom machina.platform_ import IS_WINDOWS, IS_WSL, platform_name, project_root+from machina.buildenv import validate_build, venv_pythonfrom machina.ports import kill_portfrom 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.@@ -47,7 +38,7 @@ def _sqlalchemy_preflight(root: Path) -> None:clear remediation message instead of letting uvicorn hang silently.See ``docs-internal/errors.md`` #1 / #1a."""- py = _venv_python(root)+ py = venv_python(root)if py is None:returnstarted = time.monotonic()@@ -91,15 +82,6 @@ def _temporal_running() -> bool: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"))@@ -154,7 +136,7 @@ def start_command() -> None:cfg = load_config()os.environ.setdefault("PYTHONUTF8", "1")- _validate_build(root)+ validate_build(root, require_client_dist=True)_sqlalchemy_preflight(root)temporal_running = _temporal_running()diff --git a/machina/tests/test_daemon.py b/machina/tests/test_daemon.pyindex 60104a49..18ce6feb 100644--- a/machina/tests/test_daemon.py+++ b/machina/tests/test_daemon.py@@ -12,12 +12,8 @@ import pytestfrom machina.commands import daemon-def test_venv_python_chooses_layout_per_platform():- install_dir = Path("/x")- with patch.object(daemon, "IS_WINDOWS", True):- assert daemon._venv_python(install_dir).name == "python.exe"- with patch.object(daemon, "IS_WINDOWS", False):- assert daemon._venv_python(install_dir).name == "python"+# venv-python discovery is now centralised in machina.buildenv; covered+# by tests/test_start.py (test_venv_python_finds_*).def test_detached_kwargs_windows_uses_creationflags():diff --git a/machina/tests/test_start.py b/machina/tests/test_start.pyindex 47725b54..90983cf3 100644--- a/machina/tests/test_start.py+++ b/machina/tests/test_start.py@@ -5,6 +5,7 @@ from __future__ import annotationsfrom pathlib import Pathfrom unittest.mock import patch+from machina import buildenvfrom machina.commands import startfrom machina.config import Config@@ -14,21 +15,21 @@ def _cfg() -> Config:def test_venv_python_returns_none_when_missing(tmp_path: Path):- assert start._venv_python(tmp_path) is None+ assert buildenv.venv_python(tmp_path) is Nonedef 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+ assert buildenv.venv_python(tmp_path) == win_pydef 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+ assert buildenv.venv_python(tmp_path) == posix_pydef test_temporal_running_false_when_cli_missing():