Skip to content

Self-improving AI Employees for everyone

feat(machina): Phase A — Python CLI foundation + migrate `pnpm run stop`

trohitg19fcaef037de
diff --git a/machina/README.md b/machina/README.md
new file mode 100644
index 00000000..c6315184
--- /dev/null
+++ b/machina/README.md
@@ -0,0 +1,47 @@
+# machina
+
+Project supervisor CLI for the MachinaOS stack. Replaces `scripts/*.js`
+gradually; backwards-compatible with `pnpm run start`/`dev`/`stop`/etc.
+
+## Install
+
+Done automatically in `scripts/postinstall.js` after `pnpm install`. To
+install manually:
+
+```sh
+python -m pip install -e ./machina
+```
+
+## Use
+
+```sh
+python -m machina --help # list commands
+python -m machina stop # kill ports + orphans + temporal
+```
+
+Or via the npm scripts (which now invoke the same Python CLI):
+
+```sh
+pnpm run stop
+```
+
+## Cross-platform notes
+
+- **Windows**: `python` resolves correctly out of the box.
+- **macOS / Linux**: requires `python` to point to Python 3.11+. Most
+ modern distros provide this via `python-is-python3` or a symlink. If
+ your distro only ships `python3`, run `python3 -m machina <cmd>` or
+ add an alias.
+
+## Architecture
+
+Built on battle-tested primitives — minimal custom code:
+
+| Layer | Library |
+|---|---|
+| CLI | `typer` |
+| Subprocess | `anyio.open_process` |
+| Tree-kill | `psutil` + `pywin32` (Job Objects on Windows) |
+| Restart backoff | stdlib (deque + monotonic time + jittered exponential, ~20 LOC) |
+| Output | `rich.Console` |
+| Env | `python-dotenv` |
diff --git a/machina/__init__.py b/machina/__init__.py
new file mode 100644
index 00000000..27539a19
--- /dev/null
+++ b/machina/__init__.py
@@ -0,0 +1,3 @@
+"""MachinaOS project supervisor CLI."""
+
+__version__ = "0.1.0"
diff --git a/machina/__main__.py b/machina/__main__.py
new file mode 100644
index 00000000..3972b1c7
--- /dev/null
+++ b/machina/__main__.py
@@ -0,0 +1,7 @@
+"""Entry point for ``python -m machina``."""
+
+from machina.cli import app
+
+
+if __name__ == "__main__":
+ app()
diff --git a/machina/cli.py b/machina/cli.py
new file mode 100644
index 00000000..c2e414cd
--- /dev/null
+++ b/machina/cli.py
@@ -0,0 +1,38 @@
+"""Typer CLI for ``machina``.
+
+Each subcommand lives under ``machina.commands``; this module just
+mounts them and exposes ``app`` as the entry point.
+"""
+
+from __future__ import annotations
+
+import typer
+
+from machina.commands.stop import stop_command
+
+
+app = typer.Typer(
+ name="machina",
+ help="MachinaOS project supervisor CLI.",
+ no_args_is_help=True,
+ add_completion=False,
+)
+
+
+def _root() -> None:
+ """Marks the Typer app as a multi-command group.
+
+ Without an ``@app.callback()`` Typer collapses a single registered
+ subcommand into the root, hiding the subcommand structure that's
+ about to grow as more JS scripts migrate.
+ """
+
+
+app.command("stop", help="Stop all MachinaOS services and free configured ports.")(
+ stop_command
+)
+
+
+if __name__ == "__main__":
+ app()
diff --git a/machina/colors.py b/machina/colors.py
new file mode 100644
index 00000000..3db209a9
--- /dev/null
+++ b/machina/colors.py
@@ -0,0 +1,37 @@
+"""Rich console + per-service color rotation (Honcho-style)."""
+
+from __future__ import annotations
+
+from itertools import cycle
+from rich.console import Console
+
+
+# Single shared console — single-writer aggregator avoids interleaving
+# concurrent stream output (VS Code's pty host pattern).
+console = Console()
+
+
+# Honcho's rotation, lifted: skip very-dark (black) and very-bright (white)
+# so prefixes remain readable on both light and dark terminals.
+_PALETTE = [
+ "cyan", "green", "yellow", "blue", "magenta",
+ "bright_cyan", "bright_green", "bright_yellow", "bright_blue", "bright_magenta",
+]
+_color_cycle = cycle(_PALETTE)
+
+
+def next_color() -> str:
+ return next(_color_cycle)
+
+
+def emit(name: str, color: str, line: str, *, stream: str = "stdout") -> None:
+ """Print one line tagged with the service name + color.
+
+ Renders as ``cyan │ <message>`` so prefix width is uniform
+ across services.
+ """
+ width = 12
+ prefix = f"[{color}]{name:<{width}}[/{color}]"
+ style = "" if stream == "stdout" else "[dim]"
+ suffix = "" if stream == "stdout" else "[/dim]"
+ console.print(f"{prefix}{style} | {line}{suffix}", highlight=False)
diff --git a/machina/commands/__init__.py b/machina/commands/__init__.py
new file mode 100644
index 00000000..3d5571c8
--- /dev/null
+++ b/machina/commands/__init__.py
@@ -0,0 +1 @@
+"""``machina`` subcommand modules. Imported by ``machina.cli``."""
diff --git a/machina/commands/stop.py b/machina/commands/stop.py
new file mode 100644
index 00000000..151d965f
--- /dev/null
+++ b/machina/commands/stop.py
@@ -0,0 +1,70 @@
+"""``machina stop`` -- replaces ``scripts/stop.js``.
+
+Kills configured ports + orphaned MachinaOS processes + the Temporal
+binary. Same exit-code semantics as the JS version: 0 on full success,
+1 if any port is still in use afterward.
+"""
+
+from __future__ import annotations
+
+import time
+
+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_by_pattern,
+ kill_orphaned_machina_processes,
+ kill_port,
+)
+
+
+def stop_command() -> None:
+ cfg = load_config()
+ root = project_root()
+
+ console.print()
+ console.print("[bold]Stopping MachinaOS services...[/]")
+ console.print(f"Platform: {platform_name()}")
+ console.print(f"Ports: {', '.join(str(p) for p in cfg.ports.all())}")
+ console.print(f"Temporal: enabled" if cfg.temporal_enabled else "Temporal: disabled")
+ console.print()
+
+ all_stopped = True
+ for port in cfg.ports.all():
+ result = kill_port(port)
+ status = "[green]\\[OK][/]" if result.port_free else "[red]\\[!!][/]"
+ if result.port_free:
+ if result.killed_pids:
+ msg = f"Killed {len(result.killed_pids)} process(es)"
+ else:
+ msg = "Free"
+ else:
+ msg = "Warning: Port still in use"
+ all_stopped = False
+ console.print(f"{status} Port {port}: {msg}")
+ if result.killed_pids:
+ console.print(f" PIDs: {', '.join(str(p) for p in result.killed_pids)}")
+
+ temporal_pids = kill_by_pattern("temporal")
+ if temporal_pids:
+ console.print(
+ f"[green]\\[OK][/] Temporal: Killed {len(temporal_pids)} process(es)"
+ )
+
+ orphaned_pids = kill_orphaned_machina_processes(str(root))
+ if orphaned_pids:
+ time.sleep(0.2) # let DB locks release
+ console.print(
+ f"[green]\\[OK][/] Orphaned: Killed {len(orphaned_pids)} MachinaOS process(es)"
+ )
+ console.print(f" PIDs: {', '.join(str(p) for p in orphaned_pids)}")
+
+ console.print()
+ if all_stopped:
+ console.print("[green]All services stopped.[/]")
+ else:
+ console.print("[yellow]Warning: Some ports may still be in use.[/]")
+ raise typer.Exit(code=1)
diff --git a/machina/config.py b/machina/config.py
new file mode 100644
index 00000000..3b818bf7
--- /dev/null
+++ b/machina/config.py
@@ -0,0 +1,76 @@
+""".env loader + port resolution.
+
+Mirrors what ``scripts/utils.js:loadEnvConfig`` does, using
+``python-dotenv`` instead of a custom parser.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from dotenv import dotenv_values
+
+from machina.platform_ import project_root
+
+
+@dataclass(frozen=True)
+class Ports:
+ client: int
+ backend: int
+ whatsapp: int
+ nodejs: int
+ temporal: int
+
+ def all(self) -> list[int]:
+ return [self.client, self.backend, self.whatsapp, self.nodejs, self.temporal]
+
+
+@dataclass(frozen=True)
+class Config:
+ raw: dict[str, str | None] = field(default_factory=dict)
+ ports: Ports = field(default_factory=lambda: Ports(3000, 3010, 9400, 3020, 7233))
+ temporal_enabled: bool = True
+ redis_enabled: bool = False
+
+
+def _truthy(value: str | None) -> bool:
+ return (value or "").strip().lower() in {"true", "1", "yes", "on"}
+
+
+def _int(value: str | None, default: int) -> int:
+ try:
+ return int(value) if value else default
+ except (TypeError, ValueError):
+ return default
+
+
+def _temporal_port(address: str | None) -> int:
+ if not address:
+ return 7233
+ try:
+ return int(address.rsplit(":", 1)[-1])
+ except (ValueError, IndexError):
+ return 7233
+
+
+def load_config(root: Path | None = None) -> Config:
+ root = root or project_root()
+ env_path = root / ".env"
+ if not env_path.exists():
+ env_path = root / ".env.template"
+ raw = dotenv_values(env_path) if env_path.exists() else {}
+
+ ports = Ports(
+ client=_int(raw.get("VITE_CLIENT_PORT"), 3000),
+ backend=_int(raw.get("PYTHON_BACKEND_PORT"), 3010),
+ whatsapp=_int(raw.get("WHATSAPP_RPC_PORT"), 9400),
+ nodejs=_int(raw.get("NODEJS_EXECUTOR_PORT"), 3020),
+ temporal=_temporal_port(raw.get("TEMPORAL_SERVER_ADDRESS")),
+ )
+ return Config(
+ raw=dict(raw),
+ ports=ports,
+ temporal_enabled=_truthy(raw.get("TEMPORAL_ENABLED")) or True,
+ redis_enabled=_truthy(raw.get("REDIS_ENABLED")),
+ )
diff --git a/machina/platform_.py b/machina/platform_.py
new file mode 100644
index 00000000..e7e6199e
--- /dev/null
+++ b/machina/platform_.py
@@ -0,0 +1,37 @@
+"""Platform / shell / venv detection helpers."""
+
+from __future__ import annotations
+
+import os
+import sys
+from pathlib import Path
+
+
+IS_WINDOWS = sys.platform == "win32"
+IS_MACOS = sys.platform == "darwin"
+IS_LINUX = sys.platform.startswith("linux")
+IS_WSL = IS_LINUX and ("WSL_DISTRO_NAME" in os.environ or "WSLENV" in os.environ)
+IS_GIT_BASH = IS_WINDOWS and bool(
+ os.environ.get("MSYSTEM") or "bash" in (os.environ.get("SHELL") or "")
+)
+
+
+def platform_name() -> str:
+ """Human-readable platform label."""
+ if IS_GIT_BASH:
+ return "Git Bash"
+ if IS_WSL:
+ return "WSL"
+ if IS_WINDOWS:
+ return "Windows"
+ if IS_MACOS:
+ return "macOS"
+ return "Linux"
+
+
+def project_root() -> Path:
+ """Resolve the project root from a module under ``machina/``.
+
+ Layout: ``<project_root>/machina/<this_file>`` -> parents[1].
+ """
+ return Path(__file__).resolve().parents[1]
diff --git a/machina/ports.py b/machina/ports.py
new file mode 100644
index 00000000..33954dd8
--- /dev/null
+++ b/machina/ports.py
@@ -0,0 +1,133 @@
+"""Cross-platform port + process killing.
+
+Lifts the helpers from ``scripts/port_kill.py`` so the CLI uses the
+same battle-tested ``psutil`` paths that are already in production.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import subprocess
+from dataclasses import dataclass
+
+import psutil
+
+
+@dataclass
+class KillResult:
+ port: int
+ killed_pids: list[int]
+ port_free: bool
+
+
+def find_pids_by_port(port: int) -> set[int]:
+ """Find PIDs listening on ``port`` via psutil's native APIs."""
+ pids: set[int] = set()
+ try:
+ for conn in psutil.net_connections(kind="inet"):
+ if conn.laddr and conn.laddr.port == port and conn.pid:
+ pids.add(conn.pid)
+ except psutil.AccessDenied:
+ # macOS: net_connections() requires root, fall back to lsof.
+ if sys.platform == "darwin":
+ try:
+ output = subprocess.check_output(
+ ["lsof", "-ti", f":{port}"],
+ text=True,
+ stderr=subprocess.DEVNULL,
+ )
+ for line in output.strip().splitlines():
+ try:
+ pids.add(int(line.strip()))
+ except ValueError:
+ pass
+ except (subprocess.CalledProcessError, FileNotFoundError):
+ pass
+ except OSError:
+ pass
+ return pids
+
+
+def kill_pid(pid: int, *, graceful_timeout: float = 3.0) -> bool:
+ """Terminate ``pid`` gracefully, then force-kill on timeout."""
+ try:
+ proc = psutil.Process(pid)
+ proc.terminate()
+ try:
+ proc.wait(timeout=graceful_timeout)
+ except psutil.TimeoutExpired:
+ proc.kill()
+ return True
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ return False
+
+
+def kill_port(port: int) -> KillResult:
+ """Kill anything listening on ``port`` and report whether the port is free."""
+ my_pid = os.getpid()
+ killed: list[int] = []
+ for pid in find_pids_by_port(port):
+ if pid == my_pid:
+ continue
+ if kill_pid(pid):
+ killed.append(pid)
+ port_free = not find_pids_by_port(port)
+ return KillResult(port=port, killed_pids=killed, port_free=port_free)
+
+
+def kill_by_pattern(pattern: str, *, root_dir: str | None = None) -> list[int]:
+ """Kill processes whose name OR command line matches ``pattern``.
+
+ When ``root_dir`` is supplied, only processes whose command line also
+ references that path are killed (so unrelated tools that happen to
+ share a substring are left alone).
+ """
+ pattern_lower = pattern.lower()
+ root_norm = root_dir.lower().replace("\\", "/") if root_dir else None
+ my_pid = os.getpid()
+ killed: list[int] = []
+
+ for proc in psutil.process_iter(["pid", "name", "cmdline"]):
+ try:
+ name = (proc.info["name"] or "").lower()
+ cmd = " ".join(proc.info.get("cmdline") or []).lower().replace("\\", "/")
+ if pattern_lower not in name and pattern_lower not in cmd:
+ continue
+ if root_norm and root_norm not in cmd:
+ continue
+ if proc.pid == my_pid:
+ continue
+ proc.kill()
+ killed.append(proc.pid)
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ pass
+ return killed
+
+
+def kill_orphaned_machina_processes(
+ root_dir: str, *, exclude_substring: str | None = None
+) -> list[int]:
+ """Kill stray python/node processes whose cmdline references the project root."""
+ root_norm = root_dir.lower().replace("\\", "/")
+ target_names = {"python", "python3", "python.exe", "node", "node.exe"}
+ my_pid = os.getpid()
+ killed: list[int] = []
+
+ for proc in psutil.process_iter(["pid", "name", "cmdline"]):
+ try:
+ name = (proc.info["name"] or "").lower()
+ if name not in target_names:
+ continue
+ cmd = " ".join(proc.info.get("cmdline") or []).lower().replace("\\", "/")
+ if root_norm not in cmd:
+ continue
+ if exclude_substring and exclude_substring.lower() in cmd:
+ continue
+ if proc.pid == my_pid:
+ continue
+ if kill_pid(proc.pid, graceful_timeout=2.0):
+ killed.append(proc.pid)
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ pass
+ return killed
diff --git a/machina/pyproject.toml b/machina/pyproject.toml
new file mode 100644
index 00000000..30d75235
--- /dev/null
+++ b/machina/pyproject.toml
@@ -0,0 +1,29 @@
+[project]
+name = "machina"
+version = "0.1.0"
+description = "MachinaOS project supervisor CLI"
+requires-python = ">=3.11"
+dependencies = [
+ "typer>=0.12",
+ "rich>=13",
+ "psutil>=6",
+ "anyio>=4",
+ "python-dotenv>=1",
+ "pywin32>=308; platform_system == 'Windows'",
+]
+
+[project.scripts]
+machina = "machina.cli:app"
+
+[build-system]
+requires = ["setuptools>=68"]
+build-backend = "setuptools.build_meta"
+
+[tool.setuptools.packages.find]
+where = ["."]
+include = ["machina*"]
+exclude = ["tests*"]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+asyncio_mode = "auto"
diff --git a/machina/supervisor.py b/machina/supervisor.py
new file mode 100644
index 00000000..f65406c7
--- /dev/null
+++ b/machina/supervisor.py
@@ -0,0 +1,275 @@
+"""Supervisor for long-running services.
+
+VS Code-tier process control built on stdlib + ``anyio`` + ``psutil``:
+
+- One ``ServiceSpec`` per child; ``Manager.run()`` supervises them all
+ in a single ``anyio.create_task_group`` (structured concurrency)
+- Bounded restart with sliding window (LSP rule: 5 crashes / 3 min)
+- Exponential backoff with jitter between restarts (1s -> 30s cap)
+- Two-phase shutdown: SIGTERM -> grace -> SIGKILL via tree-walk
+- Job Object on Windows / ``setsid`` on POSIX so children die with us
+- Per-service color/prefix output via ``rich``
+
+Phase A leaves ``start`` / ``dev`` migrations for later -- but the
+supervisor is fully functional now and unit-tested.
+"""
+
+from __future__ import annotations
+
+import enum
+import os
+import random
+import signal
+import subprocess
+import sys
+import time
+from collections import deque
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Iterable, Optional
+
+import anyio
+
+from machina.colors import emit, next_color
+from machina.tcp import wait_for_tcp_port
+from machina.tree import add_to_job, kill_tree, new_session_kwargs
+
+
+class RestartPolicy(enum.Enum):
+ NEVER = "never"
+ ON_CRASH = "on_crash" # restart only on non-healthy exit
+ ALWAYS = "always" # restart on any exit
+
+
+@dataclass
+class ServiceSpec:
+ name: str
+ argv: list[str]
+ cwd: Path | None = None
+ env: dict[str, str] = field(default_factory=dict)
+ ready_port: int | None = None
+ ready_timeout: float = 30.0
+ restart: RestartPolicy = RestartPolicy.ON_CRASH
+ color: str | None = None
+ healthy_exit_codes: set[int] = field(default_factory=lambda: {0})
+ crash_window_seconds: float = 180.0
+ crash_window_max: int = 5
+ terminate_grace_seconds: float = 5.0
+
+
+def _full_env(spec_env: dict[str, str]) -> dict[str, str]:
+ """Inherit parent env + force-color so child output stays readable."""
+ return {
+ **os.environ,
+ "FORCE_COLOR": "1",
+ "PYTHONUNBUFFERED": "1",
+ **spec_env,
+ }
+
+
+async def _terminate_then_kill(
+ proc: anyio.abc.Process, *, grace: float
+) -> None:
+ """SIGTERM (POSIX) / TerminateProcess (Win) -> wait grace -> tree-kill."""
+ if proc.returncode is not None:
+ return
+ try:
+ proc.terminate()
+ except ProcessLookupError:
+ return
+ with anyio.move_on_after(grace):
+ await proc.wait()
+ if proc.returncode is None:
+ kill_tree(proc.pid)
+ try:
+ await proc.wait()
+ except Exception:
+ pass
+
+
+class Manager:
+ """Supervise multiple ``ServiceSpec`` instances in one TaskGroup."""
+
+ def __init__(self) -> None:
+ self._specs: list[ServiceSpec] = []
+ self._fatal: list[str] = [] # names of services that crash-looped
+ self._active = 0
+
+ def add(self, spec: ServiceSpec) -> None:
+ if spec.color is None:
+ spec.color = next_color()
+ self._specs.append(spec)
+
+ def add_all(self, specs: Iterable[ServiceSpec]) -> None:
+ for spec in specs:
+ self.add(spec)
+
+ async def run(self) -> int:
+ """Run all services concurrently. Return 0 on clean shutdown, 1 on fatal."""
+ if not self._specs:
+ return 0
+ self._active = len(self._specs)
+ unhandled = False
+ try:
+ async with anyio.create_task_group() as tg:
+ for spec in self._specs:
+ tg.start_soon(self._supervise_wrapped, spec, tg.cancel_scope)
+ tg.start_soon(self._wait_for_signal, tg.cancel_scope)
+ except* Exception as eg: # type: ignore[syntax] # py311+
+ for exc in eg.exceptions:
+ emit("manager", "red", f"unexpected error: {exc}", stream="stderr")
+ unhandled = True
+ if unhandled:
+ return 1
+ return 1 if self._fatal else 0
+
+ async def _supervise_wrapped(
+ self, spec: ServiceSpec, cancel_scope: anyio.CancelScope
+ ) -> None:
+ """Wrap ``_supervise`` so the manager exits when the last service does."""
+ try:
+ await self._supervise(spec, cancel_scope)
+ finally:
+ self._active -= 1
+ if self._active == 0:
+ # All supervised services have finished — wake the signal
+ # waiter and let the TaskGroup unwind cleanly.
+ cancel_scope.cancel()
+
+ async def _wait_for_signal(self, cancel_scope: anyio.CancelScope) -> None:
+ """Cancel the TaskGroup on Ctrl-C / SIGTERM (cross-platform).
+
+ Windows can only deliver ``SIGINT`` and ``SIGBREAK`` to a Python
+ process; passing ``SIGTERM`` would raise ``NotImplementedError``
+ from anyio. We probe the platform and subscribe to whichever
+ subset is available.
+ """
+ if sys.platform == "win32":
+ signals = (signal.SIGINT, getattr(signal, "SIGBREAK", signal.SIGINT))
+ else:
+ signals = (signal.SIGINT, signal.SIGTERM)
+ try:
+ with anyio.open_signal_receiver(*signals) as receiver:
+ async for sig in receiver:
+ emit(
+ "manager",
+ "yellow",
+ f"received {sig.name}, shutting down",
+ stream="stderr",
+ )
+ cancel_scope.cancel()
+ return
+ except NotImplementedError:
+ # Some environments (eg. asyncio on Windows without
+ # ProactorEventLoop, or signal handling from a non-main
+ # thread) don't support open_signal_receiver. Fall back to
+ # sleeping forever -- the supervised tasks themselves wake
+ # the cancel scope when they finish.
+ await anyio.sleep_forever()
+
+ async def _supervise(
+ self, spec: ServiceSpec, cancel_scope: anyio.CancelScope
+ ) -> None:
+ crashes: deque[float] = deque(maxlen=spec.crash_window_max)
+ backoff_seconds = 1.0
+ attempt = 0
+
+ while True:
+ attempt += 1
+ exit_code = await self._spawn_once(spec)
+ healthy = exit_code in spec.healthy_exit_codes
+
+ if spec.restart is RestartPolicy.NEVER:
+ return
+ if spec.restart is RestartPolicy.ON_CRASH and healthy:
+ emit(spec.name, spec.color or "white", f"exited cleanly ({exit_code})")
+ return
+
+ # Sliding-window crash detection (LSP rule).
+ crashes.append(time.monotonic())
+ if (
+ len(crashes) == spec.crash_window_max
+ and (crashes[-1] - crashes[0]) < spec.crash_window_seconds
+ ):
+ emit(
+ spec.name,
+ "red",
+ f"crash-loop: {spec.crash_window_max} deaths in "
+ f"{spec.crash_window_seconds:.0f}s -- giving up",
+ stream="stderr",
+ )
+ self._fatal.append(spec.name)
+ return
+
+ wait = backoff_seconds + random.uniform(0, backoff_seconds * 0.1)
+ emit(
+ spec.name,
+ "yellow",
+ f"exited with {exit_code}, restarting in {wait:.1f}s (attempt #{attempt})",
+ stream="stderr",
+ )
+ await anyio.sleep(wait)
+ backoff_seconds = min(backoff_seconds * 2, 30.0)
+
+ async def _spawn_once(self, spec: ServiceSpec) -> int:
+ """Spawn the service, drain its output, return exit code."""
+ env = _full_env(spec.env)
+ spawn_kwargs = new_session_kwargs()
+ proc = await anyio.open_process(
+ spec.argv,
+ cwd=str(spec.cwd) if spec.cwd else None,
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ **spawn_kwargs,
+ )
+ if sys.platform == "win32":
+ add_to_job(proc.pid)
+ emit(spec.name, spec.color or "white", f"started pid={proc.pid}")
+
+ try:
+ async with anyio.create_task_group() as tg:
+ tg.start_soon(self._drain, proc.stdout, spec, "stdout")
+ tg.start_soon(self._drain, proc.stderr, spec, "stderr")
+ if spec.ready_port:
+ tg.start_soon(self._announce_ready, spec)
+ exit_code = await proc.wait()
+ tg.cancel_scope.cancel()
+ except anyio.get_cancelled_exc_class():
+ await _terminate_then_kill(proc, grace=spec.terminate_grace_seconds)
+ raise
+ return exit_code
+
+ async def _drain(
+ self,
+ stream: Optional[anyio.abc.ByteReceiveStream],
+ spec: ServiceSpec,
+ which: str,
+ ) -> None:
+ if stream is None:
+ return
+ buf = b""
+ try:
+ async for chunk in stream:
+ buf += chunk
+ while b"\n" in buf:
+ line, buf = buf.split(b"\n", 1)
+ text = line.decode("utf-8", errors="replace").rstrip("\r")
+ if text:
+ emit(spec.name, spec.color or "white", text, stream=which)
+ if buf:
+ text = buf.decode("utf-8", errors="replace").rstrip("\r")
+ if text:
+ emit(spec.name, spec.color or "white", text, stream=which)
+ except (anyio.ClosedResourceError, anyio.EndOfStream):
+ pass
+
+ async def _announce_ready(self, spec: ServiceSpec) -> None:
+ ok = await wait_for_tcp_port(
+ spec.ready_port, # type: ignore[arg-type]
+ timeout=spec.ready_timeout,
+ )
+ msg = f"ready on port {spec.ready_port}" if ok else f"timed out waiting for port {spec.ready_port}"
+ emit(spec.name, spec.color or "white", msg)
+
+
diff --git a/machina/tcp.py b/machina/tcp.py
new file mode 100644
index 00000000..b7f3c444
--- /dev/null
+++ b/machina/tcp.py
@@ -0,0 +1,52 @@
+"""TCP probes — port-up detection without shell pipes."""
+
+from __future__ import annotations
+
+import asyncio
+import socket
+import time
+
+
+async def probe_tcp_port(port: int, host: str = "127.0.0.1", *, timeout: float = 0.5) -> bool:
+ """Return True iff a TCP connection to ``host:port`` succeeds within ``timeout``."""
+ try:
+ _, writer = await asyncio.wait_for(
+ asyncio.open_connection(host, port), timeout=timeout
+ )
+ writer.close()
+ try:
+ await writer.wait_closed()
+ except (ConnectionResetError, OSError):
+ pass
+ return True
+ except (asyncio.TimeoutError, ConnectionRefusedError, OSError):
+ return False
+
+
+async def wait_for_tcp_port(
+ port: int,
+ *,
+ host: str = "127.0.0.1",
+ interval: float = 0.25,
+ timeout: float = 60.0,
+) -> bool:
+ """Poll until ``port`` accepts a TCP connection or ``timeout`` elapses."""
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if await probe_tcp_port(port, host, timeout=interval):
+ return True
+ await asyncio.sleep(interval)
+ return False
+
+
+def probe_tcp_port_sync(port: int, host: str = "127.0.0.1", *, timeout: float = 0.5) -> bool:
+ """Synchronous variant for places that aren't already in an event loop."""
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.settimeout(timeout)
+ try:
+ sock.connect((host, port))
+ return True
+ except OSError:
+ return False
+ finally:
+ sock.close()
diff --git a/machina/tests/__init__.py b/machina/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/machina/tests/test_cli.py b/machina/tests/test_cli.py
new file mode 100644
index 00000000..6a4e58fb
--- /dev/null
+++ b/machina/tests/test_cli.py
@@ -0,0 +1,22 @@
+"""Smoke tests for the Typer CLI surface."""
+
+from __future__ import annotations
+
+from typer.testing import CliRunner
+
+from machina.cli import app
+
+
+runner = CliRunner()
+
+
+def test_help_lists_stop():
+ result = runner.invoke(app, ["--help"])
+ assert result.exit_code == 0
+ assert "stop" in result.output
+
+
+def test_stop_help():
+ result = runner.invoke(app, ["stop", "--help"])
+ assert result.exit_code == 0
+ assert "Stop all MachinaOS services" in result.output
diff --git a/machina/tests/test_ports.py b/machina/tests/test_ports.py
new file mode 100644
index 00000000..9527581f
--- /dev/null
+++ b/machina/tests/test_ports.py
@@ -0,0 +1,41 @@
+"""Unit tests for ``machina.ports``."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import psutil
+
+from machina import ports
+
+
+def test_kill_pid_no_such_process_returns_false():
+ with patch.object(psutil, "Process", side_effect=psutil.NoSuchProcess(123)):
+ assert ports.kill_pid(123) is False
+
+
+def test_kill_pid_terminates_then_waits():
+ proc = MagicMock()
+ with patch.object(psutil, "Process", return_value=proc):
+ assert ports.kill_pid(123) is True
+ proc.terminate.assert_called_once()
+ proc.wait.assert_called_once()
+
+
+def test_kill_pid_force_kills_on_timeout():
+ proc = MagicMock()
+ proc.wait.side_effect = psutil.TimeoutExpired(seconds=1)
+ with patch.object(psutil, "Process", return_value=proc):
+ assert ports.kill_pid(123) is True
+ proc.terminate.assert_called_once()
+ proc.kill.assert_called_once()
+
+
+def test_kill_port_excludes_self():
+ """The function must never kill its own PID."""
+ import os
+ my_pid = os.getpid()
+ with patch.object(ports, "find_pids_by_port", side_effect=[{my_pid}, set()]):
+ result = ports.kill_port(9999)
+ assert result.killed_pids == []
+ assert result.port_free is True
diff --git a/machina/tests/test_supervisor.py b/machina/tests/test_supervisor.py
new file mode 100644
index 00000000..bb2a375b
--- /dev/null
+++ b/machina/tests/test_supervisor.py
@@ -0,0 +1,70 @@
+"""Unit tests for ``machina.supervisor``."""
+
+from __future__ import annotations
+
+from collections import deque
+
+import pytest
+
+from machina.supervisor import Manager, ServiceSpec, RestartPolicy, _full_env
+
+
+def test_full_env_force_color_and_unbuffered():
+ env = _full_env({"FOO": "bar"})
+ assert env["FORCE_COLOR"] == "1"
+ assert env["PYTHONUNBUFFERED"] == "1"
+ assert env["FOO"] == "bar"
+
+
+def test_manager_assigns_color_to_specs():
+ m = Manager()
+ s1 = ServiceSpec(name="a", argv=["true"])
+ s2 = ServiceSpec(name="b", argv=["true"])
+ m.add(s1)
+ m.add(s2)
+ assert s1.color is not None
+ assert s2.color is not None
+ assert s1.color != s2.color # rotation
+
+
+def test_service_spec_defaults_safe():
+ spec = ServiceSpec(name="x", argv=["echo", "hi"])
+ assert spec.restart is RestartPolicy.ON_CRASH
+ assert spec.healthy_exit_codes == {0}
+ assert spec.crash_window_max == 5
+ assert spec.crash_window_seconds == 180.0
+
+
+def test_crash_window_logic():
+ """Sliding-window detection: 5 deaths within window => give up."""
+ import time
+ crashes = deque(maxlen=5)
+ spec = ServiceSpec(name="x", argv=["true"])
+ now = time.monotonic()
+ for i in range(5):
+ crashes.append(now + i * 10) # 5 crashes in 40s
+ assert (
+ len(crashes) == spec.crash_window_max
+ and (crashes[-1] - crashes[0]) < spec.crash_window_seconds
+ )
+
+
+async def test_manager_runs_clean_exit_service():
+ """A NEVER-restart service that exits 0 should let the manager finish cleanly."""
+ import sys
+ m = Manager()
+ m.add(
+ ServiceSpec(
+ name="quick",
+ argv=[sys.executable, "-c", "print('hello'); exit(0)"],
+ restart=RestartPolicy.NEVER,
+ )
+ )
+ rc = await m.run()
+ assert rc == 0
+
+
+def anyio_backend():
+ return "asyncio"
diff --git a/machina/tree.py b/machina/tree.py
new file mode 100644
index 00000000..4905ded8
--- /dev/null
+++ b/machina/tree.py
@@ -0,0 +1,125 @@
+"""Cross-platform process-tree control.
+
+The single most important pattern from VS Code's process model:
+guarantee that supervised children die when the supervisor dies. On
+POSIX we use ``setsid`` + ``killpg``. On Windows we use a Job Object
+with ``JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`` so the OS atomically reaps
+every descendant when the supervisor handle closes.
+
+References:
+- https://nikhilism.com/post/2017/windows-job-objects-process-tree-management/
+- microsoft/node-pty (uses Job Objects in production)
+"""
+
+from __future__ import annotations
+
+import os
+import signal
+import sys
+from typing import Optional
+
+import psutil
+
+
+# ---------------------------------------------------------------- POSIX
+
+def new_session_kwargs() -> dict:
+ """``Popen``/``open_process`` kwargs to start the child in a new session.
+
+ Empty dict on Windows; uses ``start_new_session`` on POSIX so the
+ child is the leader of its own process group and ``killpg`` reaches
+ the entire descendant tree.
+ """
+ if sys.platform == "win32":
+ return {}
+ return {"start_new_session": True}
+
+
+def signal_group(pid: int, sig: signal.Signals = signal.SIGTERM) -> None:
+ """Send ``sig`` to the process group led by ``pid`` (POSIX only)."""
+ if sys.platform == "win32":
+ return
+ try:
+ os.killpg(os.getpgid(pid), sig)
+ except ProcessLookupError:
+ pass
+
+
+# ---------------------------------------------------------------- Windows Job Object
+
+class _JobObject:
+ """Lazy-imported wrapper around a Windows Job Object."""
+
+ def __init__(self) -> None:
+ self._handle = None
+ self._win32job = None
+ if sys.platform == "win32":
+ try:
+ import win32job # type: ignore[import-not-found]
+
+ self._win32job = win32job
+ self._handle = win32job.CreateJobObject(None, "")
+ info = win32job.QueryInformationJobObject(
+ self._handle, win32job.JobObjectExtendedLimitInformation
+ )
+ info["BasicLimitInformation"]["LimitFlags"] |= (
+ win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ )
+ win32job.SetInformationJobObject(
+ self._handle, win32job.JobObjectExtendedLimitInformation, info
+ )
+ except Exception: # pywin32 missing or denied
+ self._handle = None
+
+ def add(self, pid: int) -> bool:
+ """Enroll ``pid`` in the job. Returns False when unavailable."""
+ if self._handle is None or self._win32job is None:
+ return False
+ try:
+ import win32api # type: ignore[import-not-found]
+
+ handle = win32api.OpenProcess(0x1F0FFF, False, pid)
+ self._win32job.AssignProcessToJobObject(self._handle, handle)
+ return True
+ except Exception:
+ return False
+
+
+_JOB: Optional[_JobObject] = None
+
+
+def get_job() -> _JobObject:
+ global _JOB
+ if _JOB is None:
+ _JOB = _JobObject()
+ return _JOB
+
+
+def add_to_job(pid: int) -> bool:
+ """Best-effort enrollment of ``pid`` in the supervisor's Job Object."""
+ if sys.platform != "win32":
+ return False
+ return get_job().add(pid)
+
+
+# --------------------------------------------------------------- Tree kill
+
+def kill_tree(pid: int) -> None:
+ """Cross-platform tree-kill via psutil. Defensive against races."""
+ try:
+ parent = psutil.Process(pid)
+ except psutil.NoSuchProcess:
+ return
+ try:
+ children = parent.children(recursive=True)
+ except psutil.NoSuchProcess:
+ children = []
+ for child in children:
+ try:
+ child.kill()
+ except psutil.NoSuchProcess:
+ pass
+ try:
+ parent.kill()
+ except psutil.NoSuchProcess:
+ pass
diff --git a/package.json b/package.json
index 7a3b4ce2..b4e40804 100644
--- a/package.json
+++ b/package.json
@@ -72,7 +72,7 @@
"temporal:worker": "cd server && uv run python -m services.temporal.worker",
"build": "node scripts/build.js",
"clean": "node scripts/clean.js",
- "stop": "node scripts/stop.js",
+ "stop": "python -m machina stop",
"test": "npm run test:backend && npm run test:frontend",
"test:backend": "cd server && uv run pytest tests/ -v",
"test:frontend": "cd client && npm run test",
diff --git a/scripts/postinstall.js b/scripts/postinstall.js
index 518e6ad2..74f0198e 100755
--- a/scripts/postinstall.js
+++ b/scripts/postinstall.js
@@ -21,7 +21,6 @@ function fixPermissions() {
resolve(ROOT, 'bin/cli.js'),
resolve(ROOT, 'scripts/start.js'),
resolve(ROOT, 'scripts/dev.js'),
- resolve(ROOT, 'scripts/stop.js'),
resolve(ROOT, 'scripts/build.js'),
resolve(ROOT, 'scripts/clean.js'),
resolve(ROOT, 'scripts/install.js'),
@@ -78,6 +77,18 @@ function runScript(scriptPath) {
});
}
+function runPython(args) {
+ return new Promise((resolveP, reject) => {
+ const cmd = process.platform === 'win32' ? 'python' : 'python3';
+ const child = spawn(cmd, args, { cwd: ROOT, stdio: 'inherit' });
+ child.on('error', reject);
+ child.on('close', (code) => {
+ if (code === 0) resolveP();
+ else reject(new Error(`${cmd} exited with code ${code}`));
+ });
+ });
+}
+
async function main() {
try {
// Fix executable permissions on Unix
@@ -87,6 +98,19 @@ async function main() {
console.log('Installing dependencies...');
await runScript(resolve(__dirname, 'install.js'));
+ // Install the machina CLI into whatever python is on PATH (system,
+ // conda, or active venv). Idempotent: re-runs are no-ops since pip
+ // detects the editable install. Fail-soft: a missing Python
+ // interpreter doesn't block the rest of npm install.
+ console.log('Installing machina CLI (python -m pip install -e ./machina)...');
+ try {
+ await runPython(['-m', 'pip', 'install', '-e', resolve(ROOT, 'machina'),
+ '--quiet', '--disable-pip-version-check']);
+ } catch (err) {
+ console.log(`Warning: machina CLI install skipped (${err.message}).`);
+ console.log(' Install manually with: python -m pip install -e ./machina');
+ }
+
console.log('');
console.log('========================================');
console.log(' MachinaOS installed successfully!');
diff --git a/scripts/stop.js b/scripts/stop.js
deleted file mode 100755
index 79da7b79..00000000
--- a/scripts/stop.js
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/env node
-/**
- * Cross-platform stop script for MachinaOS services.
- * Works on: Windows, macOS, Linux, WSL, Git Bash
- */
-import {
- getPlatformName,
- loadEnvConfig,
- killPort,
- killByPattern,
- killOrphanedProcesses,
- sleep,
-} from './utils.js';
-
-async function main() {
- const config = loadEnvConfig();
-
- console.log('Stopping MachinaOS services...\n');
- console.log(`Platform: ${getPlatformName()}`);
- console.log(`Ports: ${config.allPorts.join(', ')}`);
- console.log(`Temporal: enabled\n`);
-
- let allStopped = true;
-
- for (const port of config.allPorts) {
- const result = await killPort(port);
- const status = result.portFree ? '[OK]' : '[!!]';
- const message = result.portFree
- ? (result.killed.length > 0 ? `Killed ${result.killed.length} process(es)` : 'Free')
- : 'Warning: Port still in use';
-
- console.log(`${status} Port ${port}: ${message}`);
- if (result.killed.length > 0) {
- console.log(` PIDs: ${result.killed.join(', ')}`);
- }
- if (!result.portFree) allStopped = false;
- }
-
- const temporalPids = await killByPattern('temporal');
- if (temporalPids.length > 0) {
- console.log(`[OK] Temporal: Killed ${temporalPids.length} process(es)`);
- }
-
- // Kill orphaned MachinaOs processes (may hold DB locks after crash)
- const orphanedPids = await killOrphanedProcesses();
- if (orphanedPids.length > 0) {
- await sleep(200);
- console.log(`[OK] Orphaned: Killed ${orphanedPids.length} MachinaOs process(es)`);
- console.log(` PIDs: ${orphanedPids.join(', ')}`);
- }
-
- console.log('');
- if (allStopped) {
- console.log('All services stopped.');
- } else {
- console.log('Warning: Some ports may still be in use.');
- process.exit(1);
- }
-}
-
-main().catch(console.error);