Skip to content

Self-improving AI Employees for everyone

test(build): cover compile-pipeline + release-config contracts (44 tests)

trohitg0f1e55e4f342
diff --git a/machina/commands/build.py b/machina/commands/build.py
index 42cd6d67..0504068b 100644
--- a/machina/commands/build.py
+++ b/machina/commands/build.py
@@ -23,6 +23,25 @@ from machina.colors import console
from machina.platform_ import project_root
+# Source dirs / entry-point modules under ``server/`` that ``machina build``
+# pre-compiles to optimised bytecode in step [5/6]. Public so tests and
+# ``scripts/install.js`` (which mirrors this list) stay in sync — both
+# the install pipeline and tests should read this constant rather than
+# duplicate the list. Excludes ``.venv/`` (uv compiles deps at install
+# time and some site-packages contain non-Python templates) and
+# ``tests/`` (ships outside the production tarball).
+COMPILEALL_SOURCE_DIRS: tuple[str, ...] = (
+ "services",
+ "core",
+ "nodes",
+ "routers",
+ "models",
+ "middleware",
+ "main.py",
+ "constants.py",
+)
+
+
# ---------------------------------------------------------------- helpers
def _which_python() -> str | None:
@@ -175,9 +194,8 @@ def build_command() -> None:
# tarball. Compiling `.venv/` is wasted work and fails on cookiecutter
# template files inside packages like crawlee that aren't real Python.
console.log("[5/6] Compiling Python bytecode...")
- source_dirs = ["services", "core", "nodes", "routers", "models", "middleware", "main.py", "constants.py"]
run(
- ["uv", "run", "python", "-O", "-m", "compileall", "-q", "-j", "0", *source_dirs],
+ ["uv", "run", "python", "-O", "-m", "compileall", "-q", "-j", "0", *COMPILEALL_SOURCE_DIRS],
cwd=server_dir,
check=False, # missing pyc is non-fatal — runtime regenerates as needed
)
diff --git a/machina/tests/conftest.py b/machina/tests/conftest.py
new file mode 100644
index 00000000..3be82659
--- /dev/null
+++ b/machina/tests/conftest.py
@@ -0,0 +1,68 @@
+"""Shared fixtures for ``machina`` tests.
+
+The release-pipeline config tests need to read files that live in
+pnpm workspace members (``client/``, ``server/nodejs/``) without
+hardcoding those filesystem paths in every test. The canonical
+oracle for "where does workspace X live" is pnpm itself:
+
+ pnpm list --json --only-projects --recursive --depth 0
+
+That returns every workspace member's name + absolute path. We invoke
+it once per test session and expose the result as a name → path map.
+
+Tests then reference workspaces by their npm package name (a stable
+identifier defined in each ``package.json``) rather than by path. If
+``server/nodejs/`` is later renamed or moved, the test suite keeps
+working — pnpm resolves the new location.
+
+For files that don't live inside a workspace (``.github/workflows``,
+``scripts/install.js``), tests resolve via the ``root`` fixture which
+points at ``machina.platform_.project_root()`` — the project's own
+canonical worktree-aware helper.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from machina.platform_ import project_root
+from machina.run import which_argv
+
+
[email protected](scope="session")
+def root() -> Path:
+ """The project root, resolved via ``machina.platform_.project_root``."""
+ return project_root()
+
+
[email protected](scope="session")
+def workspace_members(root: Path) -> dict[str, Path]:
+ """Map of pnpm workspace member name → absolute filesystem path.
+
+ Resolved once per session by shelling out to ``pnpm``. The ``--depth 0``
+ + ``--only-projects`` flags trim the output to just workspace members
+ (no transitive npm deps). Skips with a clear message if pnpm isn't
+ installed so the rest of the suite remains runnable.
+
+ Reference: https://pnpm.io/cli/list
+ """
+ # which_argv resolves Windows .cmd / .bat shims via PATHEXT — the
+ # same helper machina.run uses everywhere else for the same reason.
+ argv = which_argv(["pnpm", "list", "--json", "--only-projects",
+ "--recursive", "--depth", "0"])
+ try:
+ out = subprocess.run(
+ argv,
+ cwd=root,
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ except (FileNotFoundError, subprocess.CalledProcessError) as e:
+ pytest.skip(f"pnpm workspace listing unavailable ({e}); skipping config tests")
+ members = json.loads(out.stdout)
+ return {m["name"]: Path(m["path"]) for m in members}
diff --git a/machina/tests/test_build_compile_pipeline.py b/machina/tests/test_build_compile_pipeline.py
new file mode 100644
index 00000000..9bb88cbf
--- /dev/null
+++ b/machina/tests/test_build_compile_pipeline.py
@@ -0,0 +1,280 @@
+"""Tests for the compile-pipeline additions to ``machina build``.
+
+Covers the two new steps wired into ``machina.commands.build.build_command``:
+
+- ``[3/6] Building Node.js sidecar`` -> ``pnpm --filter machinaos-nodejs-executor run build``
+- ``[5/6] Compiling Python bytecode`` -> ``uv run python -O -m compileall -q -j 0 ...``
+
+The orchestrator is exercised once per test with every external surface
+mocked (toolchain probes, ``run``, ``project_root``) so the assertions
+focus on *which* commands fire, in what *order*, and with the right
+*flags* — not on subprocess behaviour. ``test_build.py`` already covers
+the underlying ``run`` and ``capture`` helpers in isolation.
+
+The set of source dirs that compileall walks comes from the public
+``build.COMPILEALL_SOURCE_DIRS`` constant — tests reference that
+constant rather than duplicating the list, so a future addition flows
+to the assertion automatically.
+
+Refer to ``docs-internal/release_build_pipeline.md`` for context.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Callable
+from unittest.mock import patch
+
+from machina.commands import build
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _seed_edgymeow_binary(tmp_path: Path) -> None:
+ """Create a fake edgymeow binary so the [6/6] verify step doesn't warn.
+
+ The verify step only stat()s the file; the contents are never read.
+ """
+ bin_dir = tmp_path / "node_modules" / "edgymeow" / "bin"
+ bin_dir.mkdir(parents=True, exist_ok=True)
+ bin_name = "edgymeow-server.exe" if build.sys.platform == "win32" else "edgymeow-server"
+ (bin_dir / bin_name).write_text("")
+
+
+def _run_build_capture_invocations(tmp_path: Path) -> list[dict]:
+ """Run ``build_command()`` with all external I/O mocked.
+
+ Returns a list of dicts ``{"argv": [...], **kwargs}`` — one per call
+ to ``machina.run.run`` — in the order the orchestrator emitted them.
+ Preserving kwargs lets tests assert ``check=False`` and ``cwd=...``.
+ """
+ _seed_edgymeow_binary(tmp_path)
+ captured: list[dict] = []
+
+ def fake_run(argv, **kwargs):
+ captured.append({"argv": list(argv), **kwargs})
+ return 0
+
+ def fake_capture(argv):
+ # ``_check_python`` parses for major.minor and needs Python 3.12+.
+ if argv and argv[0].startswith("python"):
+ return "Python 3.12.5"
+ return "v1.0.0"
+
+ with patch.object(build, "run", side_effect=fake_run), \
+ patch.object(build, "capture", side_effect=fake_capture), \
+ patch.object(build, "_which_python", return_value="python"), \
+ patch.object(build, "_ensure_uv"), \
+ patch.object(build, "_ensure_temporal"), \
+ patch.object(build, "project_root", return_value=tmp_path):
+ build.build_command()
+
+ return captured
+
+
+def _find_call(
+ captured: list[dict], predicate: Callable[[list[str]], bool]
+) -> tuple[int, dict] | None:
+ """First (index, call-dict) pair matching the predicate, or ``None``."""
+ for idx, call in enumerate(captured):
+ if predicate(call["argv"]):
+ return idx, call
+ return None
+
+
+# ---------------------------------------------------------------------------
+# COMPILEALL_SOURCE_DIRS constant
+# ---------------------------------------------------------------------------
+
+def test_source_dirs_constant_excludes_venv_and_tests():
+ """The bytecode-compile path list must skip ``.venv/`` and
+ ``tests/``: ``.venv/`` is wasted work (uv compiles deps at install
+ time, plus packages like crawlee ship non-Python cookiecutter
+ templates that would log spurious errors), and ``tests/`` ships
+ outside the production tarball.
+ """
+ assert ".venv" not in build.COMPILEALL_SOURCE_DIRS
+ assert "tests" not in build.COMPILEALL_SOURCE_DIRS
+ assert "." not in build.COMPILEALL_SOURCE_DIRS
+
+
+def test_source_dirs_constant_covers_runtime_modules():
+ """Whatever's in this list is the surface area the runtime imports
+ at startup. If a new top-level package or entry-point module is
+ added to ``server/`` and the runtime imports it, it should be in
+ this list — otherwise that code pays bytecode-compile cost on
+ first import in production.
+ """
+ # Core dirs that the runtime always imports at startup. Anyone
+ # adding a new top-level dir under server/ that's imported on
+ # boot should add it to COMPILEALL_SOURCE_DIRS too.
+ must_include = {"services", "core", "nodes", "routers", "models", "middleware"}
+ actual = set(build.COMPILEALL_SOURCE_DIRS)
+ missing = must_include - actual
+ assert not missing, f"COMPILEALL_SOURCE_DIRS missing required dirs: {missing}"
+ # And the entry-point modules.
+ assert "main.py" in actual
+ assert "constants.py" in actual
+
+
+# ---------------------------------------------------------------------------
+# Sidecar bundle step ([3/6])
+# ---------------------------------------------------------------------------
+
+def test_build_invokes_sidecar_pnpm_filter(tmp_path: Path):
+ """[3/6] Build Node.js sidecar via the package's ``build`` script."""
+ captured = _run_build_capture_invocations(tmp_path)
+ match = _find_call(
+ captured,
+ lambda c: c[:1] == ["pnpm"] and "--filter" in c and "machinaos-nodejs-executor" in c,
+ )
+ assert match is not None, (
+ "expected `pnpm --filter machinaos-nodejs-executor run build` in "
+ f"{[c['argv'] for c in captured]}"
+ )
+ argv = match[1]["argv"]
+ assert "run" in argv and "build" in argv, (
+ f"sidecar step must invoke the `build` script, got {argv}"
+ )
+
+
+def test_sidecar_build_runs_after_client_build(tmp_path: Path):
+ """Sidecar bundle runs AFTER the client build (the workspace install
+ + client build populate ``server/nodejs/node_modules`` with esbuild
+ first).
+ """
+ captured = _run_build_capture_invocations(tmp_path)
+ client = _find_call(captured, lambda c: "react-flow-client" in c)
+ sidecar = _find_call(captured, lambda c: "machinaos-nodejs-executor" in c)
+ assert client is not None and sidecar is not None
+ assert client[0] < sidecar[0], (
+ f"client build idx {client[0]} must precede sidecar bundle idx {sidecar[0]}"
+ )
+
+
+def test_only_one_sidecar_bundle_invocation(tmp_path: Path):
+ """Sidecar bundle must fire exactly once per build."""
+ captured = _run_build_capture_invocations(tmp_path)
+ matches = [c for c in captured if "machinaos-nodejs-executor" in c["argv"]]
+ assert len(matches) == 1, f"expected exactly 1 sidecar bundle, got {len(matches)}"
+
+
+# ---------------------------------------------------------------------------
+# Python bytecode compile step ([5/6])
+# ---------------------------------------------------------------------------
+
+def test_compileall_uses_optimised_flag_quiet_and_parallel(tmp_path: Path):
+ """``-O`` strips asserts; ``-q`` silences per-file output; ``-j 0``
+ parallelises across all CPU cores.
+ """
+ captured = _run_build_capture_invocations(tmp_path)
+ match = _find_call(captured, lambda c: "compileall" in c)
+ assert match is not None, (
+ f"compileall step missing in {[c['argv'] for c in captured]}"
+ )
+ argv = match[1]["argv"]
+ assert "-O" in argv, "must use -O for .opt-1.pyc output"
+ assert "-q" in argv, "must use -q to silence per-file logging"
+ assert "-j" in argv, "must enable parallelism via -j"
+ j_idx = argv.index("-j")
+ assert argv[j_idx + 1] == "0", "-j 0 means 'use all CPU cores'"
+
+
+def test_compileall_runs_via_uv_run_python(tmp_path: Path):
+ """Compileall must use ``uv run python`` so the project's pinned
+ interpreter is used regardless of what ``python`` is on PATH.
+ """
+ captured = _run_build_capture_invocations(tmp_path)
+ match = _find_call(captured, lambda c: "compileall" in c)
+ assert match is not None
+ argv = match[1]["argv"]
+ assert argv[:5] == ["uv", "run", "python", "-O", "-m"], (
+ f"expected `uv run python -O -m compileall ...`, got {argv[:6]}"
+ )
+
+
+def test_compileall_path_list_matches_source_dirs_constant(tmp_path: Path):
+ """The argv passed to compileall must end with exactly the dirs +
+ modules listed in ``COMPILEALL_SOURCE_DIRS`` — no fewer (would skip
+ boot-imported code), no more (would re-introduce ``.venv/`` /
+ ``tests/`` regression).
+ """
+ captured = _run_build_capture_invocations(tmp_path)
+ match = _find_call(captured, lambda c: "compileall" in c)
+ assert match is not None
+ argv = match[1]["argv"]
+ # Trailing args after `-j 0` are the path list.
+ j_idx = argv.index("-j")
+ paths_passed = tuple(argv[j_idx + 2:])
+ assert paths_passed == build.COMPILEALL_SOURCE_DIRS, (
+ f"compileall args drift: build_command passed {paths_passed!r}, "
+ f"constant says {build.COMPILEALL_SOURCE_DIRS!r}"
+ )
+
+
+def test_compileall_runs_in_server_dir(tmp_path: Path):
+ """Compileall's ``cwd`` must be ``server/`` so the relative paths
+ in COMPILEALL_SOURCE_DIRS (``services``, ``main.py``, etc.) resolve.
+ """
+ captured = _run_build_capture_invocations(tmp_path)
+ match = _find_call(captured, lambda c: "compileall" in c)
+ assert match is not None
+ call = match[1]
+ assert call.get("cwd") == tmp_path / "server", (
+ f"compileall must cwd into server/, got {call.get('cwd')}"
+ )
+
+
+def test_compileall_is_non_fatal(tmp_path: Path):
+ """Missing or unparseable Python files in the path list must NOT
+ fail the build — the runtime regenerates pyc on first import. The
+ step must pass ``check=False`` so a borderline file in a future
+ source dir doesn't block the rest of the build.
+ """
+ captured = _run_build_capture_invocations(tmp_path)
+ match = _find_call(captured, lambda c: "compileall" in c)
+ assert match is not None
+ call = match[1]
+ assert call.get("check") is False, (
+ "compileall must pass check=False so a malformed source file "
+ "doesn't block the rest of the build"
+ )
+
+
+def test_only_one_compileall_invocation(tmp_path: Path):
+ """The orchestrator must compile bytecode exactly once per build."""
+ captured = _run_build_capture_invocations(tmp_path)
+ matches = [c for c in captured if "compileall" in c["argv"]]
+ assert len(matches) == 1, f"expected exactly 1 compileall call, got {len(matches)}"
+
+
+# ---------------------------------------------------------------------------
+# Step ordering invariants
+# ---------------------------------------------------------------------------
+
+def test_pipeline_order_client_then_sidecar_then_uv_then_compileall(tmp_path: Path):
+ """Full ordering invariant for the new pipeline:
+
+ 1. client build (``pnpm --filter react-flow-client run build``)
+ 2. sidecar bundle (``pnpm --filter machinaos-nodejs-executor run build``)
+ 3. uv sync (``uv sync``)
+ 4. compileall (``uv run python -O -m compileall ...``)
+
+ compileall MUST follow uv sync because it invokes ``uv run python``,
+ which requires the venv to exist.
+ """
+ captured = _run_build_capture_invocations(tmp_path)
+ client = _find_call(captured, lambda c: "react-flow-client" in c)
+ sidecar = _find_call(captured, lambda c: "machinaos-nodejs-executor" in c)
+ uv_sync = _find_call(captured, lambda c: c[:2] == ["uv", "sync"])
+ compileall = _find_call(captured, lambda c: "compileall" in c)
+ for label, match in (("client", client), ("sidecar", sidecar),
+ ("uv_sync", uv_sync), ("compileall", compileall)):
+ assert match is not None, f"missing pipeline step: {label}"
+ indices = [client[0], sidecar[0], uv_sync[0], compileall[0]]
+ assert indices == sorted(indices), (
+ f"pipeline order broken: client={client[0]} sidecar={sidecar[0]} "
+ f"uv_sync={uv_sync[0]} compileall={compileall[0]}"
+ )
diff --git a/machina/tests/test_release_pipeline_config.py b/machina/tests/test_release_pipeline_config.py
new file mode 100644
index 00000000..61aa6b81
--- /dev/null
+++ b/machina/tests/test_release_pipeline_config.py
@@ -0,0 +1,391 @@
+"""Config-file assertions for the release-build pipeline.
+
+These tests guard contracts that ``test_build_compile_pipeline.py``
+can't cover from Python — the configuration of sibling tools (Vite,
+TypeScript, esbuild, GitHub Actions, ``scripts/install.js``).
+
+Reused infrastructure (no path strings duplicated across tests):
+
+ ``conftest.workspace_members`` → name → Path map from ``pnpm list``
+ ``conftest.root`` → project_root() for top-level files
+ ``machina.commands.build.COMPILEALL_SOURCE_DIRS``
+ → SSOT for the bytecode-compile path
+ list shared with ``scripts/install.js``
+ ``yaml`` (PyYAML, server dep) → structured workflow parsing
+ ``json`` (stdlib) → plain JSON files
+
+tsconfig.json is JSONC (allows ``/* */`` comments and trailing commas).
+The project has no JSONC parser; we use targeted ``re.search`` against
+the raw text rather than reach for a fresh dependency. The TypeScript
+team itself uses regex-on-source for tsconfig conformance tests.
+
+Refer to ``docs-internal/release_build_pipeline.md`` for the rationale
+behind each compile-pipeline knob.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+import pytest
+import yaml
+
+from machina.commands import build
+
+
+# ---------------------------------------------------------------------------
+# Workspace-keyed fixtures (no path strings)
+# ---------------------------------------------------------------------------
+
+# Workspace package names. These are the stable IDs declared in each
+# `package.json` — paths are resolved via the `workspace_members`
+# fixture so tests don't care where the workspace lives on disk.
+SIDECAR_PKG_NAME = "machinaos-nodejs-executor"
+CLIENT_PKG_NAME = "react-flow-client"
+
+
+def _load_pkg_json(workspace_path: Path) -> dict:
+ return json.loads((workspace_path / "package.json").read_text(encoding="utf-8"))
+
+
[email protected](scope="module")
+def sidecar_dir(workspace_members: dict[str, Path]) -> Path:
+ return workspace_members[SIDECAR_PKG_NAME]
+
+
[email protected](scope="module")
+def client_dir(workspace_members: dict[str, Path]) -> Path:
+ return workspace_members[CLIENT_PKG_NAME]
+
+
[email protected](scope="module")
+def sidecar_pkg(sidecar_dir: Path) -> dict:
+ return _load_pkg_json(sidecar_dir)
+
+
[email protected](scope="module")
+def client_pkg(client_dir: Path) -> dict:
+ return _load_pkg_json(client_dir)
+
+
[email protected](scope="module")
+def predeploy_yml(root: Path) -> dict:
+ """``.github/workflows/predeploy.yml`` parsed via PyYAML so tests
+ walk ``jobs[*].steps[*]`` structurally rather than regex on raw YAML.
+ """
+ path = root / ".github" / "workflows" / "predeploy.yml"
+ return yaml.safe_load(path.read_text(encoding="utf-8"))
+
+
[email protected](scope="module")
+def install_js_src(root: Path) -> str:
+ return (root / "scripts" / "install.js").read_text(encoding="utf-8")
+
+
+# ---------------------------------------------------------------------------
+# Node.js sidecar — package.json & .gitignore
+# ---------------------------------------------------------------------------
+
+def test_sidecar_start_runs_compiled_bundle(sidecar_pkg: dict):
+ """``npm start`` runs the esbuild-bundled output, not interpreted
+ TypeScript via tsx. tsx adds ~500ms-1s of interpreter startup that
+ the bundle eliminates.
+ """
+ start = sidecar_pkg["scripts"]["start"]
+ assert start == "node dist/index.js", (
+ f"sidecar start must be `node dist/index.js`, got {start!r}"
+ )
+ assert "tsx" not in start
+
+
+def test_sidecar_dev_keeps_tsx_for_hot_reload(sidecar_pkg: dict):
+ """``npm run dev`` keeps tsx watch — the bundle workflow is too slow
+ for local iteration. Only production ``start`` uses the bundle.
+ """
+ dev = sidecar_pkg["scripts"]["dev"]
+ assert "tsx" in dev and "watch" in dev
+
+
+ "esbuild",
+ "src/index.ts",
+ "--bundle",
+ "--platform=node",
+ "--target=node22",
+ "--format=esm",
+ "--packages=external",
+ "--outfile=dist/index.js",
+])
+def test_sidecar_build_script_carries_required_esbuild_flag(sidecar_pkg: dict, flag: str):
+ """Each esbuild flag in the sidecar build script is load-bearing.
+
+ - ``--bundle`` — concat the executor's own TS into one file.
+ - ``--platform=node`` — preserve Node built-in resolution.
+ - ``--target=node22`` — match ``engines.node`` in the same file.
+ - ``--format=esm`` — package.json ``type=module`` requires ESM.
+ - ``--packages=external`` — keep Express in node_modules; only the
+ executor's own TS is concatenated, so patch flow stays intact.
+ - ``--outfile=dist/index.js`` — ``start`` and ``main`` read this
+ exact path; mismatch breaks the runtime.
+ """
+ cmd = sidecar_pkg["scripts"]["build"]
+ assert flag in cmd, f"sidecar build script missing {flag!r}: {cmd}"
+
+
+def test_sidecar_engines_match_esbuild_target(sidecar_pkg: dict):
+ """``--target=node22`` and ``engines.node`` must agree. Bumping one
+ without the other would silently produce code that runs on a Node
+ version the package claims it doesn't support (or vice versa).
+ """
+ engines_node = sidecar_pkg.get("engines", {}).get("node", "")
+ assert "22" in engines_node, (
+ f"engines.node must declare ≥22 to match esbuild --target=node22, "
+ f"got {engines_node!r}"
+ )
+
+
+def test_sidecar_main_field_points_at_compiled_output(sidecar_pkg: dict):
+ """``main`` is what ``import 'machinaos-nodejs-executor'`` resolves
+ to — the compiled bundle, not the TS source.
+ """
+ assert sidecar_pkg.get("main") == "dist/index.js"
+
+
+def test_sidecar_esbuild_is_dev_only(sidecar_pkg: dict):
+ """esbuild builds the bundle; the runtime never touches it. It must
+ be a devDependency so a ``--omit=dev`` install doesn't ship it.
+ """
+ assert "esbuild" in sidecar_pkg.get("devDependencies", {})
+ assert "esbuild" not in sidecar_pkg.get("dependencies", {})
+
+
+def test_sidecar_dist_is_gitignored(sidecar_dir: Path):
+ """``dist/`` is build output and must not be tracked. Tracking it
+ triggers noisy diffs every time the bundle is regenerated.
+ """
+ gitignore = (sidecar_dir / ".gitignore").read_text(encoding="utf-8")
+ lines = {line.strip() for line in gitignore.splitlines()}
+ assert {"dist/", "dist"} & lines, (
+ f"sidecar .gitignore must list dist/, got:\n{gitignore}"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Client TypeScript / Vite
+# ---------------------------------------------------------------------------
+
+def test_client_typecheck_uses_tsgo(client_pkg: dict):
+ """The fast type-check (``pnpm run typecheck``) goes through tsgo
+ (Microsoft's Go-port of tsc, ~5x faster). The slower tsc fallback
+ stays available as ``typecheck:tsc`` in case tsgo regresses on a
+ dev release.
+ """
+ scripts = client_pkg["scripts"]
+ assert scripts.get("typecheck") == "tsgo --noEmit", (
+ f"client typecheck must be tsgo, got {scripts.get('typecheck')!r}"
+ )
+ assert scripts.get("typecheck:tsc") == "tsc --noEmit", (
+ "tsc fallback (typecheck:tsc) must remain available so a tsgo "
+ "regression has a one-line revert path"
+ )
+
+
+def test_tsgo_devdependency_is_pinned_exactly(client_pkg: dict):
+ """tsgo ships breaking changes between dev releases. A ``^`` or
+ ``~`` range would silently shift the type-check gate on each
+ install. Pin the exact version so upgrades are explicit.
+ """
+ version = client_pkg.get("devDependencies", {}).get("@typescript/native-preview")
+ assert version is not None, (
+ "@typescript/native-preview must be in client devDependencies"
+ )
+ assert not version.startswith(("^", "~", ">=", ">", "<")), (
+ f"tsgo must be pinned exactly (no range prefix), got {version!r}"
+ )
+
+
[email protected]("chunk_name", [
+ "vendor-react",
+ "vendor-flow",
+ "vendor-radix",
+ "vendor-icons",
+ "vendor-query",
+ "vendor-markdown",
+])
+def test_vite_config_declares_required_vendor_chunk(client_dir: Path, chunk_name: str):
+ """Vite must split the heavy npm libs into named vendor chunks so
+ the main bundle stays lean and dep churn doesn't bust the user's
+ HTTP cache.
+ """
+ src = (client_dir / "vite.config.js").read_text(encoding="utf-8")
+ assert "manualChunks" in src
+ assert chunk_name in src, f"vite.config.js missing chunk {chunk_name!r}"
+
+
+def test_vite_config_splits_reactflow(client_dir: Path):
+ """reactflow specifically must be split out of the main bundle —
+ it's the largest legitimate library and only canvas pages need it.
+ """
+ src = (client_dir / "vite.config.js").read_text(encoding="utf-8")
+ assert "reactflow" in src
+
+
+def test_vite_config_targets_es2022(client_dir: Path):
+ """ES2022 unlocks native ``findLast``, optional-chaining
+ assignment, class-fields without polyfills (Chrome 94+, FF 93+,
+ Safari 15.4+ — within React 19 / Tailwind 4's baseline).
+ """
+ src = (client_dir / "vite.config.js").read_text(encoding="utf-8")
+ assert re.search(r"target:\s*['\"]es2022['\"]", src), (
+ "vite.config.js must declare `target: 'es2022'` in build options"
+ )
+
+
+def test_vite_config_chunk_warning_below_one_megabyte(client_dir: Path):
+ """The chunk-size warning must be tighter than the original 1500 KB
+ so future regressions surface at build time.
+ """
+ src = (client_dir / "vite.config.js").read_text(encoding="utf-8")
+ match = re.search(r"chunkSizeWarningLimit:\s*(\d+)", src)
+ assert match is not None, "chunkSizeWarningLimit must be set in vite.config.js"
+ assert int(match.group(1)) <= 1000, (
+ f"chunkSizeWarningLimit={match.group(1)} is too lax — must be ≤1000 "
+ "to catch chunk-size regressions"
+ )
+
+
+def test_tsconfig_drops_baseurl_and_sets_typeroots(client_dir: Path):
+ """TS 7 / tsgo removed the deprecated ``baseUrl`` option.
+ ``typeRoots`` is the explicit replacement for telling the compiler
+ where to find ``@types/*`` packages — needed because pnpm's
+ symlinked ``node_modules`` layout can confuse auto-discovery.
+ """
+ src = (client_dir / "tsconfig.json").read_text(encoding="utf-8")
+ assert not re.search(r'^\s*"baseUrl"', src, re.MULTILINE), (
+ "TS 7 removed baseUrl — remove it; paths still resolve relative "
+ "to tsconfig.json without it"
+ )
+ assert re.search(
+ r'"typeRoots":\s*\[\s*"\./node_modules/@types"\s*\]',
+ src,
+ ), "typeRoots must point at ./node_modules/@types for tsgo + pnpm"
+ # The path alias must survive the baseUrl removal.
+ assert re.search(r'"@/\*":\s*\["\./src/\*"\]', src), (
+ "the `@/*` -> `./src/*` alias must remain configured"
+ )
+
+
+def test_vite_env_dts_references_google_maps(client_dir: Path):
+ """``@types/google.maps`` exposes a global ``google.maps`` namespace
+ (no module export). tsgo's auto-discovery doesn't pick it up
+ reliably through pnpm's symlinks, so the canonical Google-recommended
+ pattern (a triple-slash reference) is applied once in the
+ Vite-injected ambient declarations file.
+
+ Ref: https://developers.google.com/maps/documentation/javascript/using-typescript
+ """
+ src = (client_dir / "src" / "vite-env.d.ts").read_text(encoding="utf-8")
+ assert re.search(
+ r"///\s*<reference\s+types=[\"']google\.maps[\"']\s*/>", src
+ ), "vite-env.d.ts must triple-slash-reference google.maps"
+
+
+def test_test_setup_intersection_observer_has_scroll_margin(client_dir: Path):
+ """TS 7's lib.dom.d.ts (and Chromium 120+) requires
+ ``scrollMargin: string`` on IntersectionObserver. The vitest stub
+ must declare it or type-checks fail.
+ """
+ src = (client_dir / "src" / "test" / "setup.ts").read_text(encoding="utf-8")
+ assert "IntersectionObserverStub" in src
+ assert re.search(r"scrollMargin\s*=\s*['\"]['\"]", src), (
+ "IntersectionObserverStub must set scrollMargin to satisfy TS 7"
+ )
+
+
+# ---------------------------------------------------------------------------
+# CI gate — predeploy.yml
+# ---------------------------------------------------------------------------
+
+def _step_by_name(job: dict, step_name: str) -> dict | None:
+ for step in job.get("steps", []):
+ if step.get("name") == step_name:
+ return step
+ return None
+
+
+def test_predeploy_typecheck_step_routes_through_pnpm_script(predeploy_yml: dict):
+ """The CI typecheck step must invoke the npm script (which routes
+ through tsgo) rather than calling ``tsc`` directly. Keeps the
+ fast-vs-fallback choice in one place — ``client/package.json`` —
+ so devs can swap tools without editing the workflow.
+ """
+ job = predeploy_yml["jobs"]["build-and-lint"]
+ step = _step_by_name(job, "TypeScript check")
+ assert step is not None, "predeploy.yml must define a `TypeScript check` step"
+ cmd = step.get("run", "")
+ assert "run typecheck" in cmd, (
+ f"predeploy.yml typecheck step must call `pnpm ... run typecheck`, got {cmd!r}"
+ )
+ assert CLIENT_PKG_NAME in cmd, (
+ f"predeploy.yml typecheck step must filter to {CLIENT_PKG_NAME}, got {cmd!r}"
+ )
+ assert "tsc --noEmit" not in cmd, (
+ "predeploy.yml still calls `tsc --noEmit` directly — switch to "
+ "the typecheck script so tsgo is used"
+ )
+
+
+# ---------------------------------------------------------------------------
+# postinstall — scripts/install.js
+# ---------------------------------------------------------------------------
+
+# Single source of truth for parsing install.js's compileall command line.
+# Must match the shape that build.py emits exactly:
+# uv run python -O -m compileall -q -j 0 <dirs...>
+_INSTALL_JS_COMPILEALL_RE = re.compile(
+ r"""['"]uv\s+run\s+python\s+-O\s+-m\s+compileall\s+-q\s+-j\s+0\s+([^'"]+)['"]"""
+)
+
+
+def test_install_js_compileall_command_shape(install_js_src: str):
+ """End-user ``npm install machinaos`` runs install.js. The
+ compileall step must use the same shape as ``machina build`` —
+ ``uv run python -O -m compileall -q -j 0`` — so cold-start gains
+ apply to the npm-tarball path too.
+ """
+ assert _INSTALL_JS_COMPILEALL_RE.search(install_js_src) is not None, (
+ "install.js must run `uv run python -O -m compileall -q -j 0 ...`"
+ )
+
+
+def test_install_js_compileall_paths_match_source_dirs_constant(install_js_src: str):
+ """install.js's path list and ``build.COMPILEALL_SOURCE_DIRS`` must
+ match exactly. Drift means the npm-tarball install would compile a
+ different set of files than ``machina build``.
+ """
+ match = _INSTALL_JS_COMPILEALL_RE.search(install_js_src)
+ assert match is not None, "compileall invocation not found in install.js"
+ install_paths = tuple(match.group(1).split())
+ assert install_paths == build.COMPILEALL_SOURCE_DIRS, (
+ "install.js compileall paths drift from COMPILEALL_SOURCE_DIRS:\n"
+ f" install.js: {install_paths!r}\n"
+ f" constant : {build.COMPILEALL_SOURCE_DIRS!r}"
+ )
+
+
+def test_install_js_compileall_is_non_fatal(install_js_src: str):
+ """install.js's compileall call must be wrapped in try/catch with a
+ non-fatal warning. A malformed source file in a future commit
+ would otherwise fail every user's install — the runtime
+ regenerates pyc on first import anyway.
+ """
+ pattern = re.compile(
+ r"try\s*\{[^}]*compileall[^}]*\}\s*catch\s*\([^)]*\)\s*\{[^}]*[Ww]arning[^}]*\}",
+ re.DOTALL,
+ )
+ assert pattern.search(install_js_src) is not None, (
+ "compileall call in install.js must be wrapped in a try/catch "
+ "with a Warning log so it stays non-fatal"
+ )