Skip to content

Self-improving AI Employees for everyone

refactor(machina): extract buildenv helpers (venv_python + validate_build)

trohitg377f5119e562
diff --git a/machina/buildenv.py b/machina/buildenv.py
new file mode 100644
index 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.py
index 7bdbf754..be9a724e 100644
--- a/machina/commands/daemon.py
+++ b/machina/commands/daemon.py
@@ -21,6 +21,7 @@ from pathlib import Path
import psutil
import typer
+from machina.buildenv import venv_python
from machina.colors import console
from 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.py
index 282294f6..78e34361 100644
--- a/machina/commands/dev.py
+++ b/machina/commands/dev.py
@@ -22,16 +22,11 @@ import typer
from machina.colors import console
from machina.config import load_config
from machina.platform_ import platform_name, project_root
+from machina.buildenv import validate_build
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()
@@ -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.py
index 1929f195..d12270e6 100644
--- a/machina/commands/start.py
+++ b/machina/commands/start.py
@@ -24,20 +24,11 @@ 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.buildenv import validate_build, venv_python
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.
@@ -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:
return
started = 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.py
index 60104a49..18ce6feb 100644
--- a/machina/tests/test_daemon.py
+++ b/machina/tests/test_daemon.py
@@ -12,12 +12,8 @@ import pytest
from 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.py
index 47725b54..90983cf3 100644
--- a/machina/tests/test_start.py
+++ b/machina/tests/test_start.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from pathlib import Path
from unittest.mock import patch
+from machina import buildenv
from machina.commands import start
from 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 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
+ assert buildenv.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
+ assert buildenv.venv_python(tmp_path) == posix_py
def test_temporal_running_false_when_cli_missing():