Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(deploy): AWS through company deploy, named deployments, and errors.md #25 fixed
trohitg165608e4cff6
diff --git a/cli/buildenv.py b/cli/buildenv.pyindex e6f5df37..5fd094f9 100644--- a/cli/buildenv.py+++ b/cli/buildenv.py@@ -26,20 +26,20 @@ from cli.platform_ import ()-def validate_build(root: Path, *, require_client_dist: bool = False) -> None:+def validate_build(root: Path, *, dev: bool = False) -> None:"""Refuse to launch if ``company build`` hasn't been run.- Raises ``typer.Exit(1)`` with a remediation hint. ``dev`` allows a- missing ``client/dist`` (Vite serves the source); ``start`` and- ``serve`` opt in via ``require_client_dist=True``.-- Requiring ``node_modules`` for every caller is the open registry-install- bug in docs-internal/errors.md #25: a ``bun add -g`` install has no- ``node_modules`` next to the package, and only ``dev`` (Vite) needs it.+ Raises ``typer.Exit(1)`` with a remediation hint. Every verb needs the+ server venv. ``dev`` serves the client source through Vite, so it needs+ ``node_modules``; ``start`` and ``serve`` need the built client instead.+ A ``bun add -g`` install has no ``node_modules`` next to the package (bun+ keeps a global package's dependencies in its own global tree), so asking+ ``start`` / ``serve`` for it stopped every registry install, VMs included+ (docs-internal/errors.md #25)."""- if not node_modules_dir(root).exists() or not server_venv(root).exists():+ if not server_venv(root).exists() or (dev and not node_modules_dir(root).exists()):console.print('[red]Error: Project not built. Run "company build" first.[/]')raise typer.Exit(code=1)- if require_client_dist and not client_dist_entry(root).exists():+ if not dev and not client_dist_entry(root).exists():console.print('[red]Error: Client not built. Run "company build" first.[/]')raise typer.Exit(code=1)diff --git a/cli/cli.py b/cli/cli.pyindex f43867e6..b2f3ce79 100644--- a/cli/cli.py+++ b/cli/cli.py@@ -187,14 +187,15 @@ deploy_app = typer.Typer(help="Create an OpenCompany VM, install OpenCompany behind the login gate, and run it.",)def _deploy_up(- provider: str = typer.Option("gcp", "--provider", help="Cloud provider: gcp (aws is a follow-on)."),+ name: str = typer.Option("opencompany", "--name", help="Deployment name: its local state folder and cloud resource id. One per VM."),+ provider: str = typer.Option("gcp", "--provider", help="Cloud provider: gcp or aws."),owner_email: str = typer.Option(..., "--owner-email", help="Login email for the owner account."),owner_password: str | None = typer.Option(None, "--owner-password", help="Login password (>=8 chars). Generated + printed once if omitted."),- source: str = typer.Option("local", "--source", help="Install source: local (bun pm pack of this checkout) or release (npm registry)."),+ source: str | None = typer.Option(None, "--source", help="Install source: local (bun pm pack of this checkout) or release (npm registry). Default: local on gcp; aws supports only release."),version: str = typer.Option("latest", "--version", help="opencompany version when --source release."),- machine_type: str = typer.Option("e2-standard-2", "--machine-type", help="VM size."),+ machine_type: str | None = typer.Option(None, "--machine-type", help="VM size (default: e2-standard-2 on gcp, t3.micro on aws)."),port: int | None = typer.Option(None, "--port", help="Public port the app binds + the firewall opens (default: PYTHON_BACKEND_PORT from .env.template)."),allow_cidr: str = typer.Option("0.0.0.0/0", "--allow-cidr", help="Firewall source range (restrict to your IP/32)."),region: str | None = typer.Option(None, "--region", help="Cloud region (provider default if omitted)."),@@ -208,6 +209,7 @@ def _deploy_up(port = load_config().backend_portup_command(+ name=name,provider=provider,region=region,zone=zone,@@ -226,10 +228,12 @@ def _deploy_up("status",help="Show the OpenCompany deployment's URL + health.",)-def _deploy_status() -> None:+def _deploy_status(+ name: str = typer.Option("opencompany", "--name", help="Deployment name given to `deploy up`."),+) -> None:from cli.commands.deploy.status import status_command- status_command()+ status_command(name)@deploy_app.command(@@ -237,11 +241,12 @@ def _deploy_status() -> None:help="Terraform-destroy the OpenCompany deployment and remove its local state.",)def _deploy_destroy(+ name: str = typer.Option("opencompany", "--name", help="Deployment name given to `deploy up`."),keep_state: bool = typer.Option(False, "--keep-state", help="Keep the local Terraform state dir."),) -> None:from cli.commands.deploy.destroy import destroy_command- destroy_command(keep_state=keep_state)+ destroy_command(name=name, keep_state=keep_state)app.add_typer(deploy_app, name="deploy")diff --git a/cli/commands/deploy/_secrets.py b/cli/commands/deploy/_secrets.pyindex f48be373..5eec4c84 100644--- a/cli/commands/deploy/_secrets.py+++ b/cli/commands/deploy/_secrets.py@@ -38,11 +38,13 @@ def build_app_env(JWT/SECRET/ENCRYPTION keys are generated per deploy. ``JWT_COOKIE_SECURE``is ``false`` because the VM is reached over plain HTTP on its IP; flip to- true once a domain + TLS terminator is in front. Temporal/Redis/event- framework are off (local execution).+ true once a domain + TLS terminator is in front. Temporal, the event+ framework and ``HOST`` keep their ``.env.template`` values, as in the+ Docker image: chat, triggers and cron need Temporal, and its workers reach+ the backend at ``ws://HOST:PORT/ws/internal`` (``company serve`` binds+ every interface itself)."""return {- "HOST": "0.0.0.0","PORT": str(port),"DATA_DIR": data_dir,"WORKSPACE_BASE_DIR": "workspaces",@@ -52,8 +54,6 @@ def build_app_env("AUTH_MODE": "single","JWT_COOKIE_SECURE": "false","JWT_COOKIE_SAMESITE": "lax",- "TEMPORAL_ENABLED": "false",- "EVENT_FRAMEWORK_ENABLED": "false","REDIS_ENABLED": "false","LOG_FORMAT": "text","JWT_SECRET_KEY": new_key(),diff --git a/cli/commands/deploy/_state.py b/cli/commands/deploy/_state.pyindex de0db889..5d47894e 100644--- a/cli/commands/deploy/_state.py+++ b/cli/commands/deploy/_state.py@@ -1,9 +1,13 @@-"""Working dir + metadata for the (single) ``company deploy`` deployment.+"""Working dir + metadata for each ``company deploy`` deployment.-New deployments use ``opencompany``. Pre-rebrand deployments used-``machinaos`` and may live under either ``~/.machina`` or a checkout-local-``.machina`` root. Those paths are discovered before creating new state so a-rebrand can never orphan a live VM, firewall, bucket, or Terraform state.+A deployment is named (``--name``, default ``opencompany``). The name is its+folder under ``<DATA_DIR>/deploy/`` and its cloud resource id, so one machine+can drive several VMs, one per name.++Pre-rebrand deployments used ``machinaos`` and may live under either+``~/.machina`` or a checkout-local ``.machina`` root. For the default name+those paths are discovered before creating new state so a rebrand can never+orphan a live VM, firewall, bucket, or Terraform state.The selected directory is BOTH the Terraform working dir (rendered module +``terraform.tfvars.json`` + local state) and the home of a small@@ -17,14 +21,20 @@ resolved when a function is called.from __future__ import annotationsimport json+import refrom pathlib import Pathfrom cli.platform_ import project_root, user_data_dir-#: Current deployment/resource name and the pre-rebrand compatibility name.+#: Default deployment/resource name and the pre-rebrand compatibility name.NAME = "opencompany"LEGACY_NAME = "machinaos"+#: A deployment name is also a cloud resource id. GCP service-account ids set+#: the tightest rule: 6-30 lowercase letters, digits and hyphens, starting+#: with a letter and not ending with a hyphen.+NAME_PATTERN = re.compile(r"[a-z][a-z0-9-]{4,28}[a-z0-9]")+_META_FILENAME = "deploy-meta.json"@@ -32,10 +42,6 @@ def deploy_root() -> Path:return user_data_dir() / "deploy"-def _new_workdir() -> Path:- return deploy_root() / NAME--def _legacy_workdirs() -> tuple[Path, ...]:"""All locations used by released versions before the rebrand."""candidates = (@@ -52,10 +58,10 @@ def _has_state(path: Path) -> bool:return (path / _META_FILENAME).exists() or (path / "terraform.tfstate").exists()-def workdir() -> Path:- """Terraform state location, preferring current state then legacy state."""- current = _new_workdir()- if _has_state(current):+def workdir(name: str = NAME) -> Path:+ """Terraform state location. The default name prefers current state, then legacy state."""+ current = deploy_root() / name+ if name != NAME or _has_state(current):return currentfor legacy in _legacy_workdirs():if _has_state(legacy):@@ -63,8 +69,10 @@ def workdir() -> Path:return current-def resource_name() -> str:+def resource_name(name: str = NAME) -> str:"""Cloud resource id to render without replacing legacy resources."""+ if name != NAME:+ return namemeta = read_meta() or {}configured = meta.get("resource_name")if configured in {NAME, LEGACY_NAME}:@@ -72,18 +80,18 @@ def resource_name() -> str:return LEGACY_NAME if workdir().name == LEGACY_NAME else NAME-def meta_file() -> Path:- return workdir() / _META_FILENAME+def meta_file(name: str = NAME) -> Path:+ return workdir(name) / _META_FILENAME-def write_meta(meta: dict) -> None:- wd = workdir()+def write_meta(meta: dict, name: str = NAME) -> None:+ wd = workdir(name)wd.mkdir(parents=True, exist_ok=True)- meta_file().write_text(json.dumps(meta, indent=2), encoding="utf-8")+ meta_file(name).write_text(json.dumps(meta, indent=2), encoding="utf-8")-def read_meta() -> dict | None:- mf = meta_file()+def read_meta(name: str = NAME) -> dict | None:+ mf = meta_file(name)if not mf.exists():return Nonetry:@@ -92,5 +100,5 @@ def read_meta() -> dict | None:return None-def exists() -> bool:- return meta_file().exists()+def exists(name: str = NAME) -> bool:+ return meta_file(name).exists()diff --git a/cli/commands/deploy/_terraform.py b/cli/commands/deploy/_terraform.pyindex d12a6454..99ebd1f9 100644--- a/cli/commands/deploy/_terraform.py+++ b/cli/commands/deploy/_terraform.py@@ -44,7 +44,7 @@ def prepare_workdir(workdir: Path, provider: str) -> None:if not src.is_dir():error_block(f"No Terraform module for provider {provider!r}.",- [f"Expected at {src}", "Supported today: gcp (aws is a follow-on)."],+ [f"Expected at {src}", "Supported: gcp, aws."],)raise typer.Exit(code=1)workdir.mkdir(parents=True, exist_ok=True)diff --git a/cli/commands/deploy/destroy.py b/cli/commands/deploy/destroy.pyindex 3a6f5060..a7abb1f9 100644--- a/cli/commands/deploy/destroy.py+++ b/cli/commands/deploy/destroy.py@@ -10,20 +10,25 @@ from cli._common import preflightfrom cli.colors import consolefrom . import _state, _terraform+from .providers import get_provider-def destroy_command(*, keep_state: bool = False) -> None:+def destroy_command(*, name: str = _state.NAME, keep_state: bool = False) -> None:# Establish the same DATA_DIR context as `deploy up` so workdir() matches.preflight()- meta = _state.read_meta()+ meta = _state.read_meta(name)if meta is None:console.print("[yellow]No OpenCompany deployment found.[/]")raise typer.Exit(code=1)+ # Terraform needs the provider's credentials to delete what it created.+ cli = get_provider(meta["provider"])+ cli.check()_terraform.ensure_terraform()- wd = _state.workdir()+ cli.ensure_terraform_auth()+ wd = _state.workdir(name)- console.log(f"terraform destroy ({_state.resource_name()})...")+ console.log(f"terraform destroy ({_state.resource_name(name)})...")_terraform.tf(wd, "destroy", "-auto-approve", "-input=false")if keep_state:diff --git a/cli/commands/deploy/providers/__init__.py b/cli/commands/deploy/providers/__init__.pyindex 579031a7..e877d348 100644--- a/cli/commands/deploy/providers/__init__.py+++ b/cli/commands/deploy/providers/__init__.py@@ -27,7 +27,7 @@ def get_provider(name: str) -> ProviderCli:from cli._common import error_block- error_block(f"Unknown provider {name!r}.", ["Supported: gcp (aws is a follow-on)."])+ error_block(f"Unknown provider {name!r}.", ["Supported: gcp, aws."])raise typer.Exit(code=1)diff --git a/cli/commands/deploy/providers/_base.py b/cli/commands/deploy/providers/_base.pyindex ebf990b3..442d116f 100644--- a/cli/commands/deploy/providers/_base.py+++ b/cli/commands/deploy/providers/_base.py@@ -14,6 +14,11 @@ class ProviderCli(Protocol):"""name: str+ #: Instance size used when ``--machine-type`` is not given.+ default_machine_type: str+ #: Install sources the provider's Terraform module supports; the first is+ #: the default for ``--source``.+ sources: tuple[str, ...]def check(self) -> None:"""Abort unless the provider CLI binary is on PATH."""diff --git a/cli/commands/deploy/providers/aws.py b/cli/commands/deploy/providers/aws.pyindex 8d65bf37..9b247b34 100644--- a/cli/commands/deploy/providers/aws.py+++ b/cli/commands/deploy/providers/aws.py@@ -1,47 +1,98 @@-"""aws-cli adapter -- still a placeholder.--The ``cli/terraform/aws/`` module has landed (validated t3.micro setup), but-this adapter has not been wired to it yet. It implements the ``ProviderCli``-shape so the resolver/wiring is uniform, and aborts with a clear message-(exit 1) when selected. The real adapter will mirror gcp.py: ``aws sts-get-caller-identity`` for auth, the default credential chain for Terraform,-region from ``aws configure get region`` / ``$AWS_REGION``, and the existing-security-group + EC2 instance module.+"""aws CLI adapter -- Stage 1 of ``company deploy --provider aws``.++Uses the operator's installed + authenticated ``aws`` CLI (v2) for auth and+region; Terraform's ``aws`` provider then creates the resources with the same+identity, exported from the CLI's credential chain. The module+(``cli/terraform/aws``) installs a published release with ``install.sh``, so+``release`` is the only install source."""from __future__ import annotations+import os+import typerfrom cli._common import error_block+from cli.colors import console+from cli.run import capture++_LOGIN_HINT = "Run: aws login (or aws sso login / aws configure)"class AwsCli:name = "aws"-- def _not_yet(self) -> None:- error_block(- "The aws provider is not implemented yet.",- ["Use --provider gcp for now; the AWS module is a planned follow-on."],- )- raise typer.Exit(code=1)+ default_machine_type = "t3.micro"+ sources = ("release",)def check(self) -> None:- self._not_yet()+ if capture(["aws", "--version"]) is None:+ error_block(+ "The aws CLI was not found on PATH.",+ ["Install AWS CLI v2: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html"],+ )+ raise typer.Exit(code=1)def authed_account(self) -> str | None:- return None+ return capture(+ ["aws", "sts", "get-caller-identity", "--query", "Arn", "--output", "text", "--no-cli-pager"]+ )def resolve_context(self, *, region, zone, project) -> dict:- self._not_yet()- return {}+ account = self.authed_account()+ if not account:+ error_block("The aws CLI is not logged in, or its session expired.", [_LOGIN_HINT])+ raise typer.Exit(code=1)++ # The AWS CLI's own order: the environment, then the profile's config.+ reg = (+ region+ or os.environ.get("AWS_REGION")+ or os.environ.get("AWS_DEFAULT_REGION")+ or capture(["aws", "configure", "get", "region", "--no-cli-pager"])+ or "us-east-1"+ )++ console.print(f" aws identity: {account}")+ console.print(f" region={reg}")+ return {"region": reg}def ensure_terraform_auth(self) -> None:- self._not_yet()+ # Terraform's aws provider reads the standard credential chain but not+ # every source the CLI supports (an `aws login` console session, for+ # one). Export the credentials the CLI resolved into this process's+ # environment, so the terraform child process uses the same identity.+ exported = capture(+ ["aws", "configure", "export-credentials", "--format", "env-no-export", "--no-cli-pager"]+ )+ if exported is None:+ error_block("Terraform cannot get credentials from the aws CLI.", [_LOGIN_HINT])+ raise typer.Exit(code=1)+ for line in exported.splitlines():+ key, sep, value = line.partition("=")+ if sep and key.startswith("AWS_"):+ os.environ[key] = valuedef enable_apis(self, ctx: dict) -> None:- self._not_yet()+ # AWS has no per-service API switch. The module's one account+ # prerequisite is a default VPC in the region: it names no subnet.+ region = ctx["region"]+ vpc = capture(+ [+ "aws", "ec2", "describe-vpcs",+ "--region", region,+ "--filters", "Name=is-default,Values=true",+ "--query", "Vpcs[0].VpcId",+ "--output", "text",+ "--no-cli-pager",+ ]+ )+ if not vpc or vpc == "None":+ error_block(+ f"Region {region} has no default VPC.",+ [f"Create one: aws ec2 create-default-vpc --region {region}"],+ )+ raise typer.Exit(code=1)def tfvars_extra(self, ctx: dict) -> dict:- self._not_yet()- return {}+ return {"region": ctx["region"]}diff --git a/cli/commands/deploy/providers/gcp.py b/cli/commands/deploy/providers/gcp.pyindex 20bc391d..1c63ae2e 100644--- a/cli/commands/deploy/providers/gcp.py+++ b/cli/commands/deploy/providers/gcp.py@@ -30,6 +30,8 @@ def _clean(value: str | None) -> str | None:class GcpCli:name = "gcp"+ default_machine_type = "e2-standard-2"+ sources = ("local", "release")def check(self) -> None:if capture(["gcloud", "version"]) is None:diff --git a/cli/commands/deploy/status.py b/cli/commands/deploy/status.pyindex 5bec63bc..0e835e93 100644--- a/cli/commands/deploy/status.py+++ b/cli/commands/deploy/status.py@@ -13,23 +13,23 @@ from cli.colors import consolefrom . import _state, _terraform-def status_command() -> None:+def status_command(name: str = _state.NAME) -> None:# Establish the same DATA_DIR context as `deploy up` (load_config sets it)# so workdir() resolves to the directory `up` created.cfg, _ = preflight()- meta = _state.read_meta()+ meta = _state.read_meta(name)if meta is None:console.print("[yellow]No OpenCompany deployment found.[/]")raise typer.Exit(code=1)- wd = _state.workdir()+ wd = _state.workdir(name)ip = _terraform.tf_output(wd, "external_ip")url = _terraform.tf_output(wd, "url") or (f"http://{ip}:{meta.get('port') or cfg.backend_port}" if ip else None)- console.print(" Deployment: OpenCompany")- console.print(f" Resource ID: {_state.resource_name()}")+ console.print(f" Deployment: {name}")+ console.print(f" Resource ID: {_state.resource_name(name)}")console.print(f" Provider: {meta.get('provider', '?')}")console.print(f" External IP: {ip or '(unknown / destroyed)'}")console.print(f" URL: {url or '(unknown)'}")diff --git a/cli/commands/deploy/up.py b/cli/commands/deploy/up.pyindex b842727c..14210f20 100644--- a/cli/commands/deploy/up.py+++ b/cli/commands/deploy/up.py@@ -65,33 +65,58 @@ def _poll_health(url: str, *, attempts: int = 40, delay: float = 15.0) -> bool:def up_command(*,+ name: str,provider: str,region: str | None,zone: str | None,- machine_type: str,+ machine_type: str | None,port: int,owner_email: str,owner_password: str | None,- source: str,+ source: str | None,version: str,allow_cidr: str,project: str | None,) -> None:_, root = preflight()+ if not _state.NAME_PATTERN.fullmatch(name):+ error_block(+ f"Invalid deployment name {name!r}.",+ ["Use 6-30 lowercase letters, digits and hyphens, starting with a letter."],+ )+ raise typer.Exit(code=1)+ # One working dir holds one provider's module and state; applying another+ # provider's module there would destroy the first provider's resources.+ meta = _state.read_meta(name)+ if meta and meta.get("provider") != provider:+ error_block(+ f"Deployment {name!r} runs on {meta.get('provider')}, not {provider}.",+ [f"Destroy it first (company deploy destroy --name {name}), or pick another --name."],+ )+ raise typer.Exit(code=1)+# --- STAGE 1: cloud CLI (auth + context + APIs) ------------------------cli = get_provider(provider)+ source = source or cli.sources[0]+ if source not in cli.sources:+ error_block(+ f"--source {source} is not available with --provider {provider}.",+ [f"Supported: {', '.join(cli.sources)}."],+ )+ raise typer.Exit(code=1)+ machine_type = machine_type or cli.default_machine_typecli.check()_terraform.ensure_terraform()ctx = cli.resolve_context(region=region, zone=zone, project=project)cli.ensure_terraform_auth()cli.enable_apis(ctx)- resource_name = _state.resource_name()- if _state.exists() and (_state.workdir() / "terraform.tfstate").exists():+ resource_name = _state.resource_name(name)+ if _state.exists(name) and (_state.workdir(name) / "terraform.tfstate").exists():console.print(- "[yellow]An OpenCompany deployment already exists. Re-running will "- "re-apply Terraform (safe), or run `company deploy destroy` first.[/]"+ f"[yellow]The OpenCompany deployment {name!r} already exists. Re-running will "+ f"re-apply Terraform (safe), or run `company deploy destroy --name {name}` first.[/]")# --- STAGE 2: secrets + source + Terraform -----------------------------@@ -118,7 +143,7 @@ def up_command(}tfvars.update(cli.tfvars_extra(ctx))- wd = _state.workdir()+ wd = _state.workdir(name)_terraform.prepare_workdir(wd, provider)_terraform.write_tfvars(wd, tfvars)_state.write_meta(@@ -127,7 +152,8 @@ def up_command("port": port,"owner_email": owner_email,"resource_name": resource_name,- }+ },+ name,)console.log("terraform init...")diff --git a/cli/commands/dev.py b/cli/commands/dev.pyindex be470c3d..80f15404 100644--- a/cli/commands/dev.py+++ b/cli/commands/dev.py@@ -93,7 +93,7 @@ def dev_command(cfg, root = preflight()os.environ.setdefault("PYTHONUTF8", "1")- validate_build(root)+ validate_build(root, dev=True)console.print("\n[bold]=== OpenCompany Starting ===[/]\n")console.print(f"Platform: {platform_name()}")diff --git a/cli/commands/serve.py b/cli/commands/serve.pyindex 2e672887..a4558887 100644--- a/cli/commands/serve.py+++ b/cli/commands/serve.py@@ -32,7 +32,7 @@ def serve_command(port: int | None = None) -> None:cfg, root = preflight()os.environ.setdefault("PYTHONUTF8", "1")- validate_build(root, require_client_dist=True)+ validate_build(root)# Public port: --port flag > $PORT (Cloud Run / systemd convention) ># PYTHON_BACKEND_PORT from the env files.diff --git a/cli/commands/start.py b/cli/commands/start.pyindex 73dcdacc..996b77e7 100644--- a/cli/commands/start.py+++ b/cli/commands/start.py@@ -130,7 +130,7 @@ def start_command() -> None:cfg, root = preflight()os.environ.setdefault("PYTHONUTF8", "1")- validate_build(root, require_client_dist=True)+ validate_build(root)_sqlalchemy_preflight(root)console.log("Freeing ports...")diff --git a/cli/terraform/aws/README.md b/cli/terraform/aws/README.mdindex 65455baa..aab9814e 100644--- a/cli/terraform/aws/README.md+++ b/cli/terraform/aws/README.md@@ -1,55 +1,66 @@# OpenCompany on AWS (Terraform)-One login-gated EC2 instance running OpenCompany. File layout and workflow-follow the HashiCorp AWS get-started tutorial+One login-gated EC2 instance running OpenCompany per deployment, driven by+`company deploy --provider aws` (`cli/commands/deploy/providers/aws.py`). The+adapter checks the aws CLI and its login, resolves the region (`--region`,+then `AWS_REGION` / `AWS_DEFAULT_REGION`, then the profile, then `us-east-1`),+hands the credentials the CLI resolved to Terraform (its aws provider cannot+read every source the CLI can, `aws login` sessions included), and checks+that the region has a default VPC. `up` then writes `terraform.tfvars.json`+into the deployment's own folder and runs `terraform apply`.++File layout follows the HashiCorp AWS get-started tutorial(https://developer.hashicorp.com/terraform/tutorials/aws-get-started):-`terraform.tf` (providers), `main.tf`, `variables.tf`, `outputs.tf`, plus-`startup.sh.tftpl` (the cloud-init startup script template).+`terraform.tf` (providers), `main.tf`, `variables.tf` (the variable set every+provider module declares, plus `region` and three optional AWS settings),+`outputs.tf` (`external_ip`, `url`, `instance_id`), plus `startup.sh.tftpl`+(the cloud-init startup script template).++```bash+company deploy up --provider aws --name acme-corp --owner-email [email protected]+company deploy status --name acme-corp+company deploy destroy --name acme-corp+```-Settings are the ones validated on a live t3.micro in September 2026:+Each `--name` is a separate deployment: its own Terraform state under+`<DATA_DIR>/deploy/<name>/`, its own instance, security group (`<name>-app`),+systemd unit, env file and data directory. That is how one machine creates+one VM per user. Names are 6-30 lowercase letters, digits and hyphens+starting with a letter (GCP's service-account rule, so a name works on both+providers).| Setting | Value | Why ||---|---|---|-| Instance | `t3.micro`, 2 vCPU, 1 GiB | Smallest size the app runs on (backend ~200 MB + Temporal ~150 MB). 512 MB OOM-loops. |+| Instance | `--machine-type`, default `t3.micro` (2 vCPU, 1 GiB) | Smallest size the app runs on (backend ~200 MB + Temporal ~150 MB). 512 MB OOM-loops. || Credit mode | `standard` | Caps compute at the hourly rate under continuous CPU load. || Root disk | 10 GiB gp3, deleted with the instance | A fresh install uses ~4.5 GiB. |-| Image | Ubuntu 24.04 LTS (Canonical) | Python 3.12 inside the server's `<3.13` pin. |-| bun | installed by `install.sh` (the official bun installer, into `~ubuntu/.bun`) when none is present; no Node, no npm | The published package runs on bun: the `company` shim, the JS executor sidecar and the plugin CLIs (including the Cloudflare `cf` CLI: bun ignores its `engines.node >= 22` and runs its API commands; only cf's project commands, which load a `cloudflare.config.ts`, need Node 22.18+). systemd gets `$APP_HOME/.bun/bin` on PATH and `ExecStart=$APP_HOME/.bun/bin/company serve`. |-| Install | `install.sh` as `ubuntu`, no sudo | Root installs leave the venvs unusable by the login user (errors.md #16). |-| Runtime | `company serve` under systemd as `ubuntu` on port 5678 | The server rejects ports below 1024; 80/443 stay free for a TLS front door. |-| Security group | 22, 80, 443 and the app port from `allow_cidr` | Same shape as the gcp module. |+| Image | Ubuntu 24.04 LTS (Canonical), the newest when the instance is created | Python 3.12 inside the server's `<3.13` pin. |+| Install | `install.sh` as `ubuntu`, no sudo; a published release only | Root installs leave the venvs unusable by the login user (errors.md #16). The module has no artifact bucket, so `--source local` is refused. |+| bun | installed by `install.sh` (the official bun installer, into `~ubuntu/.bun`) when none is present; no Node, no npm | The published package runs on bun. systemd gets `$APP_HOME/.bun/bin` on PATH and `ExecStart=$APP_HOME/.bun/bin/company serve`. |+| Runtime | `company serve` under systemd as `ubuntu` on `--port` (default `PYTHON_BACKEND_PORT`) | The server rejects ports below 1024; 80/443 stay free for a TLS front door. |+| Temporal | on (the `.env.template` default, as in the Docker image) | Chat, chat and webhook triggers, and cron need it. |+| Security group | 22, 80, 443 and the app port from `--allow-cidr` | Same shape as the gcp module. |+| Re-apply | never replaces or restarts a running instance (`ignore_changes = [ami, user_data]`) | Replacing deletes the root volume and everything in `DATA_DIR`. The boot script runs only on the first boot, so a new image, script or `app_env` reaches new instances only. |-```bash-cd cli/terraform/aws-terraform init-terraform fmt-terraform validate-terraform apply -var key_name=<your-key-pair> -var opencompany_version=0.2.1 \- -var-file=app_env.auto.tfvars.json-terraform output url-```+Releases up to 0.2.1 do not come up on a fresh instance: `company serve`+stops with `Project not built` and systemd restarts it in a loop+([errors.md #25](../../../docs-internal/errors.md), fixed after 0.2.1).+`--version` picks the release (the tag without the `v`); the default `latest`+installs the newest one.-`opencompany_version` is the release tag without the `v`. The module was-validated on 0.1.1; the 0.2.x registry package currently fails `company serve`-on a fresh install (see [errors.md #25](../../../docs-internal/errors.md)), so-a VM deploy of 0.2.x does not come up until that is fixed.--`app_env` carries the owner login, fresh JWT/encryption keys, `PORT=5678`,-`DATA_DIR=/var/lib/opencompany` and `TEMPORAL_ENABLED=false`. Generate it with-`cli/commands/deploy/_secrets.py build_app_env(owner_email=..., owner_password=...,-port=5678)` and write it as `{"app_env": {...}}` to `app_env.auto.tfvars.json`-(gitignored) rather than typing it by hand. First boot takes about 10 minutes-on a t3.micro. Changing `app_env` or the boot script later does not recreate-the instance; the new user data only runs on a fresh one.+`app_env` carries the owner login, fresh JWT/encryption keys, `PORT`,+`DATA_DIR=/var/lib/<name>` and `DEPLOYMENT_MODE=cloud`; `company deploy` builds+it with `build_app_env` (`cli/commands/deploy/_secrets.py`). To run the module+by hand, write `terraform.tfvars.json` with the variables in `variables.tf`+(the file `company deploy up` writes is the template) and run `terraform+init` / `apply` in a folder of its own. First boot takes about 10 minutes on a+t3.micro.First boot fetches `https://opencompany.sh/install.sh` (override with`install_sh_url`), and that script asks `https://opencompany.sh/version` forthe release unless `opencompany_version` is set. Both endpoints must be servedfrom the opencompany.sh site.-Uses the AWS CLI's default credential chain. `company deploy` cannot drive this-module yet; it needs an AWS entry in `cli/commands/deploy/providers`.--Cost at us-east-1 list prices: about $12/month fixed (instance, disk, public-IPv4), and CPU load cannot raise it. Egress past the free 100 GB/month is the-only open-ended line.+Cost at us-east-1 list prices: about $12/month per t3.micro deployment+(instance, disk, public IPv4), and CPU load cannot raise it. Egress past the+free 100 GB/month is the only open-ended line.diff --git a/cli/terraform/aws/main.tf b/cli/terraform/aws/main.tfindex b552e1f8..93247488 100644--- a/cli/terraform/aws/main.tf+++ b/cli/terraform/aws/main.tf@@ -17,7 +17,7 @@ data "aws_ami" "ubuntu" {}resource "aws_security_group" "app_server" {- name = "${var.instance_name}-app"+ name = "${var.resource_name}-app"description = "OpenCompany: SSH, web, and the app port"dynamic "ingress" {@@ -38,13 +38,13 @@ resource "aws_security_group" "app_server" {}tags = {- Name = "${var.instance_name}-app"+ Name = "${var.resource_name}-app"}}resource "aws_instance" "app_server" {ami = data.aws_ami.ubuntu.id- instance_type = var.instance_type+ instance_type = var.machine_typekey_name = var.key_name != "" ? var.key_name : nullvpc_security_group_ids = [aws_security_group.app_server.id]@@ -61,13 +61,22 @@ resource "aws_instance" "app_server" {}user_data = templatefile("${path.module}/startup.sh.tftpl", {- instance_name = var.instance_name+ resource_name = var.resource_nameversion = var.opencompany_versioninstall_sh_url = var.install_sh_urlapp_env = var.app_env})tags = {- Name = var.instance_name+ Name = var.resource_name+ }++ # A later apply never replaces or restarts a running instance: replacing+ # deletes the root volume and everything in DATA_DIR. The boot script runs+ # only on the first boot anyway, so a changed script or app_env (company+ # deploy mints new keys on every run) can only reach a new instance, and+ # the newest image the lookup above finds is for new instances too.+ lifecycle {+ ignore_changes = [ami, user_data]}}diff --git a/cli/terraform/aws/outputs.tf b/cli/terraform/aws/outputs.tfindex 13476b2a..370c3096 100644--- a/cli/terraform/aws/outputs.tf+++ b/cli/terraform/aws/outputs.tf@@ -1,9 +1,4 @@-output "instance_id" {- description = "ID of the EC2 instance."- value = aws_instance.app_server.id-}--output "instance_public_ip" {+output "external_ip" {description = "Public IP of the EC2 instance (changes on stop/start unless an Elastic IP is attached)."value = aws_instance.app_server.public_ip}@@ -12,3 +7,8 @@ output "url" {description = "The app URL (login gate)."value = "http://${aws_instance.app_server.public_ip}:${var.port}"}++output "instance_id" {+ description = "ID of the EC2 instance."+ value = aws_instance.app_server.id+}diff --git a/cli/terraform/aws/startup.sh.tftpl b/cli/terraform/aws/startup.sh.tftplindex 174e38b7..1cdb8312 100644--- a/cli/terraform/aws/startup.sh.tftpl+++ b/cli/terraform/aws/startup.sh.tftpl@@ -18,30 +18,30 @@ APP_USER=ubuntuAPP_HOME=/home/$APP_USERINSTALL_SH='${install_sh_url}'-echo "[${instance_name}] installing OpenCompany as $APP_USER..."+echo "[${resource_name}] installing OpenCompany as $APP_USER..."sudo -u $APP_USER -H env OPENCOMPANY_VERSION="${version}" \bash -c "curl -fsSL $INSTALL_SH | bash"-echo "[${instance_name}] writing login-gate env..."-mkdir -p /etc/${instance_name}-cat > /etc/${instance_name}/opencompany.env <<'OPENCOMPANY_ENV_EOF'+echo "[${resource_name}] writing login-gate env..."+mkdir -p /etc/${resource_name}+cat > /etc/${resource_name}/opencompany.env <<'OPENCOMPANY_ENV_EOF'%{ for k, v in app_env ~}${k}=${v}%{ endfor ~}OPENCOMPANY_ENV_EOF-chmod 600 /etc/${instance_name}/opencompany.env+chmod 600 /etc/${resource_name}/opencompany.env-# DATA_DIR from app_env (default /var/lib/opencompany) must be writable by-# the service user.-mkdir -p /var/lib/${instance_name}-chown $APP_USER:$APP_USER /var/lib/${instance_name}+# DATA_DIR from app_env (/var/lib/<resource_name>) must be writable by the+# service user.+mkdir -p /var/lib/${resource_name}+chown $APP_USER:$APP_USER /var/lib/${resource_name}-echo "[${instance_name}] installing systemd service..."+echo "[${resource_name}] installing systemd service..."# The shim lives under the user's bun global bin dir (install.sh installs bun# for the login user; BUN_INSTALL defaults to ~/.bun).OPENCOMPANY_BIN="$APP_HOME/.bun/bin/company"test -x "$OPENCOMPANY_BIN"-cat > /etc/systemd/system/${instance_name}.service <<SERVICE_EOF+cat > /etc/systemd/system/${resource_name}.service <<SERVICE_EOF[Unit]Description=OpenCompany (single login-gated instance)After=network-online.target@@ -52,7 +52,7 @@ Type=simpleUser=$APP_USERWorkingDirectory=$APP_HOMEEnvironment=PATH=$APP_HOME/.bun/bin:$APP_HOME/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin-EnvironmentFile=/etc/${instance_name}/opencompany.env+EnvironmentFile=/etc/${resource_name}/opencompany.envExecStart=$OPENCOMPANY_BIN serveRestart=on-failureRestartSec=5@@ -67,5 +67,5 @@ WantedBy=multi-user.targetSERVICE_EOFsystemctl daemon-reload-systemctl enable --now ${instance_name}-echo "[${instance_name}] OpenCompany is ready."+systemctl enable --now ${resource_name}+echo "[${resource_name}] OpenCompany is ready."diff --git a/cli/terraform/aws/variables.tf b/cli/terraform/aws/variables.tfindex 30dfb6b9..8f5b2706 100644--- a/cli/terraform/aws/variables.tf+++ b/cli/terraform/aws/variables.tf@@ -1,59 +1,74 @@+# Shared deployment variable interface: every provider module declares the+# same set (see ../gcp/variables.tf), so `company deploy` writes one tfvars+# shape whatever the provider. `region` comes from the aws adapter; the last+# three variables are AWS-only and optional.+variable "region" {+ type = stringdescription = "AWS region."+}++variable "machine_type" {+ type = string+ description = "EC2 instance type. t3.micro (2 vCPU, 1 GiB) is the smallest size the app runs on; 512 MB instances OOM-loop."+}++variable "port" {+ type = number+ description = "Public port the app binds and the security group opens. The server rejects ports below 1024; 80/443 are left for a TLS front door."+}++variable "allow_cidr" {type = string- default = "us-east-1"+ description = "Security group source range (e.g. 0.0.0.0/0 or <your-ip>/32)."}-variable "instance_name" {- description = "Value of the EC2 instance's Name tag; also the systemd unit and env-file name on the VM."+variable "source_mode" {type = string- default = "opencompany"+ description = "Install source. This module installs a published release with install.sh, so only 'release' is accepted."++ validation {+ condition = var.source_mode == "release"+ error_message = "The aws module installs a published release with install.sh: set source_mode = \"release\" (company deploy --source release)."+ }}-variable "instance_type" {- description = "The EC2 instance's type. t3.micro (2 vCPU, 1 GiB) is the smallest size the app runs on; 512 MB instances OOM-loop."+variable "opencompany_version" {type = string- default = "t3.micro"+ description = "opencompany version to install from npm: the release tag without the v, or latest."}-variable "root_volume_gb" {- description = "Root gp3 volume size in GiB. A fresh install uses about 4.5 GiB."- type = number- default = 10+variable "resource_name" {+ type = string+ description = "Durable id: the instance's Name tag, the security group's name prefix, and the systemd unit, env file and data directory names on the VM."}-variable "key_name" {- description = "Existing EC2 key pair name for SSH. Empty = no key pair."+variable "pack_tarball" {type = stringdefault = ""+ description = "Unused here: the shared interface's tarball for source_mode = 'local', which this module does not support."}-variable "port" {- description = "Public port the app binds and the security group opens. The server rejects ports below 1024; 80/443 are left for a TLS front door."- type = number- default = 5678+variable "app_env" {+ type = map(string)+ sensitive = true+ description = "KEY=VALUE map rendered into the VM's systemd EnvironmentFile (company deploy builds it with build_app_env in cli/commands/deploy/_secrets.py)."}-variable "allow_cidr" {- description = "Security group source range (e.g. 0.0.0.0/0 or <your-ip>/32)."- type = string- default = "0.0.0.0/0"+variable "root_volume_gb" {+ type = number+ default = 10+ description = "Root gp3 volume size in GiB. A fresh install uses about 4.5 GiB."}-variable "opencompany_version" {- description = "opencompany version to install from npm. Empty = latest."+variable "key_name" {type = stringdefault = ""+ description = "Existing EC2 key pair name for SSH. Empty = no key pair; EC2 Instance Connect still works."}variable "install_sh_url" {- description = "URL of the OpenCompany install script the first boot runs. Override to test an unreleased installer."type = stringdefault = "https://opencompany.sh/install.sh"-}--variable "app_env" {- description = "KEY=VALUE map rendered into the VM's systemd EnvironmentFile. Generate with cli/commands/deploy/_secrets.py build_app_env(port=<port>)."- type = map(string)- sensitive = true+ description = "URL of the OpenCompany install script the first boot runs. Override to test an unreleased installer."}diff --git a/cli/tests/test_backend_shutdown.py b/cli/tests/test_backend_shutdown.pyindex 41fee1fd..42ec21f8 100644--- a/cli/tests/test_backend_shutdown.py+++ b/cli/tests/test_backend_shutdown.py@@ -129,8 +129,9 @@ def test_stop_kills_only_this_installations_temporal(tmp_path: Path, monkeypatchdef test_vm_unit_outwaits_the_backend_shutdown_allowance(rel: str, monkeypatch: pytest.MonkeyPatch):"""systemd must not SIGKILL the backend before the CLI's own deadline.- Deployed VMs start with Temporal off, but the runbook documents turning it- on, so each unit covers the allowance with Temporal on and the template's+ ``company deploy`` VMs run with Temporal on (the ``.env.template`` default)+ and the manual runbook documents turning it on, so each unit covers the+ allowance with Temporal on and the template's``TEMPORAL_GRACEFUL_SHUTDOWN_SECONDS``. A shorter ``TimeoutStopSec`` killsthe backend before its shutdown hooks run, and with Temporal on the nextboot then treats the stop as a crash and pauses running deployments.diff --git a/cli/tests/test_buildenv.py b/cli/tests/test_buildenv.pynew file mode 100644index 00000000..e0019c2b--- /dev/null+++ b/cli/tests/test_buildenv.py@@ -0,0 +1,55 @@+"""``validate_build``: what each verb needs from ``company build``."""++from __future__ import annotations++from pathlib import Path++import pytest+import typer++from cli.buildenv import validate_build+++def _layout(root: Path, *, venv: bool, node_modules: bool, client: bool) -> Path:+ if venv:+ (root / "server" / ".venv").mkdir(parents=True)+ if node_modules:+ (root / "node_modules").mkdir()+ if client:+ (root / "client" / "dist").mkdir(parents=True)+ (root / "client" / "dist" / "index.html").write_text("<html></html>", encoding="utf-8")+ return root++[email protected](autouse=True)+def _default_venv_location(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("UV_PROJECT_ENVIRONMENT", raising=False)+++def test_registry_install_starts_without_node_modules(tmp_path: Path) -> None:+ """``bun add -g`` leaves no ``node_modules`` next to the package; ``start`` /+ ``serve`` need only the server venv and the built client (errors.md #25)."""+ validate_build(_layout(tmp_path, venv=True, node_modules=False, client=True))+++def test_dev_needs_node_modules(tmp_path: Path) -> None:+ root = _layout(tmp_path, venv=True, node_modules=False, client=True)+ with pytest.raises(typer.Exit):+ validate_build(root, dev=True)+++def test_dev_runs_without_the_built_client(tmp_path: Path) -> None:+ validate_build(_layout(tmp_path, venv=True, node_modules=True, client=False), dev=True)+++def test_start_needs_the_built_client(tmp_path: Path) -> None:+ root = _layout(tmp_path, venv=True, node_modules=True, client=False)+ with pytest.raises(typer.Exit):+ validate_build(root)++[email protected]("dev", [False, True])+def test_every_verb_needs_the_server_venv(tmp_path: Path, dev: bool) -> None:+ root = _layout(tmp_path, venv=False, node_modules=True, client=True)+ with pytest.raises(typer.Exit):+ validate_build(root, dev=dev)diff --git a/cli/tests/test_deploy_aws.py b/cli/tests/test_deploy_aws.pynew file mode 100644index 00000000..57bd1f61--- /dev/null+++ b/cli/tests/test_deploy_aws.py@@ -0,0 +1,93 @@+"""The aws adapter of ``company deploy`` (Stage 1), with the aws CLI faked."""++from __future__ import annotations++import os+from unittest.mock import patch++import pytest+import typer++from cli.commands.deploy.providers import aws+from cli.commands.deploy.providers.aws import AwsCli+++def _fake_capture(responses: dict[tuple[str, ...], str | None]):+ """``capture`` stand-in answering by argv prefix."""++ def capture(argv, cwd=None):+ for prefix, out in responses.items():+ if tuple(argv[: len(prefix)]) == prefix:+ return out+ raise AssertionError(f"unexpected command: {argv}")++ return capture+++_LOGGED_IN = {("aws", "sts", "get-caller-identity"): "arn:aws:iam::123456789012:user/ops"}+++ ("flag", "env", "config", "expected"),+ [+ ("eu-west-1", {"AWS_REGION": "ap-south-1"}, "us-west-2", "eu-west-1"),+ (None, {"AWS_REGION": "ap-south-1", "AWS_DEFAULT_REGION": "ca-central-1"}, "us-west-2", "ap-south-1"),+ (None, {"AWS_DEFAULT_REGION": "ca-central-1"}, "us-west-2", "ca-central-1"),+ (None, {}, "us-west-2", "us-west-2"),+ (None, {}, None, "us-east-1"),+ ],+)+def test_region_follows_the_aws_cli_order(monkeypatch, flag, env, config, expected) -> None:+ for key in ("AWS_REGION", "AWS_DEFAULT_REGION"):+ monkeypatch.delenv(key, raising=False)+ for key, value in env.items():+ monkeypatch.setenv(key, value)+ responses = {**_LOGGED_IN, ("aws", "configure", "get", "region"): config}+ with patch.object(aws, "capture", side_effect=_fake_capture(responses)):+ ctx = AwsCli().resolve_context(region=flag, zone=None, project=None)+ assert ctx == {"region": expected}+ assert AwsCli().tfvars_extra(ctx) == {"region": expected}+++def test_not_logged_in_stops_before_terraform() -> None:+ responses = {("aws", "sts", "get-caller-identity"): None}+ with patch.object(aws, "capture", side_effect=_fake_capture(responses)), pytest.raises(typer.Exit) as exc:+ AwsCli().resolve_context(region="us-east-1", zone=None, project=None)+ assert exc.value.exit_code == 1+++def test_terraform_gets_the_credentials_the_cli_resolved() -> None:+ exported = (+ "AWS_ACCESS_KEY_ID=ASIAEXAMPLE\n"+ "AWS_SECRET_ACCESS_KEY=abc/def+ghi=\n"+ "AWS_SESSION_TOKEN=token==\n"+ "AWS_CREDENTIAL_EXPIRATION=2026-10-09T12:00:00+00:00"+ )+ responses = {("aws", "configure", "export-credentials"): exported}+ with patch.dict(os.environ), patch.object(aws, "capture", side_effect=_fake_capture(responses)):+ AwsCli().ensure_terraform_auth()+ assert os.environ["AWS_ACCESS_KEY_ID"] == "ASIAEXAMPLE"+ assert os.environ["AWS_SECRET_ACCESS_KEY"] == "abc/def+ghi="+ assert os.environ["AWS_SESSION_TOKEN"] == "token=="+++def test_no_exportable_credentials_stops_before_terraform() -> None:+ responses = {("aws", "configure", "export-credentials"): None}+ with patch.object(aws, "capture", side_effect=_fake_capture(responses)), pytest.raises(typer.Exit):+ AwsCli().ensure_terraform_auth()++[email protected](("vpc", "ok"), [("vpc-0abc", True), ("None", False), (None, False)])+def test_a_default_vpc_is_required(vpc, ok) -> None:+ responses = {("aws", "ec2", "describe-vpcs"): vpc}+ with patch.object(aws, "capture", side_effect=_fake_capture(responses)):+ if ok:+ AwsCli().enable_apis({"region": "us-east-1"})+ else:+ with pytest.raises(typer.Exit):+ AwsCli().enable_apis({"region": "us-east-1"})+++def test_missing_cli_is_reported() -> None:+ with patch.object(aws, "capture", return_value=None), pytest.raises(typer.Exit):+ AwsCli().check()diff --git a/cli/tests/test_deploy_state.py b/cli/tests/test_deploy_state.pyindex 0091afed..6d822060 100644--- a/cli/tests/test_deploy_state.py+++ b/cli/tests/test_deploy_state.py@@ -1,10 +1,12 @@-"""Rebrand compatibility tests for persisted deployment state."""+"""Persisted deployment state: named deployments and rebrand compatibility."""from __future__ import annotationsimport jsonfrom pathlib import Path+import pytest+from cli.commands.deploy import _state@@ -38,3 +40,42 @@ def test_new_deployments_use_opencompany(monkeypatch, tmp_path: Path) -> None:assert _state.workdir() == currentassert _state.resource_name() == "opencompany"+++def test_named_deployments_keep_their_own_state(monkeypatch, tmp_path: Path) -> None:+ data = _isolate_roots(monkeypatch, tmp_path)++ _state.write_meta({"provider": "aws"}, "acme-corp")++ assert _state.workdir("acme-corp") == data / "deploy" / "acme-corp"+ assert _state.resource_name("acme-corp") == "acme-corp"+ assert _state.read_meta("acme-corp") == {"provider": "aws"}+ assert _state.read_meta() is None+++def test_named_deployments_never_adopt_legacy_state(monkeypatch, tmp_path: Path) -> None:+ data = _isolate_roots(monkeypatch, tmp_path)+ legacy = data / "deploy" / "machinaos"+ legacy.mkdir(parents=True)+ (legacy / "deploy-meta.json").write_text(json.dumps({"provider": "gcp"}), encoding="utf-8")++ assert _state.workdir("acme-corp") == data / "deploy" / "acme-corp"+ assert _state.workdir() == legacy+++ ("name", "valid"),+ [+ ("opencompany", True),+ ("machinaos", True),+ ("acme-corp-01", True),+ ("abc", False),+ ("Acme-corp", False),+ ("acme-", False),+ ("1acme", False),+ ("acme_corp", False),+ ("a" * 31, False),+ ],+)+def test_names_must_be_valid_cloud_ids(name: str, valid: bool) -> None:+ assert bool(_state.NAME_PATTERN.fullmatch(name)) is validdiff --git a/cli/tests/test_deploy_up.py b/cli/tests/test_deploy_up.pynew file mode 100644index 00000000..9ea90525--- /dev/null+++ b/cli/tests/test_deploy_up.py@@ -0,0 +1,150 @@+"""``company deploy up`` wiring: option defaults per provider, and the+contract between the tfvars ``up`` writes and each provider module."""++from __future__ import annotations++import re+from pathlib import Path+from unittest.mock import patch++import pytest+import typer++from cli.commands.deploy import up+from cli.commands.deploy.providers import get_provider+from cli.platform_ import project_root++_CONTEXT = {+ "gcp": {"project": "demo-project", "region": "us-central1", "zone": "us-central1-a"},+ "aws": {"region": "us-east-1"},+}+++def _module_variables(provider: str) -> dict[str, bool]:+ """``{name: has_default}`` for every variable the provider module declares."""+ text = (project_root() / "cli" / "terraform" / provider / "variables.tf").read_text(encoding="utf-8")+ blocks = re.split(r'^variable "', text, flags=re.MULTILINE)[1:]+ return {block.split('"', 1)[0]: re.search(r"^\s*default\s*=", block, re.MULTILINE) is not None for block in blocks}+++def _module_outputs(provider: str) -> set[str]:+ text = (project_root() / "cli" / "terraform" / provider / "outputs.tf").read_text(encoding="utf-8")+ return set(re.findall(r'^output "([^"]+)"', text, re.MULTILINE))+++def _up(provider: str, tmp_path: Path, written: dict, **overrides) -> None:+ adapter = get_provider(provider)+ kwargs = {+ "name": "opencompany",+ "provider": provider,+ "region": None,+ "zone": None,+ "machine_type": None,+ "port": 4321,+ "owner_email": "[email protected]",+ "owner_password": "correct-horse-battery",+ "source": None,+ "version": "latest",+ "allow_cidr": "203.0.113.4/32",+ "project": None,+ **overrides,+ }+ with (+ patch.object(up, "preflight", return_value=(None, tmp_path)),+ patch.object(up, "get_provider", return_value=adapter),+ patch.object(type(adapter), "check"),+ patch.object(type(adapter), "resolve_context", return_value=_CONTEXT[provider]),+ patch.object(type(adapter), "ensure_terraform_auth"),+ patch.object(type(adapter), "enable_apis"),+ patch.object(up._state, "read_meta", return_value=None),+ patch.object(up._state, "exists", return_value=False),+ patch.object(up._state, "workdir", return_value=tmp_path),+ patch.object(up._state, "write_meta"),+ patch.object(up._terraform, "ensure_terraform"),+ patch.object(up._terraform, "prepare_workdir"),+ patch.object(up._terraform, "write_tfvars", side_effect=lambda _wd, tfvars: written.update(tfvars)),+ patch.object(up._terraform, "tf"),+ patch.object(up._terraform, "tf_output", return_value=None),+ patch.object(up, "_npm_pack", return_value=str(tmp_path / "pkg.tgz")),+ patch.object(up.console, "print"),+ patch.object(up.console, "log"),+ ):+ up.up_command(**kwargs)++[email protected]("provider", ["gcp", "aws"])+def test_tfvars_match_the_provider_module(provider: str, tmp_path: Path) -> None:+ """Every key ``up`` writes is a variable the module declares, and every+ variable without a default is written. The aws module used to diverge+ (``instance_type`` / ``instance_name``) and Terraform only warns about+ undeclared tfvars, so the mismatch was silent."""+ written: dict = {}+ _up(provider, tmp_path, written)+ declared = _module_variables(provider)+ assert set(written) <= set(declared)+ assert {name for name, has_default in declared.items() if not has_default} <= set(written)++[email protected]("provider", ["gcp", "aws"])+def test_module_exports_the_outputs_up_and_status_read(provider: str) -> None:+ assert {"external_ip", "url"} <= _module_outputs(provider)++[email protected]("provider", ["gcp", "aws"])+def test_defaults_come_from_the_provider(provider: str, tmp_path: Path) -> None:+ written: dict = {}+ _up(provider, tmp_path, written)+ adapter = get_provider(provider)+ assert written["machine_type"] == adapter.default_machine_type+ assert written["source_mode"] == adapter.sources[0]+ assert written["resource_name"] == "opencompany"+++def test_aws_refuses_local_source_before_any_cloud_call(tmp_path: Path) -> None:+ adapter = get_provider("aws")+ with (+ patch.object(up, "preflight", return_value=(None, tmp_path)),+ patch.object(up._state, "read_meta", return_value=None),+ patch.object(up, "get_provider", return_value=adapter),+ patch.object(type(adapter), "check") as check,+ pytest.raises(typer.Exit) as exc,+ ):+ up.up_command(+ name="opencompany", provider="aws", region=None, zone=None, machine_type=None, port=4321,+ owner_email="[email protected]", owner_password=None, source="local", version="latest",+ allow_cidr="0.0.0.0/0", project=None,+ )+ assert exc.value.exit_code == 1+ check.assert_not_called()+++def test_a_name_belongs_to_one_provider(tmp_path: Path) -> None:+ """Applying aws's module in a gcp deployment's working dir would destroy+ the gcp resources, so ``up`` refuses before touching any cloud."""+ with (+ patch.object(up, "preflight", return_value=(None, tmp_path)),+ patch.object(up._state, "read_meta", return_value={"provider": "gcp"}),+ patch.object(up, "get_provider") as get,+ pytest.raises(typer.Exit),+ ):+ up.up_command(+ name="opencompany", provider="aws", region=None, zone=None, machine_type=None, port=4321,+ owner_email="[email protected]", owner_password=None, source=None, version="latest",+ allow_cidr="0.0.0.0/0", project=None,+ )+ get.assert_not_called()++[email protected]("name", ["abc", "Acme-corp", "acme-", "1acme", "a" * 31, "acme_corp"])+def test_invalid_names_are_refused(name: str, tmp_path: Path) -> None:+ with (+ patch.object(up, "preflight", return_value=(None, tmp_path)),+ patch.object(up, "get_provider") as get,+ pytest.raises(typer.Exit),+ ):+ up.up_command(+ name=name, provider="aws", region=None, zone=None, machine_type=None, port=4321,+ owner_email="[email protected]", owner_password=None, source=None, version="latest",+ allow_cidr="0.0.0.0/0", project=None,+ )+ get.assert_not_called()diff --git a/docs-internal/SCRIPTS.md b/docs-internal/SCRIPTS.mdindex ff9b68a7..241dd44c 100644--- a/docs-internal/SCRIPTS.md+++ b/docs-internal/SCRIPTS.md@@ -36,7 +36,7 @@ deprecation warning; kept for upgrade compatibility).| `company stop` | Stop all services and free configured ports || `company build` | Full production build (bun install → client → sidecar → `uv sync --extra docs` → 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 (and `bun install` in a checkout or `company provision` usually creates one first, as a plain template copy: see [Credentials Encryption → Placeholder secrets](./credentials_encryption.md#placeholder-secrets)) || `company clean` | Stop services, then remove build artifacts, node_modules, `.venv`, repo-local state (preserves `.opencompany/{workflows,deploy,packages}`) |-| `company deploy up/status/destroy` | Self-deploy a login-gated VM (gcloud preflight + Terraform; see `cli/commands/deploy/`) |+| `company deploy up/status/destroy` | Self-deploy a login-gated VM on GCP or AWS (gcloud / aws CLI preflight + Terraform; `--name` gives each VM its own state; see `cli/commands/deploy/`) || `company daemon start/stop/status/restart` | Detached backend management (PID file under user data dir) || `company version sync [tag]` | Write a git tag's version (default: the latest) into every version file: root / client / desktop `package.json`, `pyproject.toml`, `cli/__init__.py`. Never `server/pyproject.toml`, which `server/uv.lock` records. The release procedure is in [ci_cd.md -> Cutting a release](./ci_cd.md#cutting-a-release) || `company docs nodes [--check]` | Regenerate (or verify) the `docs-internal/node-logic-flows/` index |@@ -150,7 +150,7 @@ self-hosting image from source (`docker/Dockerfile`,`docker-compose.yml`); see [docker.md](./docker.md). No script or CLIverb wraps it. The old multi-container topology is preserved in[deployment_legacy.md](./deployment_legacy.md). Cloud VM deployment is-`company deploy` (Terraform → GCP VM → systemd).+`company deploy` (Terraform → GCP or AWS VM → systemd).---@@ -204,6 +204,7 @@ company clean # Clean everything (keeps workflows/deploy/packages state# Deploycompany deploy up --provider gcp --owner-email [email protected]-company deploy status-company deploy destroy+company deploy up --provider aws --name acme-corp --owner-email [email protected]+company deploy status --name acme-corp+company deploy destroy --name acme-corp```diff --git a/docs-internal/deployment_legacy.md b/docs-internal/deployment_legacy.mdindex 438fbca0..57f91fd7 100644--- a/docs-internal/deployment_legacy.md+++ b/docs-internal/deployment_legacy.md@@ -11,32 +11,45 @@ image built from source: see [docker.md](./docker.md).## Self-Deploy CLI (`company deploy`) — current path-One command provisions a login-gated OpenCompany VM on a cloud provider. Two stages:--1. **Operator's cloud CLI** (gcloud; the AWS Terraform module in `cli/terraform/aws/` is complete and validated on t3.micro, but the `cli/commands/deploy/providers/aws.py` CLI adapter is still a stub that exits 1) handles auth + project/region/zone resolution +- ADC verification + API enablement.-2. **Terraform** (`cli/terraform/gcp/`) owns all resources — new VMs use the- `opencompany` resource id,- firewall, artifact bucket (local `bun pm pack` source), service account, and a cloud-init startup- script (`startup.sh.tftpl`) that installs bun + uv (no Node, no npm), `bun add -g`s the package,- provisions its Python side with `company provision`, and runs `company serve` under systemd.+One command provisions a login-gated OpenCompany VM on GCP or AWS. Two stages:++1. **Operator's cloud CLI** (`providers/gcp.py`, `providers/aws.py`): gcloud handles auth ++ project/region/zone resolution + ADC verification + API enablement; the aws CLI handles+ auth (`sts get-caller-identity`) + region, hands its resolved credentials to Terraform+ (`aws configure export-credentials`, so `aws login` sessions work), and checks the region+ has a default VPC. Each adapter also names its default `--machine-type` and the `--source`+ values its module supports.+2. **Terraform** (`cli/terraform/<provider>/`, one shared variable set) owns all resources.+ GCP: firewall, artifact bucket (local `bun pm pack` source), service account, and a+ startup script (`startup.sh.tftpl`, GCE metadata, re-run on every boot) that installs bun ++ uv (no Node, no npm), `bun add -g`s the package, provisions its Python side with+ `company provision`, and runs `company serve` under systemd. AWS: a security group and an+ EC2 instance whose cloud-init script (first boot only) runs `install.sh` as `ubuntu` with a+ published release (`--source release` only) and runs `company serve` under systemd as that+ user; a later apply never replaces or restarts the instance (`ignore_changes = [ami,+ user_data]`). See [cli/terraform/aws/README.md](../cli/terraform/aws/README.md).> **Known issue in 0.2.0 and 0.2.1 ([errors.md #25 and #26](./errors.md))**: on a registry> install, `company serve` stops with `Project not built. Run "company build" first.`, so the> VM's systemd service fails and keeps restarting, and the package also lacks the JS executor-> sidecar bundle. Until the fix ships, run `company build` once on the VM as root (the startup-> script's user), which fixes both, then `systemctl restart opencompany` (`machinaos` on a-> pre-rebrand deployment).+> sidecar bundle. #25 is fixed after 0.2.1; on those two releases run `company build` once on the VM as the+> service user, then `systemctl restart opencompany` (`machinaos` on a pre-rebrand deployment).Login gate = built-in auth (`VITE_AUTH_ENABLED=true`, `AUTH_MODE=single`) with the ownercredential generated at deploy time and seeded on first boot. `build_app_env`(`cli/commands/deploy/_secrets.py`) also sets `DEPLOYMENT_MODE=cloud` on the VM and mints-fresh `JWT_SECRET_KEY` / `SECRET_KEY` / `API_KEY_ENCRYPTION_KEY` per deploy.+fresh `JWT_SECRET_KEY` / `SECRET_KEY` / `API_KEY_ENCRYPTION_KEY` per deploy. Temporal, the+event framework and `HOST` keep their `.env.template` values (Temporal on), as in the Docker+image, so chat, triggers and cron work on the VM.++`--name` (default `opencompany`) names a deployment: its state folder and its cloud resource+id. One machine drives one VM per name; a name stays with the provider that created it.```bashcompany deploy up --provider gcp --owner-email [email protected] # provision + install + print URL/creds-company deploy status # URL + /health-company deploy destroy # terraform destroy + clear state+company deploy up --provider aws --name acme-corp --owner-email [email protected]+company deploy status [--name acme-corp] # URL + /health+company deploy destroy [--name acme-corp] # terraform destroy + clear state```### Key files@@ -45,12 +58,15 @@ company deploy destroy # terraform des|------|----------------|| `cli/commands/serve.py` | Single-port runtime: uvicorn fronts API + WS + built SPA. `serve` supervises exactly one process — the JS code-exec sidecar (on bun), WhatsApp and the Temporal dev server are backend-owned and spawn on demand || `cli/commands/deploy/` | Verbs (`up.py` / `status.py` / `destroy.py`), `_secrets.py`, `_state.py`, `_terraform.py` (Terraform driver), `providers/` (`gcp.py` / `aws.py` provider CLI adapters) |-| `cli/terraform/gcp/` | HCL module (`main.tf` / `variables.tf` / `outputs.tf`) + `startup.sh.tftpl` cloud-init template |+| `cli/terraform/gcp/` | HCL module (`main.tf` / `variables.tf` / `outputs.tf`) + `startup.sh.tftpl` GCE startup-script template |+| `cli/terraform/aws/` | HCL module (`terraform.tf` / `main.tf` / `variables.tf` / `outputs.tf`) + `startup.sh.tftpl` cloud-init template |### State + delinking-- New deployment state lives at `<user-data>/deploy/opencompany/` — preserved by `company clean`- (see `_OPENCOMPANY_KEEP` in `cli/commands/clean.py`); only `company deploy destroy` removes it.+- Deployment state lives at `<DATA_DIR>/deploy/<name>/` (`~/.opencompany/deploy/opencompany/` by+ default); only `company deploy destroy` removes it. `company clean` keeps `.opencompany/deploy`+ inside the repo (see `_OPENCOMPANY_KEEP` in `cli/commands/clean.py`), which matters only when+ `DATA_DIR` points there.- Upgrade compatibility is deliberate: the CLI discovers pre-rebrand`deploy/machinaos/` state under the configured data root, `~/.machina`, or acheckout-local `.machina` directory. It retains the `machinaos` cloud anddiff --git a/docs-internal/errors.md b/docs-internal/errors.mdindex 249e7fe4..87e64672 100644--- a/docs-internal/errors.md+++ b/docs-internal/errors.md@@ -536,15 +536,15 @@ bun add -g @zeenie-ai/opencompany**Fix**: The job writes the scope route and the token into one `~/.npmrc` (`@zeenie-ai:registry=https://npm.pkg.github.com/` plus `//npm.pkg.github.com/:_authToken=<GITHUB_TOKEN>`) and runs a plain `bun publish`; the package.json rewrite is gone. To publish a mirror that failed this way, dispatch the Release workflow with `tag` set to the release and `registries` set to `github-packages`; the job checks out that tag. Locked by `test_github_packages_release_routes_the_scope_through_npmrc` in `cli/tests/test_release_pipeline_config.py`.-## 25. OPEN: `company start` / `company serve` from a `bun add -g` install stops with `Project not built. Run "company build" first.`+## 25. `company start` / `company serve` from a `bun add -g` install stops with `Project not built. Run "company build" first.`-**Status**: open in 0.2.0 and 0.2.1 (found 2026-09-12 by running the README steps in a clean Ubuntu 24.04 container; the fix is small but has not shipped). Affects every registry install, including the installer scripts and the GCP / AWS VM templates, which end in `company serve`. The desktop app is unaffected.+**Status**: fixed after 0.2.1 (2026-10-09); 0.2.0 and 0.2.1 are affected (found 2026-09-12 by running the README steps in a clean Ubuntu 24.04 container). Affects every registry install of those releases, including the installer scripts and the GCP / AWS VM templates, which end in `company serve`. The desktop app is unaffected.**Symptom**: `bun add -g @zeenie-ai/opencompany` (or `install.sh` / `install.ps1`) provisions the Python side fine, then the first `company start` prints `Error: Project not built. Run "company build" first.` and exits.**Root cause**: `cli/buildenv.py::validate_build` requires a `node_modules/` directory next to the package for every verb. That is an npm-era layout assumption: `npm install -g` nested a package's dependencies under the package, while bun keeps a global package's dependencies in its own global tree, so the directory never exists. Nothing at runtime needs it: `company start` is uvicorn plus the built SPA, and the JS executor sidecar is a self-contained bundle. Only `company dev` (Vite) genuinely needs `node_modules`.-**Workaround**: run `company build` once from the installed package (it runs `bun install` there, which creates the directory), then `company start`. **Fix, when shipped**: require `node_modules` only for `dev`; keep the server venv and the built client as the check for `start` / `serve`.+**Workaround** (0.2.0 and 0.2.1): run `company build` once from the installed package (it runs `bun install` there, which creates the directory), then `company start`. **Fix**: `validate_build` requires `node_modules` only for `dev`; `start` and `serve` check the server venv and the built client. Locked by `cli/tests/test_buildenv.py`.## 26. OPEN: JS / TS executor nodes fail on a registry install because the sidecar bundle is not in the tarball