Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor: trim resident process overhead from the runtime topology
trohitgdc9a7eb1ccad
diff --git a/CLAUDE.md b/CLAUDE.mdindex f0a261a9..de7d3215 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -714,7 +714,7 @@ npm run deploy # Self-deploy to a cloud VM (python -m cli deploy)```### Cross-Platform Scripts-Service orchestration lives in the Python CLI (`company start/dev/stop/build/clean/serve/daemon/deploy/docs/version` — see `cli/`). The `scripts/` directory retains only the npm install lifecycle helpers (`install.js`, `preinstall.js`, `postinstall.js`) and `serve-client.js`.+Service orchestration lives in the Python CLI (`company start/dev/stop/build/clean/serve/daemon/deploy/docs/version` — see `cli/`). The `scripts/` directory retains only the npm install lifecycle helpers (`install.js`, `preinstall.js`, `postinstall.js`). `company start` is single-port: uvicorn serves API + WS + built SPA on the backend port (`SERVE_STATIC_CLIENT`, default on); the retired `scripts/serve-client.js` static server and its `:3000` frontend port are gone.See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.@@ -734,7 +734,7 @@ See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.✅ **Process Management**: Robust stop scripts with duplicate process detection✅ **WhatsApp Integration**: Square node design with QR code viewer, group/sender name persistence, newsletter channel support (send, query, follow/unfollow, create, mute, mark viewed, react, live updates), media download, profile pics, and proper error handling✅ **Backend Stability**: Fixed dependency injection and error handling preventing crashes-✅ **Development Server**: Running at **http://localhost:3001** (frontend) and **http://localhost:3010** (backend)+✅ **Development Server**: `company dev` = Vite HMR at **http://localhost:3000** + backend at **http://localhost:3010**; `company start` (production) = single port **http://localhost:3010** (API + WS + SPA)✅ **WebSocket Integration**: Persistent WebSocket connections for remote Android devices with background tasks and message queue✅ **Real-time Status WebSocket**: Frontend-backend WebSocket at `/ws/status` for live Android status, node status, and variable updates✅ **Event-Driven Trigger Nodes**: WhatsApp Receive and Webhook Trigger with asyncio.Future-based event waiting, filter builders, and cancel support@@ -1121,7 +1121,7 @@ Full reference — agent loop, skill injection, tool building, input/auto-prompt## Testing & Validation```bash# Development server test-curl -I http://localhost:3001+curl -I http://localhost:3010# TypeScript validationnpx tsc --noEmit@@ -2708,7 +2708,7 @@ This function:- **No raw `print()` outside three sanctioned helpers**: `main._startup_log` (pre-logger boot markers), `core.container._clog` (DI-bootstrap markers), and `nodes.code.python_executor.captured_print` (the sandbox builtin handed to user code). Everything else goes through `logger = get_logger(__name__)`. The supervisor prefixes every aggregated line with `[HH:MM:SS.fff]` so no inner `TimeStamper` is needed; structlog console mode is deliberately timestamp-less. Test `server/tests/test_no_raw_prints.py` AST-walks the tree and flags any unsanctioned `print(...)` call.- **`configure_logging(settings)` must run BEFORE plugin self-registration imports**: in `main.py`, `Settings()` + `configure_logging(settings)` + `init_tracing()` + `get_logger(__name__)` happen ahead of `from core.container import container` and `from routers import …`. Otherwise plugin folders that register on import call `logger.debug(...)` while structlog is still on its default processor chain (which includes `TimeStamper` + no `filter_by_level`) — symptom is double timestamps + debug records leaking despite `LOG_LEVEL=INFO`.- **Plugin-identifier shape validator (`services/plugin/identifiers.py`)** (`7700f87`): `NODE_TYPE_PATTERN = r"^[A-Za-z_][A-Za-z0-9_]*$"` + `is_valid_node_type(value)`. Single source of truth used by FastAPI URL routes (`Path(pattern=NODE_TYPE_PATTERN)` in `routers/schemas.py`) AND internal helpers (`nodes/_visuals.py::get_plugin_meta` / `get_plugin_icon_path`). Closes CodeQL `py/path-injection` alerts on the icon-resolution endpoints: the registry lookup `get_node_class(node_type)` already gates the taint in practice, but CodeQL can't follow registry-mediated sanitization — adding `fullmatch` at the function boundary is the canonical pattern its rule docs prescribe. Contract test (`tests/services/test_identifiers.py`, 47 cases) locks the regex against `../etc/passwd`, `..\windows\system32`, `foo\x00bar`, `%2e%2e%2fetc`, `foo;bar`, `${HOME}`, `` foo`bar ``, CRLF, and non-string input.-- **CLI recovery-resilience invariants** (May 2026): `python -m cli clean` must run end-to-end on a system Python with no third-party deps. Achieved by: (a) every verb in [`cli/cli.py`](./cli/cli.py) is a lazy stub that imports its impl inside the function body — `import cli.cli` does NOT pull in `anyio` / `psutil` / `cli.supervisor` / sibling verb modules (300 → 131 modules at boot). (b) [`cli/_common.py`](./cli/_common.py) defers `cli.run` + `cli.supervisor` imports inside `build_backend_spec` so importing `cli._common` (and therefore `clean.py`) doesn't drag in rich. (c) [`cli/platform_.py`](./cli/platform_.py) lazy-imports `platformdirs` inside the four `user_*_dir` helpers — module loads without the wheel. (d) [`cli/commands/clean.py`](./cli/commands/clean.py) uses stdlib `print()` (no rich) + lazy `cli.ports` import inside `_kill_running_processes` wrapped in `try/except ImportError` (skip-with-warning if psutil is missing). (e) [`cli/commands/_temporal_specs.py`](./cli/commands/_temporal_specs.py) reads `os.environ["TEMPORAL_*"]` inside `temporal_specs()`, not at module load — so importing the module is safe before `load_config()` has run. (f) The supervised-runtime shim moved from `cli/commands/_supervised_runtime.py` to [`server/services/temporal/_supervised_runtime.py`](./server/services/temporal/_supervised_runtime.py) (colocated with the factories it imports). (g) `daemon` is now a verb-per-file package ([`cli/commands/daemon/`](./cli/commands/daemon/) — `_state.py` + `start.py` + `stop.py` + `status.py` + `restart.py`) following pdm's `commands/venv/` shape; PID-file resolution is a function (`pid_dir()`) not a module-level attribute so platformdirs only loads at call time.+- **CLI recovery-resilience invariants** (May 2026): `python -m cli clean` must run end-to-end on a system Python with no third-party deps. Achieved by: (a) every verb in [`cli/cli.py`](./cli/cli.py) is a lazy stub that imports its impl inside the function body — `import cli.cli` does NOT pull in `anyio` / `psutil` / `cli.supervisor` / sibling verb modules (300 → 131 modules at boot). (b) [`cli/_common.py`](./cli/_common.py) defers `cli.supervisor` imports inside `build_backend_spec` so importing `cli._common` (and therefore `clean.py`) doesn't drag in rich. (c) [`cli/platform_.py`](./cli/platform_.py) lazy-imports `platformdirs` inside the four `user_*_dir` helpers — module loads without the wheel. (d) [`cli/commands/clean.py`](./cli/commands/clean.py) uses stdlib `print()` (no rich) + lazy `cli.ports` import inside `_kill_running_processes` wrapped in `try/except ImportError` (skip-with-warning if psutil is missing). (e)+(f) retired July 2026: the CLI no longer supervises Temporal at all — the backend lifespan owns the dev server via `services.temporal._runtime.ensure_started()` (`cli/commands/_temporal_specs.py` and the `_supervised_runtime.py` shim were deleted; long-running specs spawn the server venv interpreter directly via `cli.platform_.server_venv_python`, no resident `uv run` parents). (g) `daemon` is now a verb-per-file package ([`cli/commands/daemon/`](./cli/commands/daemon/) — `_state.py` + `start.py` + `stop.py` + `status.py` + `restart.py`) following pdm's `commands/venv/` shape; PID-file resolution is a function (`pid_dir()`) not a module-level attribute so platformdirs only loads at call time.- **Wave 13 canary fixes** — six load-bearing corrections to the Wave 12 event framework. See [docs-internal/event_framework.md → Wave 13 fixes](./docs-internal/event_framework.md#wave-13-fixes) for the full breakdown. Key invariants to remember when working on canary triggers: (1) `register_canary_trigger_type(node_type, cloudevent_type)` requires the CloudEvents reverse-DNS string as second arg — must match the producer's `WorkflowEvent.type` exactly or the deployment manager's `EventType` SA won't match `dispatch.emit`'s Visibility query (silent firing failure). Diverging re-registration raises `ValueError` so plugin upgrades surface loudly. (2) Plugin `_events.py` for canary-registered triggers is canary-only — no `event_waiter.dispatch` / `send_custom_event` calls (those have zero consumers in canary-on mode). `dispatch.emit(envelope, wire_routing_key=...)` handles BOTH Temporal Signal fan-out AND in-process WS broadcast. (3) `TriggerListenerWorkflow` + `PollingTriggerWorkflow` call `broadcast_trigger_status_activity` before/after each child spawn for firing-pulse UX (matches legacy `triggers.py` collector/processor). (4) `PollingTriggerNode.as_poll_activity` returns `seen_ids: list(current)` — NOT `list(prior_seen | current)` (the latter grows unboundedly; Gmail at ~100/day hit ~36K entries in a year). The legacy `_build_poll_coroutine` does `seen = set(current)` at end of cycle for the same reason. Visibility-filtered providers (Gmail-unread) re-emit on re-surface, which is correct. (5) Canary trigger output persistence: `MachinaWorkflow.run`'s pre-executed loop schedules `store_node_output_activity` for every firing trigger so `ParameterResolver` can resolve `{{triggerNode.field}}` in downstream nodes (the legacy `_execute_from_trigger` did this via `_store_output(trigger_node_id, "output_0", ...)`; canary skipped it pre-fix). Skips non-firing siblings (`_trigger_output={"not_triggered": True}`). (6) `DeploymentManager.cancel` sweeps stuck node statuses via `_clear_stuck_node_statuses(workflow_id, include_waiting=True)` + emits terminal `update_workflow_status(executing=False, workflow_id=...)`. Without these the FE leaves downstream nodes glowing forever after deployment cancel and the toolbar Start/Stop indicator stays at `executing=True`. The delegation guard inside `_clear_stuck_node_statuses` still protects in-flight fire-and-forget child agents.- **Deployment reconcile snapshot on WS connect** (de8df87): a stale FE `deploymentStatus.isRunning=true` used to survive a backend restart because the in-memory `DeploymentManager._deployments` dict was wiped (no recovery wiring — the `RecoverySweeper.set_recovery_callback` extension point exists but is intentionally unwired; see the "workflow status not properly recognized" investigation). The Start button therefore stayed showing "Stop" forever. Fix: new `WorkflowEvent.deployment_snapshot(running_workflow_ids)` typed factory (`source = opencompany://services/workflow`, `type = workflow.deployment.snapshot`) + `broadcaster._send_deployment_snapshot(websocket)` that runs at the tail of `broadcaster.connect()` (single-target, NOT fan-out — only the just-connecting client needs to reconcile). FE `case 'deployment_snapshot'` in `WebSocketContext.tsx` iterates `useAppStore.workflowUIStates` and clears `isExecuting=true` on any workflow NOT in the snapshot's running set (empty list is meaningful — this is the load-bearing reset). Also reconciles `deploymentStatus.isRunning` for the active workflow. Distinct from `workflow_lifecycle("deployment.started")` (state-transition edge event) — the snapshot is an idempotent state dump tied to client connect, not a transition.- **Agent progress badge — defensive status invariant** (15b8d9d): `AIAgentNode`'s "N / max" iteration badge is gated on `isExecuting && typeof iteration === 'number' && typeof maxIterations === 'number'` where `isExecuting = nodeStatus?.status === 'executing'`. The `agent_progress` handler USED to only set `data.iteration` / `data.max_iterations`, relying on a prior `node_status='executing'` broadcast to have already stamped the status. If agent_progress arrived first (race, single-step agent completion, out-of-order Temporal activity delivery), `status` stayed undefined and the badge was hidden even though the iteration data was populated. Fix: the agent_progress handler now defensively sets `status='executing'` on the slot — but preserves `'success'` / `'error'` if a later terminal broadcast already flipped the slot (terminal states win over the resurrection).diff --git a/README.md b/README.mdindex 0c882e2f..704434c9 100644--- a/README.md+++ b/README.md@@ -22,7 +22,7 @@ npm install -g @zeenie-ai/opencompanycompany start```-Open http://localhost:3000 and click the key icon (**API Credentials**) in the toolbar to connect your first AI provider.+Open http://localhost:3010 and click the key icon (**API Credentials**) in the toolbar to connect your first AI provider.> **Upgrading from MachinaOS?** Existing `~/.machina` and checkout-local `.machina` state is detected when the new `.opencompany` location does not yet exist, so databases and deployment state are not stranded. The `machina` command remains available as a deprecated legacy alias; new scripts should use `company`.diff --git a/cli/_common.py b/cli/_common.pyindex d98c92c5..d48f3371 100644--- a/cli/_common.py+++ b/cli/_common.py@@ -9,9 +9,8 @@ Centralises the four patterns that previously appeared inlined inloop; lazy-imports ``cli.ports`` so abroken ``psutil`` install doesn't takedown the recovery verb.- - :func:`build_backend_spec` -- the shared ``uv_run("uvicorn", ...)``- ServiceSpec used by both ``start``- and ``dev``.+ - :func:`build_backend_spec` -- the shared uvicorn ServiceSpec used+ by both ``start`` and ``dev``.- :func:`error_block` -- multi-line ``[red]Error: ...[/]``formatter; lazy-imports ``cli.colors``.@@ -77,21 +76,25 @@ def build_backend_spec() -> "ServiceSpec":"""The Python backend ``ServiceSpec`` shared by ``start`` and ``dev``.- Routes through :func:`cli.run.uv_run` so the standardised- ``uv run --no-sync`` flags stay in one place. ``host`` is the only- differentiator (``start`` picks ``127.0.0.1`` on Windows/WSL vs- ``0.0.0.0`` elsewhere; ``dev`` honours its ``--daemon`` flag).+ Invokes the server venv's interpreter directly — the same idiom+ ``company serve`` documents (no resident ``uv run`` parent process,+ no runtime dependency on uv being on PATH; ``company build`` owns+ sync semantics). ``host`` is the only differentiator (``start``+ picks ``127.0.0.1`` on Windows/WSL vs ``0.0.0.0`` elsewhere;+ ``dev`` honours its ``--daemon`` flag).- ``cli.run`` and ``cli.supervisor`` are lazy-imported so this module- stays importable when their transitive ``rich`` dep is missing --- ``company clean`` doesn't call this and shouldn't pay for it.+ ``cli.supervisor`` is lazy-imported so this module stays importable+ when its transitive ``rich`` dep is missing -- ``company clean``+ doesn't call this and shouldn't pay for it."""- from cli.run import uv_run+ from cli.platform_ import server_venv_pythonfrom cli.supervisor import ServiceSpecreturn ServiceSpec(name="server",- argv=uv_run(+ argv=[+ str(server_venv_python(root)),+ "-m","uvicorn","main:app","--host",@@ -100,7 +103,7 @@ def build_backend_spec(str(cfg.backend_port),"--log-level","warning",- ),+ ],cwd=server_dir(root),ready_port=cfg.backend_port,)diff --git a/cli/commands/_temporal_specs.py b/cli/commands/_temporal_specs.pydeleted file mode 100644index 9c5f3e4b..00000000--- a/cli/commands/_temporal_specs.py+++ /dev/null@@ -1,59 +0,0 @@-"""ServiceSpec for the Temporal stack — shared by ``start`` and ``dev``.--One ServiceSpec running the supervised :class:`TemporalServerRuntime`-singleton via :mod:`services.temporal._supervised_runtime` (a thin-shim that lives next to the runtime factory it imports). The runtime-spawns the official ``temporal`` CLI (downloaded by pooch from-https://temporal.download/cli/archive/latest) with the ``server-start-dev`` subcommand against a SQLite db at-``settings.temporal_sqlite_path``.--Matches the local-dev install method documented at-https://docs.temporal.io/develop/python/set-up-your-local-python.-"""--from __future__ import annotations--import os-from pathlib import Path--from cli.config import Config-from cli.platform_ import server_dir-from cli.run import uv_run-from cli.supervisor import RestartPolicy, ServiceSpec---def temporal_specs(root: Path, cfg: Config) -> list[ServiceSpec]:- """Return the Temporal ServiceSpec list.-- ``cfg`` is :class:`cli.config.Config`; ``cfg.temporal_port`` drives- the gRPC readiness probe.-- Readiness-probe + graceful-shutdown windows are read at call time- from ``os.environ`` (pushed there by :func:`cli.config.load_config`- from ``.env.template``); ``KeyError`` if missing — broken install.- Doing the reads here, not at module import, keeps the module safe- to import before ``load_config()`` runs (tests, REPL, reverse- import order).- """- return [- ServiceSpec(- name="temporal",- argv=uv_run(- "python",- "-m",- "services.temporal._supervised_runtime",- "services.temporal._runtime:get_temporal_server_runtime",- ),- cwd=server_dir(root),- ready_port=cfg.temporal_port,- ready_timeout=float(os.environ["TEMPORAL_SERVER_READY_TIMEOUT_SECONDS"]),- restart=RestartPolicy.ON_CRASH,- terminate_grace_seconds=float(- os.environ["TEMPORAL_GRACEFUL_SHUTDOWN_SECONDS"]- ),- ),- ]---__all__ = ["temporal_specs"]diff --git a/cli/commands/daemon/start.py b/cli/commands/daemon/start.pyindex 6f258e10..96259eb0 100644--- a/cli/commands/daemon/start.py+++ b/cli/commands/daemon/start.py@@ -6,8 +6,7 @@ import subprocessfrom cli._common import preflightfrom cli.colors import console-from cli.platform_ import server_dir-from cli.run import uv_run+from cli.platform_ import server_dir, server_venv_pythonfrom . import appfrom ._state import detached_kwargs, log_file, pid_dir, pid_file, read_pid@@ -29,7 +28,9 @@ def start_command() -> None:log = log_path.open("ab")proc = subprocess.Popen(- uv_run(+ [+ str(server_venv_python(root)),+ "-m","uvicorn","main:app","--host",@@ -38,7 +39,7 @@ def start_command() -> None:str(backend_port),"--log-level","warning",- ),+ ],cwd=str(server_dir(root)),stdin=subprocess.DEVNULL,stdout=log,diff --git a/cli/commands/dev.py b/cli/commands/dev.pyindex 411873a1..0f758925 100644--- a/cli/commands/dev.py+++ b/cli/commands/dev.py@@ -1,7 +1,8 @@"""``company dev`` -- replaces ``scripts/dev.js``.Development launcher: validates the build, frees ports, then spawns-Vite + uvicorn + temporal-server under ``Manager.run()``.+Vite + uvicorn under ``Manager.run()``. The Temporal dev server is+backend-owned (started from the lifespan when ``TEMPORAL_ENABLED``).The Vite dep cache (``client/node_modules/.vite``) is preserved acrossboots -- Vite self-invalidates it via the lockfile/config hashes in@@ -34,11 +35,9 @@ from cli.config import load_dev_overridesfrom cli.platform_ import (node_modules_dir,platform_name,- static_client_script,)from cli.buildenv import validate_buildfrom cli.supervisor import Manager, ServiceSpec-from cli.commands._temporal_specs import temporal_specsdef _has_vite(root: Path) -> bool:@@ -50,26 +49,25 @@ def _has_vite(root: Path) -> bool:def _build_specs(root: Path, cfg, *, daemon: bool, use_vite: bool, force: bool = False) -> list[ServiceSpec]:- if use_vite:- client_spec = ServiceSpec(+ # Without Vite there is no separate client process: the backend+ # serves the built SPA itself (``SERVE_STATIC_CLIENT`` in+ # ``server/main.py``, on by default). The Temporal dev server is+ # likewise backend-owned (started from the lifespan when enabled).+ backend_host = "0.0.0.0" if daemon else "127.0.0.1"+ server_spec = build_backend_spec(cfg, host=backend_host, root=root)+ if not use_vite:+ return [server_spec]+ return [+ ServiceSpec(name="client",argv=["pnpm", "run", "client:start"],cwd=root,ready_port=cfg.client_port,ready_timeout=60.0,env={"VITE_FORCE": "1"} if force else {},- )- else:- client_spec = ServiceSpec(- name="client",- argv=["node", str(static_client_script(root))],- cwd=root,- ready_port=cfg.client_port,- )-- backend_host = "0.0.0.0" if daemon else "127.0.0.1"- server_spec = build_backend_spec(cfg, host=backend_host, root=root)- return [client_spec, server_spec, *temporal_specs(root, cfg)]+ ),+ server_spec,+ ]def dev_command(@@ -108,7 +106,9 @@ def dev_command(console.log("Ports ready")use_vite = _has_vite(root)- console.print(f"Client: {'Vite dev server' if use_vite else 'Static server'}")+ console.print(+ f"Client: {'Vite dev server' if use_vite else 'served by backend (built SPA)'}"+ )if force:console.print("Vite: forced dependency re-bundle (--force)")console.print()diff --git a/cli/commands/serve.py b/cli/commands/serve.pyindex c94a469e..54589a53 100644--- a/cli/commands/serve.py+++ b/cli/commands/serve.py@@ -28,14 +28,7 @@ import typerfrom cli._common import preflightfrom cli.buildenv import validate_buildfrom cli.colors import console-from cli.platform_ import IS_WINDOWS, server_dir, server_venv---def _venv_python(root: Path | None = None) -> str:- """Absolute path to the server venv's Python interpreter."""- venv = server_venv(root)- rel = "Scripts/python.exe" if IS_WINDOWS else "bin/python"- return str(venv / rel)+from cli.platform_ import server_dir, server_venv_pythondef serve_command(port: int | None = None) -> None:@@ -67,7 +60,7 @@ def serve_command(port: int | None = None) -> None:ServiceSpec(name="server",argv=[- _venv_python(root),+ str(server_venv_python(root)),"-m","uvicorn","main:app",diff --git a/cli/commands/start.py b/cli/commands/start.pyindex d21a2710..73dcdacc 100644--- a/cli/commands/start.py+++ b/cli/commands/start.py@@ -2,11 +2,16 @@Production launcher: validates the build exists, runs the sqlalchemypreflight 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.+then spawns uvicorn under ``Manager.run()``. The backend serves the+built SPA itself (the ``SERVE_STATIC_CLIENT`` block in+``server/main.py``, on by default), so there is no separate static+client process.++Optional daemons are supervised by the Python backend, not here:+WhatsApp's edgymeow binary (``server/nodes/whatsapp/_runtime.py``) and+the Temporal dev server (``server/services/temporal/_runtime.py``,+started from the backend lifespan when ``TEMPORAL_ENABLED`` and the+configured address is loopback)."""from __future__ import annotations@@ -27,12 +32,10 @@ from cli.platform_ import (platform_name,server_dir,server_venv,- static_client_script,+ server_venv_python,)from cli.buildenv import validate_build-from cli.run import uv_runfrom cli.supervisor import Manager, ServiceSpec-from cli.commands._temporal_specs import temporal_specsdef _sqlalchemy_preflight(root: Path) -> None:@@ -44,16 +47,13 @@ def _sqlalchemy_preflight(root: Path) -> None:clear remediation message instead of letting uvicorn hang silently.See ``docs-internal/errors.md`` #1 / #1a.- Runs the probe inside the server ``.venv`` through ``uv run`` with- ``cwd=server/`` so uv discovers ``server/pyproject.toml`` (the only- place uv-managed Python deps live -- root ``pyproject.toml`` is the- standalone CLI package). Same environment the supervised services- will use, no path-to-interpreter logic on this side.+ Runs the probe with the server venv's interpreter -- the same one+ the supervised backend spec uses."""started = time.monotonic()try:subprocess.run(- uv_run("python", "-c", "import sqlalchemy"),+ [str(server_venv_python(root)), "-c", "import sqlalchemy"],cwd=str(server_dir(root)),timeout=15,check=True,@@ -101,17 +101,6 @@ def _sqlalchemy_preflight(root: Path) -> None:)-def _temporal_running(cfg) -> bool:- """Check whether a Temporal frontend is already listening on the- configured gRPC port. TCP probe instead of spawning a CLI -- works- without the legacy ``temporal-server`` npm wrapper (we install our- own binary via pooch at first boot of the supervised- ``TemporalServerRuntime``)."""- from cli.tcp import probe_tcp_port_sync-- return probe_tcp_port_sync(cfg.temporal_port)--def _read_version(root: Path) -> str:try:pkg = json.loads((root / "package.json").read_text(encoding="utf-8"))@@ -120,7 +109,7 @@ def _read_version(root: Path) -> str:return "0.0.0"-def _build_specs(root: Path, cfg, *, temporal_running: bool) -> list[ServiceSpec]:+def _build_specs(root: Path, cfg) -> list[ServiceSpec]:# Bind host: ``OPENCOMPANY_BIND_HOST`` overrides the auto-pick. The# pre-rebrand ``MACHINA_BIND_HOST`` spelling remains a compatibility# hatch when the platform detection is wrong or the operator wants@@ -134,18 +123,7 @@ def _build_specs(root: Path, cfg, *, temporal_running: bool) -> list[ServiceSpecor ("127.0.0.1" if IS_WINDOWS else "0.0.0.0"))- specs: list[ServiceSpec] = [- ServiceSpec(- name="client",- argv=["node", str(static_client_script(root))],- cwd=root,- ready_port=cfg.client_port,- ),- build_backend_spec(cfg, host=backend_host, root=root),- ]- if not temporal_running:- specs.extend(temporal_specs(root, cfg))- return specs+ return [build_backend_spec(cfg, host=backend_host, root=root)]def start_command() -> None:@@ -155,10 +133,6 @@ def start_command() -> None:validate_build(root, require_client_dist=True)_sqlalchemy_preflight(root)- temporal_running = _temporal_running(cfg)- if temporal_running:- console.print("[dim]Temporal already running, skipping[/]")-console.log("Freeing ports...")free_all_ports(cfg)console.log("Ports ready")@@ -166,13 +140,12 @@ def start_command() -> None:version = _read_version(root)console.print()console.print(f" [bold]OpenCompany[/] v{version}")- console.print(f" Frontend: http://localhost:{cfg.client_port}")- console.print(f" Backend: http://localhost:{cfg.backend_port}")+ console.print(f" App: http://localhost:{cfg.backend_port} (API + WebSocket + SPA)")console.print(f" Platform: {platform_name()}")console.print()manager = Manager()- manager.add_all(_build_specs(root, cfg, temporal_running=temporal_running))+ manager.add_all(_build_specs(root, cfg))rc = asyncio.run(manager.run())if rc != 0:raise typer.Exit(code=rc)diff --git a/cli/platform_.py b/cli/platform_.pyindex f0a52ee5..36ab974b 100644--- a/cli/platform_.py+++ b/cli/platform_.py@@ -106,6 +106,18 @@ def server_venv(root: Path | None = None) -> Path:return base / ".venv"+def server_venv_python(root: Path | None = None) -> Path:+ """The server venv's Python interpreter (respects+ ``UV_PROJECT_ENVIRONMENT`` via :func:`server_venv`).++ Long-running services spawn this directly; ``uv run`` would stay+ resident as each child's parent and require uv on PATH at runtime.+ One-shot build/sync commands keep using :func:`cli.run.uv_run`.+ """+ rel = "Scripts/python.exe" if IS_WINDOWS else "bin/python"+ return server_venv(root) / rel++def node_modules_dir(root: Path | None = None) -> Path:"""The pnpm/npm-installed dependency tree at the workspace root."""return _root(root) / "node_modules"@@ -117,12 +129,6 @@ def client_dist_entry(root: Path | None = None) -> Path:return _root(root) / "client" / "dist" / "index.html"-def static_client_script(root: Path | None = None) -> Path:- """The Node.js static-server script that serves the built client- (used by ``company start``)."""- return _root(root) / "scripts" / "serve-client.js"--# ---------------------------------------------------------------------------# OS-native user directories via ``platformdirs``# (https://pypi.org/project/platformdirs/). ``platformdirs`` is importeddiff --git a/cli/tests/test_dev.py b/cli/tests/test_dev.pyindex 57d9d1d3..a6791e21 100644--- a/cli/tests/test_dev.py+++ b/cli/tests/test_dev.py@@ -63,12 +63,12 @@ def test_build_specs_dev_uses_vite_when_available(tmp_path: Path):assert by_name["client"].argv[:3] == ["pnpm", "run", "client:start"]-def test_build_specs_dev_falls_back_to_static_without_vite(tmp_path: Path):+def test_build_specs_dev_without_vite_is_backend_only(tmp_path: Path):+ # No Vite => no client process at all: the backend serves the built+ # SPA itself (SERVE_STATIC_CLIENT in server/main.py, on by default).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]+ assert {s.name for s in specs} == {"server"}def test_build_specs_daemon_binds_0_0_0_0(tmp_path: Path):@@ -85,7 +85,10 @@ def test_build_specs_non_daemon_binds_127_0_0_1(tmp_path: Path):assert "127.0.0.1" in server_argv-def test_build_specs_dev_always_includes_temporal(tmp_path: Path):+def test_build_specs_dev_has_no_temporal_spec(tmp_path: Path):+ # The Temporal dev server is backend-owned: started from the FastAPI+ # lifespan (services.temporal._runtime.ensure_started) when+ # TEMPORAL_ENABLED and the configured address is loopback.cfg = _cfg()specs = dev._build_specs(tmp_path, cfg, daemon=False, use_vite=True)- assert any(s.name == "temporal" for s in specs)+ assert not any(s.name == "temporal" for s in specs)diff --git a/cli/tests/test_start.py b/cli/tests/test_start.pyindex 373bb3e0..732a13c2 100644--- a/cli/tests/test_start.py+++ b/cli/tests/test_start.py@@ -3,7 +3,6 @@from __future__ import annotationsfrom pathlib import Path-from unittest.mock import patchfrom cli.commands import startfrom cli.config import Config, load_config@@ -17,42 +16,31 @@ def _cfg() -> Config:return load_config()-# The previous ``test_venv_python_*`` cases verified a custom helper-# that walked ``server/.venv/{Scripts,bin}`` paths. That helper has been-# retired: subprocess launchers now build their argv via-# :func:`cli.run.uv_run`, which delegates interpreter selection to-# ``uv run`` (https://docs.astral.sh/uv/reference/cli/#uv-run). Nothing-# platform-specific to assert from the CLI side anymore.+# ``start`` supervises exactly one process: uvicorn, spawned via the+# server venv's interpreter (see ``cli.platform_.server_venv_python``).+# The backend serves the built SPA itself (SERVE_STATIC_CLIENT) and+# owns the Temporal dev server + other optional daemons from its+# lifespan, so no client/temporal specs exist on the CLI side.-def test_temporal_running_false_when_port_closed():- # TCP-probe based check: returns False when nothing is listening on- # the configured gRPC port. Mock the probe directly instead of the- # legacy subprocess-spawn implementation.+def test_build_specs_is_backend_only(tmp_path: Path):cfg = _cfg()- with patch("cli.tcp.probe_tcp_port_sync", return_value=False):- assert start._temporal_running(cfg) is False+ specs = start._build_specs(tmp_path, cfg)+ assert {s.name for s in specs} == {"server"}-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_backend_uses_venv_interpreter(tmp_path: Path):+ from cli.platform_ import server_venv_python-def test_build_specs_includes_temporal_when_not_running(tmp_path: Path):cfg = _cfg()- specs = start._build_specs(tmp_path, cfg, temporal_running=False)- names = {s.name for s in specs}- # Backend-agnostic: sqlite yields {"client", "server", "temporal"};- # postgres yields {"client", "server", "postgres", "temporal"}.- assert {"client", "server", "temporal"} <= names+ specs = start._build_specs(tmp_path, cfg)+ server = next(s for s in specs if s.name == "server")+ assert server.argv[0] == str(server_venv_python(tmp_path))+ assert server.argv[1:4] == ["-m", "uvicorn", "main:app"]def test_build_specs_assigns_ready_ports(tmp_path: Path):cfg = _cfg()- specs = start._build_specs(tmp_path, cfg, temporal_running=False)+ specs = start._build_specs(tmp_path, cfg)by_name = {s.name: s for s in specs}- assert by_name["client"].ready_port == cfg.client_portassert by_name["server"].ready_port == cfg.backend_port- assert by_name["temporal"].ready_port == cfg.temporal_portdiff --git a/docs-internal/SCRIPTS.md b/docs-internal/SCRIPTS.mdindex 0a64403f..5b1dc7fb 100644--- a/docs-internal/SCRIPTS.md+++ b/docs-internal/SCRIPTS.md@@ -7,7 +7,7 @@ npm install -g @zeenie-ai/opencompanycompany start```-Open http://localhost:3000+Open http://localhost:3010## CLI Commands (`company`, Python Typer app under `cli/`)@@ -20,8 +20,8 @@ deprecation warning; kept for upgrade compatibility).| Command | Description ||---------|-------------|-| `company start` | Start all services in production mode (static client + uvicorn + temporal) |-| `company dev` | Start in dev mode (Vite HMR + uvicorn + temporal). `--force` re-bundles Vite deps (recovers "Outdated Optimize Dep"); `--daemon` binds backend to 0.0.0.0 |+| `company start` | Production mode, single port: uvicorn serves API + WS + built SPA on :3010. Optional daemons (Temporal dev server, WhatsApp) are backend-owned, started from the lifespan when enabled |+| `company dev` | Start in dev mode (Vite HMR + uvicorn). `--force` re-bundles Vite deps (recovers "Outdated Optimize Dep"); `--daemon` binds backend to 0.0.0.0 || `company serve` | Single-port production runtime (uvicorn serves API + WS + built SPA + Node sidecar) — the systemd `ExecStart` on deployed VMs || `company stop` | Stop all services and free configured ports || `company build` | Full production build (pnpm install → client → sidecar → uv sync → bytecode → temporal binary). Step [0/6] scaffolds `.env` from `.env.template` when missing, generating fresh random secrets (`secrets.token_hex(24)`) for `SECRET_KEY` / `JWT_SECRET_KEY` / `API_KEY_ENCRYPTION_KEY` instead of the dev placeholders; an existing `.env` is untouched |@@ -90,9 +90,11 @@ Temporal server lifecycle is managed by `company start` / `company dev` / `compa| `install.js` | npm-tarball install pipeline (pnpm/uv install, client + sidecar build, bytecode compile, temporal binary fetch) — mirrors `company build`; the compileall command shape is locked in sync by `cli/tests/test_release_pipeline_config.py` || `preinstall.js` | Legacy-package/temp cleanup (also runs on uninstall) || `postinstall.js` | npm lifecycle entry that guards recursion and invokes install.js |-| `serve-client.js` | Static client server used by `company start` (production mode, no Vite) || `migrate_icons.py`, `migrate_skill_icons.py` | One-off icon-migration utilities (historical) |+(`serve-client.js` was retired July 2026: `company start` is single-port —+the backend serves the built SPA itself via `SERVE_STATIC_CLIENT`.)+There is no Docker tooling: Docker Compose support was removed(historical topology preserved in[deployment_legacy.md](./deployment_legacy.md)); deployment isdiff --git a/docs-internal/SETUP.md b/docs-internal/SETUP.mdindex c95fc13b..e82e22a3 100644--- a/docs-internal/SETUP.md+++ b/docs-internal/SETUP.md@@ -4,7 +4,7 @@```OpenCompany/-├── client/ # React frontend (port 3000)+├── client/ # React frontend (Vite dev server on port 3000; production build served by the backend)│ ├── src/│ └── package.json├── server/ # Python FastAPI backend (port 3010)@@ -25,7 +25,8 @@ npm install -g @zeenie-ai/opencompanycompany start```-Open http://localhost:3000+Open http://localhost:3010 — `company start` is single-port (API ++WebSocket + built SPA on the backend port).### Local Development (from source)@@ -47,22 +48,16 @@ the embedding node and long-term memory, install the optional extra:cd server && uv sync --extra local-embeddings```-### Docker+Services (production `company start`):+- **App (API + WS + SPA)**: http://localhost:3010+- **WhatsApp Service**: http://localhost:9400 (backend-spawned on demand)+- **Temporal dev server**: gRPC :7233, Web UI :8080 (backend-spawned when `TEMPORAL_ENABLED`)-```bash-git clone https://github.com/zeenie-ai/OpenCompany.git OpenCompany-cd OpenCompany-npm run docker:up-```--Services will be available at:-- **Frontend**: http://localhost:3000-- **Backend API**: http://localhost:3010-- **WhatsApp Service**: http://localhost:9400+`company dev` additionally runs the Vite HMR client at http://localhost:3000.## Services Overview-### Frontend (React - Port 3000)+### Frontend (React — Vite dev port 3000, production served by the backend on 3010)- React 19 with TypeScript- React Flow for workflow canvas- Zustand for state management@@ -89,8 +84,8 @@ Services will be available at:### Temporal Server (Distributed Execution)- Provides durable workflow execution with per-node retry and horizontal scaling-- Official `temporal` CLI downloaded by `pooch` from `https://temporal.download/cli/archive/latest` on `company build` (or first `company start`)-- Supervised by OpenCompany as `temporal server start-dev` — single process, SQLite at `~/.opencompany/temporal.db`+- Official `temporal` CLI downloaded by `pooch` from `https://temporal.download/cli/archive/latest` on `company build` (or first backend boot with Temporal enabled)+- Backend-owned: the FastAPI lifespan starts `temporal server start-dev` via `TemporalServerRuntime.ensure_started()` when `TEMPORAL_ENABLED` and the configured address is loopback (external clusters are detected via TCP probe and left alone) — SQLite at `~/.opencompany/temporal.db`- Ports: gRPC 7233, Web UI 8080- Embedded worker runs inside Python backend (`TemporalWorkerManager` in `main.py`)- Workflow auto-resumption disabled at startup (history preserved); see `TEMPORAL_TERMINATE_RUNNING_ON_STARTUP`@@ -142,16 +137,9 @@ When `VITE_AUTH_ENABLED=false` (the default):- API keys can be saved/retrieved without user authentication- Useful for local development and testing-## Docker Commands--| Command | Description |-|---------|-------------|-| `npm run docker:up` | Start containers |-| `npm run docker:down` | Stop containers |-| `npm run docker:logs` | View logs |-| `npm run docker:build` | Rebuild images |-**Redis (optional):** Set `REDIS_ENABLED=true` in `.env`+(Docker Compose tooling was removed; the historical topology is in+[deployment_legacy.md](./deployment_legacy.md).)## Local Commands@@ -185,16 +173,9 @@ uv export --frozen --no-emit-project --no-hashes --no-dev -o requirements.txt```### Database issues-SQLite database is created automatically at `server/workflow.db`.-Delete the database file to reset all data.--### Docker containers won't start-Check logs and rebuild:-```bash-docker-compose logs -f-docker-compose down-docker-compose up --build -d-```+SQLite databases are created automatically under `DATA_DIR`+(`~/.opencompany/` by default; `<repo>/.opencompany/` in dev mode).+Delete `workflow.db` there to reset all data.## Development Workflow@@ -205,7 +186,7 @@ docker-compose up --build -d## Architecture Notes-- **WebSocket-First**: 25 message handlers replace most REST APIs+- **WebSocket-First**: WS message handlers replace most REST APIs (live set = `MESSAGE_HANDLERS` in `server/routers/websocket.py` + plugin-registered handlers)- **n8n-inspired**: Node definitions follow n8n INodeProperties pattern- **Cache Fallback**: Redis (production) → SQLite (dev) → Memory- **Event-Driven**: Trigger nodes use asyncio.Future for event waitingdiff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex e7d4923b..65125ab2 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -583,7 +583,7 @@ The Temporal binary + persistence are managed in-process by the plugin-folder pa- **[`pooch`](https://pypi.org/project/pooch/)** — `services/temporal/_install.py` downloads the official `temporal` CLI archive from `https://temporal.download/cli/archive/latest?platform=<os>&arch=<arch>`. Cross-platform (Windows zip / macOS+Linux tar.gz), cached at `<DATA_DIR>/packages/temporal/` via `_cache_dir() = core.paths.package_dir("temporal")` (pooch's `path=` argument). The retrieve call passes an explicit `downloader=pooch.HTTPDownloader(timeout=300, progressbar=True)`: the timeout is per-socket-read (not total transfer), so arbitrarily slow links can finish the ~114 MB fetch — pooch's 30 s default aborted them — and `progressbar` must live on the downloader because `retrieve()` ignores its own kwarg when `downloader=` is explicit. Failed downloads never poison the cache (pooch writes to a temp file and renames atomically on success). Standalone entry: `python -m services.temporal._install` — invoked **fatally** by `company build` step [6/6] (so first `company start` doesn't pay the download; contract locked by `test_temporal_install_is_fatal_on_failure`) and **non-fatally** by npm postinstall (`scripts/install.js` try/catch — `TemporalServerRuntime._pre_spawn()` re-downloads lazily on first `company start`, so a failed eager fetch never fails `npm install -g`). The binary cache survives `company clean` (`packages` is in `_OPENCOMPANY_KEEP`, `cli/commands/clean.py`). Pre-fix this used `pooch.os_cache("opencompany-temporal")` (`~/.cache/OpenCompany/opencompany-temporal/` etc.) — a separate OS-cache namespace operators reported as "not local"; it now sits under DATA_DIR alongside the Stripe binary and the shared npm tree.- **`BaseProcessSupervisor` + `BaseSupervisor`** (`server/services/_supervisor/`) — the in-house supervisor base classes that `server/nodes/whatsapp/_runtime.py` also uses. Provides cross-platform signal handling (POSIX `setsid` + Windows Job Objects + `CREATE_NEW_PROCESS_GROUP` for graceful `CTRL_BREAK_EVENT` shutdown), restart policy via tenacity, log draining, status snapshots. We subclass both — zero custom supervisor logic.-**ServiceSpec wiring**: [`cli/commands/_temporal_specs.py`](../cli/commands/_temporal_specs.py) returns one ServiceSpec for the supervised Temporal dev server (env reads happen inside `temporal_specs()` at call time, safe to import before `cli.config.load_config()` runs). Both `start.py` and `dev.py` call it. The generic supervised-runtime shim lives at [`server/services/temporal/_supervised_runtime.py`](../server/services/temporal/_supervised_runtime.py) so the spawned `uv run python -m services.temporal._supervised_runtime services.temporal._runtime:get_temporal_server_runtime` resolves out of the workspace `.venv` without any cross-tree path plumbing.+**Lifecycle wiring (July 2026)**: backend-owned. `main.py`'s `_init_temporal_background` calls `TemporalServerRuntime.ensure_started()` before each connect attempt — a TCP probe on the gRPC port skips the spawn when a server (previously spawned or externally managed) is already listening, and non-loopback `TEMPORAL_SERVER_ADDRESS` values are never spawned at. Teardown rides the existing `shutdown_all_supervisors()` lifespan hook. The CLI no longer supervises Temporal: `cli/commands/_temporal_specs.py` and the `_supervised_runtime.py` shim were deleted (the shim was a full second server-venv Python process, ~81 MB resident, plus a ~28 MB resident `uv run` parent — pure supervision overhead).**WS surface**: `_handlers.py` registers `temporal_status` / `temporal_start` / `temporal_stop` via `services.ws_handler_registry.register_ws_handlers`. `_refresh.py` registers a WS-connect callback via `services.status_broadcaster.register_service_refresh` so the FE health indicator stays current.@@ -609,11 +609,9 @@ The Temporal binary + persistence are managed in-process by the plugin-folder pa| `temporal_graceful_shutdown_seconds` | `TEMPORAL_GRACEFUL_SHUTDOWN_SECONDS` | `30` | `CTRL_BREAK_EVENT` (Windows) / `SIGTERM` (POSIX) → tree-kill grace window. Shared with the embedded worker shutdown. || `temporal_terminate_running_on_startup` | `TEMPORAL_TERMINATE_RUNNING_ON_STARTUP` | `true` | Resumption toggle (see above). |-One supervisor-build-time env var (read inside `_temporal_specs.py`, not in `Settings`):-| Env var | `.env.template` default | Purpose ||---|---|---|-| `TEMPORAL_SERVER_READY_TIMEOUT_SECONDS` | `120` | How long the supervisor waits for Temporal's gRPC port to come up. Covers the first-run binary download (~114 MB) if `company build` didn't pre-cache. |+| `TEMPORAL_SERVER_READY_TIMEOUT_SECONDS` | `120` | Legacy knob from the CLI-supervised era (readiness wait for the gRPC port). Unused since the backend-owned cutover; retained in `.env.template` for config compatibility. |One temporary agent-engine cutover variable is also read directly rather thanthrough `Settings`:diff --git a/docs-internal/cli_services_integration.md b/docs-internal/cli_services_integration.mdindex 46267cb0..198f9c52 100644--- a/docs-internal/cli_services_integration.md+++ b/docs-internal/cli_services_integration.md@@ -18,7 +18,7 @@ Wraps the official `temporal` CLI's `server start-dev` mode (per [docs.temporal.**Install:** Automated. `company build` step [6/6] runs `python -m services.temporal._install`, which uses `pooch` to download the official CLI archive from `https://temporal.download/cli/archive/latest?platform=<os>&arch=<arch>` into `<DATA_DIR>/packages/temporal/` (= `~/.opencompany/packages/temporal/` by default, on every OS — via `core.paths.package_dir("temporal")`). No npm package, no system install required.-**Lifecycle:** Managed entirely by the CLI commands (`company start` / `company dev` / `company stop`) — there's no separate `temporal:start` npm script. The supervisor at [cli/supervisor.py](../cli/supervisor.py) spawns the official CLI via the supervised-runtime shim at [server/services/temporal/_supervised_runtime.py](../server/services/temporal/_supervised_runtime.py).+**Lifecycle:** Backend-owned (July 2026): the FastAPI lifespan starts the dev server via `TemporalServerRuntime.ensure_started()` ([server/services/temporal/_runtime.py](../server/services/temporal/_runtime.py)) when `TEMPORAL_ENABLED` and the configured address is loopback; `shutdown_all_supervisors()` stops it at shutdown. The CLI no longer supervises Temporal (the `_supervised_runtime.py` shim and `cli/commands/_temporal_specs.py` were deleted); `company stop` still frees the Temporal ports.**Ports (declared in `.env.template`, freed by `company stop`'s port-kill pre-flight):**| Service | Port | Env var |diff --git a/docs-internal/gcp_vm_deploy_runbook.md b/docs-internal/gcp_vm_deploy_runbook.mdindex b15ed527..ec91ff9a 100644--- a/docs-internal/gcp_vm_deploy_runbook.md+++ b/docs-internal/gcp_vm_deploy_runbook.md@@ -61,6 +61,10 @@ print('ENC='+secrets.token_hex(24))"single-port `serve` (API + WS + SPA, used by the Terraform path). This runbook'stested shape remains `company start` (static client on **:3000**, backend uvicornon **:3010**) plus an nginx reverse proxy on :80/:443 — it works on every release.+ **Releases after 0.0.95**: `company start` became single-port itself (uvicorn+ serves the SPA on :3010; no :3000 static server). When upgrading a VM past+ 0.0.95, change the nginx `location /` block to `proxy_pass http://127.0.0.1:3010;`+ (same target as `/api/`) and reload nginx.3. **Owner env seeding requires `>= 0.0.95`.** 0.0.88 ignored `MACHINA_OWNER_*`entirely. Since 0.0.95 the backend seeds the owner at startup from`OPENCOMPANY_OWNER_EMAIL` + `OPENCOMPANY_OWNER_PASSWORD` (>= 8 chars;diff --git a/docs-internal/release_build_pipeline.md b/docs-internal/release_build_pipeline.mdindex 1670ba62..d01363e8 100644--- a/docs-internal/release_build_pipeline.md+++ b/docs-internal/release_build_pipeline.md@@ -114,7 +114,7 @@ Idempotent on re-runs (compileall only rewrites stale pyc; esbuild is determinis4. `cd server && uv run python -m compileall -q -j 0 services` → plain `__pycache__/*.pyc` present (no `.opt-1.pyc` — nothing loads those).5. Cold-start: clean install + `company start > start.log 2>&1` → `Application startup complete` at ≤+50s (was +66.9s).6. `npm pack --dry-run` → `server/nodejs/dist/index.js` included; no `__pycache__/`; tarball size ≤ v0.0.76.-7. Smoke: `company start` → load http://localhost:3000 → run "AI Assistant" example → agent responds.+7. Smoke: `company start` → load http://localhost:3010 → run "AI Assistant" example → agent responds.## Out of scope (future work)diff --git a/scripts/postinstall.js b/scripts/postinstall.jsindex 889515f8..56070182 100755--- a/scripts/postinstall.js+++ b/scripts/postinstall.js@@ -128,7 +128,7 @@ async function main() {console.log('========================================');console.log('');console.log('Run: company start');- console.log('Open: http://localhost:3000');+ console.log('Open: http://localhost:3010');console.log('');} catch (err) {diff --git a/scripts/serve-client.js b/scripts/serve-client.jsdeleted file mode 100755index 01493951..00000000--- a/scripts/serve-client.js+++ /dev/null@@ -1,74 +0,0 @@-#!/usr/bin/env node-/**- * Simple static file server for pre-built client.- * Used in production mode when client dist exists but node_modules doesn't.- */-import { createServer } from 'http';-import { readFile } from 'fs';-import { join, extname } from 'path';-import { fileURLToPath } from 'url';-import { dirname, resolve } from 'path';--const __dirname = dirname(fileURLToPath(import.meta.url));-const DIST_DIR = resolve(__dirname, '..', 'client', 'dist');-const PORT = parseInt(process.env.VITE_CLIENT_PORT) || 3000;--const MIME_TYPES = {- '.html': 'text/html',- '.js': 'text/javascript',- '.css': 'text/css',- '.json': 'application/json',- '.png': 'image/png',- '.jpg': 'image/jpeg',- '.gif': 'image/gif',- '.svg': 'image/svg+xml',- '.ico': 'image/x-icon',- '.woff': 'font/woff',- '.woff2': 'font/woff2',- '.ttf': 'font/ttf',-};--const server = createServer((req, res) => {- let url = req.url === '/' ? '/index.html' : req.url;-- // Remove query string- url = url.split('?')[0];-- const filePath = resolve(DIST_DIR, '.' + url);-- // Prevent path traversal outside DIST_DIR- if (!filePath.startsWith(DIST_DIR)) {- res.writeHead(403);- res.end('Forbidden');- return;- }-- readFile(filePath, (err, content) => {- if (err) {- // SPA fallback - serve index.html for routes- if (err.code === 'ENOENT' && !extname(url)) {- readFile(join(DIST_DIR, 'index.html'), (err2, indexContent) => {- if (err2) {- res.writeHead(404);- res.end('Not found');- } else {- res.writeHead(200, { 'Content-Type': 'text/html' });- res.end(indexContent);- }- });- } else {- res.writeHead(404);- res.end('Not found');- }- } else {- const ext = extname(filePath);- const contentType = MIME_TYPES[ext] || 'application/octet-stream';- res.writeHead(200, { 'Content-Type': contentType });- res.end(content);- }- });-});--server.listen(PORT, '0.0.0.0', () => {- console.log(`Client: http://localhost:${PORT}`);-});diff --git a/server/main.py b/server/main.pyindex 1267976b..28c7446f 100644--- a/server/main.py+++ b/server/main.py@@ -59,7 +59,7 @@ _startup_log("Importing DI container + all services...")from core.container import container_startup_log("Importing routers...")-from routers import workflow, database, nodejs_compat, websocket, webhook, auth, credentials, schemas+from routers import workflow, database, websocket, webhook, auth, credentials, schemas_startup_log("All imports complete")@@ -138,7 +138,6 @@ async def lifespan(app: FastAPI):modules=["routers.workflow","routers.database",- "routers.nodejs_compat","routers.websocket","routers.webhook","routers.auth",@@ -327,9 +326,22 @@ async def lifespan(app: FastAPI):unwired after an initial failed connect."""temporal_client_wrapper = container.temporal_client()+ # Loopback address => this process owns the SQLite dev server,+ # via the same BaseSupervisor singleton pattern as the WhatsApp+ # runtime (teardown is covered by shutdown_all_supervisors()).+ # Remote/production clusters are never spawned at.+ _tp_host = settings.temporal_server_address.rsplit(":", 1)[0].strip("[]")+ _owns_dev_server = _tp_host in ("localhost", "127.0.0.1", "::1")attempt = 0while True:attempt += 1+ if _owns_dev_server:+ from services.temporal._runtime import get_temporal_server_runtime++ try:+ await get_temporal_server_runtime().ensure_started()+ except Exception as dev_exc: # noqa: BLE001 — connect loop retries+ _startup_log(f"[Temporal] Dev server start failed (attempt {attempt}): {dev_exc}")client = await temporal_client_wrapper.connect(retries=1, delay=0)if client is None:# Surface every failed attempt to stdout so users can see@@ -595,7 +607,6 @@ app.add_middleware(# folder's ``__init__.py`` and are mounted via the loop below — main.py# never imports a migrated plugin module by name.app.include_router(auth.router) # Auth routes (login, register, logout, status)-app.include_router(nodejs_compat.router) # Node.js compatibility (includes root endpoints)app.include_router(workflow.router)app.include_router(database.router)app.include_router(websocket.router)@@ -720,11 +731,11 @@ async def health_check():# Single-port SPA serving (container / Cloud Run)# ---------------------------------------------------------------------------#-# In the containerised deployment one uvicorn process must front the API,-# the WebSocket, AND the built React client on a single port ($PORT). The-# CLI dev/start path serves the client from a separate node static server-# (scripts/serve-client.js), so this block is gated on the dist existing +-# SERVE_STATIC_CLIENT so local ``company dev`` is unaffected.+# One uvicorn process fronts the API, the WebSocket, AND the built React+# client. This is the only static-serving path: ``company start`` and the+# containerised deployment both rely on it (``company dev`` uses Vite for+# HMR instead). Gated on the dist existing + SERVE_STATIC_CLIENT (default+# on) so a dist-less dev checkout is unaffected.## Registered LAST so every real API / WS / mounted route above wins; this# only catches otherwise-unmatched GET paths and returns the SPA shell for@@ -740,18 +751,8 @@ _SERVE_STATIC = _spa_os.environ.get("SERVE_STATIC_CLIENT", "true").lower() in ("_NON_SPA_PREFIXES = ("api/", "ws/", "webhook/", "mcp/", "health", "docs", "redoc", "openapi.json")if _SERVE_STATIC and (_CLIENT_DIST / "index.html").is_file():- # The nodejs-compat router registers an informational ``GET /`` JSON shim- # that would shadow the SPA at the root. In the container the SPA must own- # "/", so drop that single route before installing the fallback. Its- # ``/api/*`` routes are untouched.- from starlette.routing import Route as _Route-- app.router.routes = [- _r- for _r in app.router.routes- if not (isinstance(_r, _Route) and _r.path == "/" and "GET" in (_r.methods or set()))- ]-+ # The SPA owns "/" — no other GET "/" route exists (the legacy+ # nodejs-compat router that used to shadow it was removed entirely)._assets_dir = _CLIENT_DIST / "assets"if _assets_dir.is_dir():app.mount("/assets", StaticFiles(directory=str(_assets_dir)), name="assets")diff --git a/server/routers/nodejs_compat.py b/server/routers/nodejs_compat.pydeleted file mode 100644index 6a20a0f1..00000000--- a/server/routers/nodejs_compat.py+++ /dev/null@@ -1,229 +0,0 @@-"""Node.js API compatibility routes for seamless migration."""--from datetime import datetime-from uuid import uuid4-from fastapi import APIRouter, HTTPException, Depends-from pydantic import BaseModel-from typing import Dict, Any, List, Optional--from core.container import container-from core.database import Database-from services.workflow import WorkflowService-from core.logging import get_logger--logger = get_logger(__name__)-router = APIRouter(tags=["nodejs-compatibility"])---# Pydantic models matching Node.js API-class NodeExecuteRequest(BaseModel):- nodeId: str- nodeType: str- parameters: Optional[Dict[str, Any]] = {}- nodes: Optional[List[Dict[str, Any]]] = []- edges: Optional[List[Dict[str, Any]]] = []---class WorkflowSaveRequest(BaseModel):- name: str- data: Dict[str, Any]---# Health and status endpoints[email protected]("/")-async def root():- """Node.js compatible root endpoint."""- return {- "message": "React Flow Project API Server",- "status": "running",- "version": "2.0.0-python",- "endpoints": {"health": "/api/health", "workflows": "/api/workflows", "nodes": "/api/nodes", "execute": "/api/nodes/execute"},- "services": {"main": "http://localhost:3010", "python": "http://localhost:3010"},- "timestamp": datetime.now().isoformat(),- }--[email protected]("/api/health")-async def health_check():- """Node.js compatible health check."""- return {"status": "OK", "message": "React Flow Server is running", "timestamp": datetime.now().isoformat()}---# Workflow management endpoints[email protected]("/api/workflows")-async def get_workflows(database: Database = Depends(lambda: container.database())):- """Get all workflows (Node.js compatible)."""- try:- workflows = await database.get_all_workflows()- return {"workflows": workflows}- except Exception as e:- logger.error("Failed to get workflows", error=str(e))- return {"workflows": []}--[email protected]("/api/workflows")-async def save_workflow(request: WorkflowSaveRequest, database: Database = Depends(lambda: container.database())):- """Save workflow (Node.js compatible)."""- try:- workflow_id = str(int(datetime.now().timestamp() * 1000)) # Node.js style ID- success = await database.save_workflow(workflow_id=workflow_id, name=request.name, data=request.data)-- if success:- return {"success": True, "id": workflow_id, "message": "Workflow saved successfully"}- else:- raise HTTPException(status_code=500, detail="Failed to save workflow")-- except Exception as e:- logger.error("Failed to save workflow", error=str(e))- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/api/workflows/{workflow_id}")-async def get_workflow(workflow_id: str, database: Database = Depends(lambda: container.database())):- """Get workflow by ID (Node.js compatible)."""- try:- workflow = await database.get_workflow(workflow_id)-- if workflow:- return {"id": workflow.id, "name": workflow.name, "data": workflow.data}- else:- return {"id": workflow_id, "name": "Sample Workflow", "data": {"nodes": [], "edges": []}}-- except Exception as e:- logger.error("Failed to get workflow", workflow_id=workflow_id, error=str(e))- return {"id": workflow_id, "name": "Sample Workflow", "data": {"nodes": [], "edges": []}}---# Main execution endpoint - Node.js compatible[email protected]("/api/nodes/execute")-async def execute_node(request: NodeExecuteRequest, workflow_service: WorkflowService = Depends(lambda: container.workflow_service())):- """Execute a single node (Node.js compatible)."""- try:- if not request.nodeId or not request.nodeType:- raise HTTPException(status_code=400, detail="nodeId and nodeType are required")-- execution_id = str(uuid4())- logger.info("Executing node", node_id=request.nodeId, execution_id=execution_id)-- # Execute the node using workflow service- result = await workflow_service.execute_node(- node_id=request.nodeId,- node_type=request.nodeType,- parameters=request.parameters or {},- nodes=request.nodes or [],- edges=request.edges or [],- session_id="default",- execution_id=execution_id,- )-- # Transform result to match Node.js format- if result.get("success"):- return {- "success": True,- "executionId": execution_id,- "nodeId": request.nodeId,- "nodeType": request.nodeType,- "result": result.get("result", {}),- "executionTime": result.get("execution_time", 0),- "timestamp": result.get("timestamp", datetime.now().isoformat()),- }- else:- return {- "success": False,- "executionId": execution_id,- "nodeId": request.nodeId,- "nodeType": request.nodeType,- "error": result.get("error", "Unknown error"),- "executionTime": result.get("execution_time", 0),- "timestamp": result.get("timestamp", datetime.now().isoformat()),- }-- except Exception as e:- logger.error("Node execution error", node_id=request.nodeId, error=str(e))- raise HTTPException(status_code=500, detail=str(e))---# Execution status and output endpoints[email protected]("/api/executions/{execution_id}")-async def get_execution_status(execution_id: str):- """Get execution status (Node.js compatible)."""- # For simplicity, return success status- # In a full implementation, you'd track execution status- return {"success": True, "executionId": execution_id, "status": "completed", "timestamp": datetime.now().isoformat()}--[email protected]("/api/nodes/{node_id}/output")-async def get_node_output(node_id: str, workflow_service: WorkflowService = Depends(lambda: container.workflow_service())):- """Get node output data (Node.js compatible)."""- try:- result = await workflow_service.get_workflow_node_output(node_id)-- if result.get("success"):- return {"success": True, "nodeId": node_id, "output": result.get("data", {})}- else:- return {"success": False, "nodeId": node_id, "error": result.get("error", "Node output not found")}-- except Exception as e:- logger.error("Get node output error", node_id=node_id, error=str(e))- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/api/executions/clear")-async def clear_execution_cache():- """Clear execution cache (Node.js compatible)."""- try:- # Clear workflow service cache if implemented- return {"success": True, "message": "Execution cache cleared"}- except Exception as e:- logger.error("Clear cache error", error=str(e))- raise HTTPException(status_code=500, detail=str(e))---# Legacy endpoint for backwards compatibility[email protected]("/api/execute/{node_id}")-async def legacy_execute_node(- node_id: str, request: Dict[str, Any], workflow_service: WorkflowService = Depends(lambda: container.workflow_service())-):- """Legacy execution endpoint (Node.js compatible)."""- try:- node_type = request.get("nodeType")- if not node_type:- raise HTTPException(status_code=400, detail="nodeType is required")-- execution_id = str(uuid4())-- result = await workflow_service.execute_node(- node_id=node_id,- node_type=node_type,- parameters=request.get("parameters", {}),- nodes=request.get("nodes", []),- edges=request.get("edges", []),- session_id="default",- execution_id=execution_id,- )-- # Return in Node.js format- if result.get("success"):- return {- "success": True,- "executionId": execution_id,- "nodeId": node_id,- "nodeType": node_type,- "result": result.get("result", {}),- "executionTime": result.get("execution_time", 0),- "timestamp": result.get("timestamp", datetime.now().isoformat()),- }- else:- return {- "success": False,- "executionId": execution_id,- "nodeId": node_id,- "nodeType": node_type,- "error": result.get("error", "Unknown error"),- "executionTime": result.get("execution_time", 0),- "timestamp": result.get("timestamp", datetime.now().isoformat()),- }-- except Exception as e:- logger.error("Legacy execution error", node_id=node_id, error=str(e))- raise HTTPException(status_code=500, detail=str(e))diff --git a/server/services/temporal/_runtime.py b/server/services/temporal/_runtime.pyindex 1216a5b8..a2e382a5 100644--- a/server/services/temporal/_runtime.py+++ b/server/services/temporal/_runtime.py@@ -177,6 +177,17 @@ class TemporalServerRuntime(BaseProcessSupervisor):# OpenCompany uses for every other supervised TCP service.return await _probe_tcp_port(self.settings.temporal_frontend_grpc_port)+ async def ensure_started(self) -> None:+ """Start the dev server unless the gRPC port is already served.++ A listening port means either a previously spawned instance or an+ externally managed Temporal server — both are left alone. Idempotent+ like ``start()``; callers may invoke it on every reconnect attempt.+ """+ if await _probe_tcp_port(self.settings.temporal_frontend_grpc_port):+ return+ await self.start()+def _extra_status(self) -> dict[str, Any]:base = super()._extra_status()return {diff --git a/server/services/temporal/_supervised_runtime.py b/server/services/temporal/_supervised_runtime.pydeleted file mode 100644index 0fb9d69e..00000000--- a/server/services/temporal/_supervised_runtime.py+++ /dev/null@@ -1,102 +0,0 @@-"""Generic bridge: run any ``BaseSupervisor`` singleton from a CLI.--The CLI's ``Manager`` supervisor (``cli/supervisor.py``) schedules-``ServiceSpec`` entries by spawning a subprocess and supervising it.-``BaseSupervisor``-managed runtimes (e.g. the Temporal CLI dev server)-don't ship a CLI of their own -- they're Python singletons started via-``await runtime.start()``.--This shim bridges the two: import a runtime factory by dotted path,-call it, ``await singleton.start()``, then block on a shutdown signal.-``Manager`` sends SIGTERM during graceful shutdown; we catch it,-``await singleton.stop()``, then exit cleanly.--Module location: this lives inside the ``server`` package because the-factory targets it resolves-(``services.temporal._runtime:get_temporal_server_runtime``) are-server-side singletons. Hosting the shim here keeps the CLI free of-server-side imports and lets a single ``uv run python -m-services.temporal._supervised_runtime <factory>`` invocation work-against the workspace ``.venv`` -- no PYTHONPATH composition, no-cross-venv plumbing.--Invocation (inside ``ServiceSpec.argv``, built via ``cli.run.uv_run``):-- uv_run("python", "-m",- "services.temporal._supervised_runtime",- "services.temporal._runtime:get_temporal_server_runtime")--Equivalent to (Python idiom):-- from services.temporal._runtime import get_temporal_server_runtime- runtime = get_temporal_server_runtime()- await runtime.start()- await asyncio.Event().wait() # block on signal-"""--from __future__ import annotations--import asyncio-import importlib-import signal-import sys-from typing import Awaitable, Callable---def _resolve(dotted: str) -> Callable[[], Awaitable[None]]:- """Resolve ``module.path:attr`` to a callable factory."""- if ":" not in dotted:- raise SystemExit(f"factory must be 'module.path:attr', got {dotted!r}")- mod_path, attr = dotted.split(":", 1)- mod = importlib.import_module(mod_path)- factory = getattr(mod, attr, None)- if factory is None:- raise SystemExit(f"{mod_path}.{attr} not found")- return factory---async def _run(factory_dotted: str) -> int:- factory = _resolve(factory_dotted)- runtime = factory()- stop = asyncio.Event()-- def _on_signal() -> None:- if not stop.is_set():- stop.set()-- loop = asyncio.get_running_loop()- for sig in (signal.SIGINT, signal.SIGTERM):- try:- loop.add_signal_handler(sig, _on_signal)- except NotImplementedError:- # Windows: add_signal_handler raises for SIGTERM. The- # Manager supervisor's tree-kill semantics (psutil-based)- # work regardless -- we just lose the graceful path on Win.- pass-- print(f"[supervised_runtime] starting {factory_dotted}", flush=True)- try:- await runtime.start()- print(f"[supervised_runtime] {factory_dotted} ready", flush=True)- await stop.wait()- finally:- print(f"[supervised_runtime] stopping {factory_dotted}", flush=True)- await runtime.stop()- return 0---def main() -> int:- if len(sys.argv) != 2:- print(- "usage: python -m services.temporal._supervised_runtime " "<module.path:factory>",- file=sys.stderr,- )- return 2- try:- return asyncio.run(_run(sys.argv[1]))- except KeyboardInterrupt:- return 0---if __name__ == "__main__":- raise SystemExit(main())diff --git a/server/tests/test_no_raw_prints.py b/server/tests/test_no_raw_prints.pyindex e29b5b08..0c6c5ea8 100644--- a/server/tests/test_no_raw_prints.py+++ b/server/tests/test_no_raw_prints.py@@ -45,13 +45,9 @@ _SANCTIONED: List[Tuple[str, str]] = [("main.py", "_startup_log"),("core/container.py", "_clog"),("nodes/code/python_executor/__init__.py", "captured_print"),- # Temporal CLI shims — supervised subprocess + build-time installer.- # These run BEFORE the structlog pipeline is configured in their own- # subprocess (same role as ``_startup_log`` / ``_clog`` for the main- # process). Stdout markers are consumed by the supervisor's- # line-prefixer (``cli/colors.py``), which adds the timestamp tag.- ("services/temporal/_supervised_runtime.py", "_run"),- ("services/temporal/_supervised_runtime.py", "main"),+ # Build-time Temporal installer — runs in its own one-shot subprocess+ # BEFORE the structlog pipeline is configured (same role as+ # ``_startup_log`` / ``_clog`` for the main process).("services/temporal/_install.py", "_main"),]@@ -87,8 +83,7 @@ def _enclosing_function_name(tree: ast.AST, target: ast.AST) -> str:def test_no_raw_prints_in_server_code() -> None:"""Every ``print(`` call in server runtime code is in an allow-listed body."""- # Multimap: a single module may sanction multiple entry-point bodies- # (e.g. ``_supervised_runtime`` has both ``_run`` and ``main``).+ # Multimap: a single module may sanction multiple entry-point bodies.sanctioned_map: dict[str, set[str]] = {}for rel, fn in _SANCTIONED:sanctioned_map.setdefault(rel.replace("\\", "/"), set()).add(fn)diff --git a/server/tests/test_plugin_self_containment.py b/server/tests/test_plugin_self_containment.pyindex 718fb742..da988fbb 100644--- a/server/tests/test_plugin_self_containment.py+++ b/server/tests/test_plugin_self_containment.py@@ -141,9 +141,10 @@ class TestNoPluginRouterOutsideNodes:``nodes/<plugin>/_router.py`` -- never in ``server/routers/``.``server/routers/`` is reserved for cross-cutting routers- (auth, websocket, webhook, workflow, database, maps,- nodejs_compat, schemas, credentials). Maps/webhook are recorded- here as still-shared dispatchers pending a future design pass.+ (auth, websocket, webhook, workflow, database, schemas,+ credentials). Webhook is recorded here as a still-shared+ dispatcher pending a future design pass. The legacy nodejs_compat+ router was deleted in the July 2026 trim (nothing consumed it)."""_MUST_NOT_EXIST = (@@ -296,8 +297,8 @@ class TestStaleServiceFilesAbsent:class TestMainPyDoesNotMountPluginRouters:"""``server/main.py`` mounts framework routers explicitly- (auth / websocket / workflow / database / maps / nodejs_compat /- schemas / credentials / webhook). Plugin routers flow in via the+ (auth / websocket / workflow / database / schemas / credentials /+ webhook). Plugin routers flow in via the``for r in get_routers(): app.include_router(r)`` loop.Direct ``app.include_router(<plugin>.router)`` calls or