Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(devbox): add devbox:sync via mutagen (#59225)

Raúl Negrón-Otero9a46acc53774
diff --git a/.agents/skills/setting-up-devbox/SKILL.md b/.agents/skills/setting-up-devbox/SKILL.md
index 2159b41e916f..c4a3ad144768 100644
--- a/.agents/skills/setting-up-devbox/SKILL.md
+++ b/.agents/skills/setting-up-devbox/SKILL.md
@@ -1,6 +1,6 @@
---
name: setting-up-devbox
-description: Guide a PostHog engineer through spinning up, connecting to, and running commands on a remote devbox (a Coder workspace running the full PostHog stack). Use when asked to set up a devbox, start or connect to a devbox, configure remote dev, get gh CLI / Claude Code authed on a devbox, run a command on a devbox, or diagnose why a devbox command fails. Covers the tailnet prerequisite, hogli devbox commands, Coder user secrets for auth, and verifying with devbox:exec. How each dev personalizes their box is left to them.
+description: Guide a PostHog engineer through spinning up, connecting to, running commands on, and mirroring local code to a remote devbox (a Coder workspace running the full PostHog stack). Use when asked to set up a devbox, start or connect to a devbox, configure remote dev, get gh CLI / Claude Code authed on a devbox, run a command on a devbox, sync a local checkout so you can edit locally while the stack runs remotely (devbox:sync), or diagnose why a devbox command fails. Covers the tailnet prerequisite, hogli devbox commands, Coder user secrets for auth, one-way local->remote sync via mutagen, and verifying with devbox:exec. How each dev personalizes their box is left to them.
---
# Setting up a PostHog devbox
@@ -25,7 +25,7 @@ A safe probe — it never prompts or mutates host config (unlike `devbox:setup`)
### 2. One-time local setup — `hogli devbox:setup`
-Interactive: checks Tailscale + Coder reachability, installs and authenticates the `coder` CLI, and writes the SSH host entries that `devbox:ssh`/`devbox:exec` rely on. It then _offers_ git identity, git signing, a dotfiles repo, and your Claude token — all optional; `--skip-*` anything you don't want. Re-run one step with its flag, e.g. `hogli devbox:setup --configure-git-signing`.
+Interactive: checks Tailscale + Coder reachability, installs and authenticates the `coder` CLI (plus the pinned mutagen binary that backs `devbox:sync`), and writes the SSH host entries that `devbox:ssh`/`devbox:exec` rely on. It then _offers_ git identity, git signing, a dotfiles repo, and your Claude token — all optional; `--skip-*` anything you don't want. Re-run one step with its flag, e.g. `hogli devbox:setup --configure-git-signing`.
### 3. Start and connect — `hogli devbox:start`
@@ -69,6 +69,28 @@ Wrap commands in `bash -lc '...'`: a non-login shell doesn't reliably source `~/
`devbox:exec` is not side-effect-free: like every `devbox:*` command it runs the reachability check first, which on Linux may `sudo tailscale set --accept-routes` and prompt for a password. Run `hogli devbox:setup` once interactively so routes and SSH config are in place before an agent drives `devbox:exec` unattended.
+## Editing locally, running on the box — `hogli devbox:sync`
+
+When you want your fast local checkout to stay the place you edit but the heavy stack (`hogli up`) to run on the box, `hogli devbox:sync` mirrors your repo onto the box over [mutagen](https://mutagen.io), one-way: local is the source of truth, nothing comes back. Reach for this in an agentic loop — edit with your normal local tools, let the mirror carry each change, and drive the remote stack with `devbox:exec` — instead of committing and pushing every iteration or editing over Remote-SSH.
+
+```bash
+hogli devbox:start # the box must be running first
+hogli devbox:sync # create the mirror (idempotent: re-run just reports status)
+# edit files locally — changes propagate within seconds
+hogli devbox:exec -- bash -lc 'cd ~/posthog && pnpm --filter=@posthog/frontend typescript:check'
+hogli devbox:sync --status # watching / paused / conflicts
+hogli devbox:sync --terminate # tear the mirror down when done
+```
+
+The non-obvious parts:
+
+- **It runs on your machine and pushes to the box — not the reverse.** Don't invoke it through `devbox:exec`. It mirrors whichever checkout you run it from (it walks up from the cwd for `hogli.yaml` + `.git`), so run it from the repo root you are editing — including a `/wt` worktree.
+- **`one-way-safe` preserves remote-only files.** The AMI's prewarmed `node_modules`, venv, and `target/` are never deleted — they aren't in your local checkout and the mode leaves remote-only content alone. Lockfiles _do_ sync, so the box reconciles deps on its next start.
+- **The first sync of a feature branch conflicts per diverged file.** The AMI is always on `master`; every file your branch changed relative to the box's `master` surfaces as a conflict in `--status`. That is expected one-way-safe behavior, and it is per-path — non-conflicting files (including brand-new ones) still sync. Resolve a path, or check the matching branch out on the box, only if you specifically need that file mirrored.
+- **Don't also edit those files on the box.** Editing over Remote-SSH while the mirror is live fights the local source of truth; `devbox:open --vscode|--cursor` warns when a sync is active for exactly this reason.
+
+The packaged ignore defaults are seeded once to `~/.hogli/mutagen.yml` and never overwritten — it is yours to tweak. If a newer hogli ships updated ignore defaults, `rm ~/.hogli/mutagen.yml` and re-run `devbox:setup` to pick them up.
+
## Persistence & multiple boxes
- `devbox:stop` → `devbox:start` and template/AMI updates preserve `/home` (the instance is stopped, not terminated). A `devbox:destroy` wipes it — intentional, so don't keep anything irreplaceable only inside a box.
diff --git a/hogli.yaml b/hogli.yaml
index 98712846147d..6f560c869630 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -189,6 +189,9 @@ devbox:
devbox:cleanup:disk:
click: hogli_commands.devbox.cli:devbox_cleanup_disk
description: Free disk space by cleaning caches and build artifacts
+ devbox:sync:
+ click: hogli_commands.devbox.sync:cmd_sync
+ description: Mirror your local PostHog checkout to a devbox
devbox:task:
click: hogli_commands.devbox.cli:devbox_task
description: Run a background agent task on a fresh devbox
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.py
index 1dbdaa581bee..35ffba38d501 100644
--- a/tools/hogli-commands/hogli_commands/devbox/cli.py
+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py
@@ -21,6 +21,7 @@ from typing import Any
import click
from hogli.manifest import get_manifest
+from . import mutagen
from .coder import (
CLAUDE_CODE_OAUTH_ENV,
DEFAULT_PRESET,
@@ -245,6 +246,10 @@ def _print_connection_info(name: str) -> None:
for label, command in commands:
click.echo(f" {label:<8} hogli {command}{suffix}")
+ if not mutagen.sync_list(label_selector=mutagen.workspace_label_selector(name)):
+ click.echo()
+ click.echo(f" Tip: run `hogli devbox:sync{suffix}` to mirror your local checkout to this devbox.")
+
def _workspace_arg_suffix(name: str) -> str:
"""Return the optional CLI suffix for a named workspace."""
@@ -266,6 +271,40 @@ def _workspace_status_color(status: str) -> str:
return WORKSPACE_STATUS_COLORS.get(status, "white")
+def _ljust_styled(text: str, width: int) -> str:
+ """Left-justify a click-styled string to ``width`` *visible* columns.
+
+ A plain ``f"{text:<width}"`` counts the invisible ANSI escape codes toward
+ the width and under-pads colored cells; measure off the unstyled text so
+ columns line up with their (unstyled) headers.
+ """
+ return text + " " * max(0, width - len(click.unstyle(text)))
+
+
+def _render_sync_status(workspace_name: str) -> str:
+ """Return a single-line summary of the mutagen sync state for a workspace.
+
+ Reads the first session matching the workspace label. If multiple sessions
+ happen to share the label (shouldn't happen via hogli, but possible via
+ direct mutagen use), only the first is rendered -- intentionally simple.
+ """
+ sessions = mutagen.sync_list(label_selector=mutagen.workspace_label_selector(workspace_name))
+ if not sessions:
+ return click.style("○ not configured", fg="white")
+ session = sessions[0]
+ if session.get("paused"):
+ return click.style("⚠ paused", fg="yellow")
+ conflicts = mutagen.conflict_count(session)
+ if conflicts:
+ return click.style(f"⚠ {conflicts} conflict{'s' if conflicts != 1 else ''}", fg="red")
+ status = str(session.get("status", "")).strip() or "running"
+ # mutagen reports a stalled sync (box stopped, remote root gone) as a
+ # `disconnected`/`halted-*` status; a green dot there would read as healthy.
+ if status == "disconnected" or status.startswith("halted"):
+ return click.style(f"✗ {status}", fg="red")
+ return click.style(f"● {status}", fg="green")
+
+
def _sync_workspace_parameters(name: str) -> None:
"""Push local config (git identity, dotfiles) to workspace parameters before start.
@@ -970,6 +1009,7 @@ def _confirm_run_setup() -> bool:
click.echo("hogli devbox:setup will check or configure:")
click.echo(" - Tailscale + Coder reachability")
click.echo(" - Local SSH config for Coder hosts")
+ click.echo(" - File sync tooling (mutagen) for devbox:sync")
click.echo(" - Git identity (name/email) for new workspaces")
click.echo(" - Git commit signing key propagation")
click.echo(" - Preferred region for new workspaces (optional)")
@@ -1053,6 +1093,9 @@ def devbox_setup(
click.echo("Aborted. Re-run `hogli devbox:setup` when ready.")
return
+ mutagen.ensure_mutagen_installed(verbose=verbose)
+ mutagen.register_daemon()
+ mutagen.ensure_user_mutagen_config()
maybe_configure_ssh(
configure_ssh=configure_ssh,
identity_agent_socket=_resolve_local_identity_agent_for_coder(),
@@ -1075,14 +1118,18 @@ def devbox_list() -> None:
if not workspaces:
click.echo("No devboxes found. Run 'hogli devbox:start' to create one.")
else:
- click.echo(f"{'LABEL':<16} {'STATUS':<12} {'REGION':<14} {'NAME'}")
+ click.echo(f"{'LABEL':<16} {'STATUS':<12} {'REGION':<14} {'SYNC':<18} {'NAME'}")
for ws in workspaces:
ws_name = ws.get("name", "")
label = extract_workspace_label(ws_name) or "(default)"
status = get_workspace_status(ws)
region = get_workspace_region(ws) or "unknown"
styled_status = click.style(status, fg=_workspace_status_color(status))
- click.echo(f" {label:<14} {styled_status:<20} {region:<14} {ws_name}")
+ sync_state = _render_sync_status(ws_name)
+ click.echo(
+ f" {label:<14} {_ljust_styled(styled_status, 12)} "
+ f"{region:<14} {_ljust_styled(sync_state, 18)} {ws_name}"
+ )
shared = list_shared_workspaces()
if shared:
@@ -1326,6 +1373,10 @@ def devbox_update(workspace: str | None, verbose: bool) -> None:
click.echo(f"Updating '{name}' to the latest template...")
update_workspace(name, parameters=params, verbose=verbose)
click.echo("Updated.")
+ click.echo(
+ "Note: if your local lockfiles differ from the new AMI's baked versions, "
+ "expect a one-time dep re-install on next workspace start (2-5 min)."
+ )
_print_connection_info(name)
@@ -1379,6 +1430,15 @@ def devbox_open(workspace: str | None, vscode: bool, cursor: bool, web: bool) ->
ensure_runtime_ready()
name, _ = resolve_workspace_name(workspace)
+ if (vscode or cursor) and mutagen.sync_list(label_selector=mutagen.workspace_label_selector(name)):
+ ide = "VS Code" if vscode else "Cursor"
+ click.echo(
+ click.style(
+ f"⚠ Sync is active for '{name}'. Editing in {ide} Remote can conflict with the local source of truth.",
+ fg="yellow",
+ )
+ )
+
if vscode:
click.echo(f"Opening '{name}' in VS Code...")
open_vscode(name)
@@ -1584,6 +1644,16 @@ def devbox_destroy(workspace: str | None, verbose: bool) -> None:
click.echo("Cancelled.")
return
+ label = mutagen.workspace_label_selector(name)
+ if mutagen.sync_list(label_selector=label):
+ try:
+ mutagen.sync_terminate(label)
+ click.echo("Sync session terminated.")
+ except SystemExit:
+ # Best-effort: a stuck mutagen daemon should not block the user
+ # from destroying their devbox. The session ends with the remote.
+ click.echo(click.style("Warning: failed to terminate sync session; continuing.", fg="yellow"))
+
delete_workspace(name, verbose=verbose)
click.echo("Destroyed.")
@@ -1605,6 +1675,7 @@ def devbox_status(workspace: str | None) -> None:
click.echo(f" Name: {name}")
click.echo(f" Status: {click.style(status, fg=_workspace_status_color(status))}")
click.echo(f" Region: {get_workspace_region(ws) or 'unknown'}")
+ click.echo(f" Sync: {_render_sync_status(name)}")
if ws.get("outdated"):
click.echo(click.style(" Update: template update available", fg="yellow"))
diff --git a/tools/hogli-commands/hogli_commands/devbox/mutagen.py b/tools/hogli-commands/hogli_commands/devbox/mutagen.py
new file mode 100644
index 000000000000..da6ff425d494
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/devbox/mutagen.py
@@ -0,0 +1,406 @@
+"""Mutagen CLI wrapper for one-way local->remote file sync.
+
+Mirrors ``coder.py`` shape: a managed binary lives in ``~/.hogli/bin/``,
+version is pinned, and all subprocess interactions are isolated behind thin
+wrappers. v1 only targets Coder workspaces as the remote endpoint.
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+import hashlib
+import platform
+import subprocess
+from pathlib import Path
+from typing import Any
+
+import click
+
+from .coder import _fail
+
+_MANAGED_MUTAGEN_DIR = Path.home() / ".hogli" / "bin"
+_MUTAGEN_VERSION = "0.18.1"
+_RELEASE_URL_TEMPLATE = (
+ "https://github.com/mutagen-io/mutagen/releases/download/v{version}/mutagen_{os}_{arch}_v{version}.tar.gz"
+)
+
+# Pinned SHA256 of each release tarball, from the v0.18.1 `SHA256SUMS` asset.
+# The download is unverified TLS-only without this, so a MITM or tampered
+# release could execute arbitrary code on the engineer's machine on every sync.
+# Bump these in lockstep with `_MUTAGEN_VERSION`.
+_MUTAGEN_SHA256 = {
+ ("darwin", "amd64"): "7d06f7d8fcfe90bc7e55cc834a2f2f20c2e0af9ea9bc35911fc4341ad56a9bbf",
+ ("darwin", "arm64"): "6f810416d9e5fc4fd5e18431146f8b3c5a2056ba5a24f76c1e66da86eb3257e2",
+ ("linux", "amd64"): "7735286c778cc438418209f24d03a64f3a0151c8065ef0fe079cfaf093af6f8f",
+ ("linux", "arm64"): "bcba735aebf8cbc11da9b3742118a665599ac697fa06bc5751cac8dcd540db8a",
+}
+
+
+def _mutagen_platform() -> tuple[str, str]:
+ """Map the host to mutagen's ``(os, arch)`` release naming, or fail if unsupported.
+
+ ``os`` is ``darwin``/``linux`` and ``arch`` is ``amd64``/``arm64``.
+ Verified against the v0.18.1 release on GitHub.
+ """
+ system = platform.system().lower()
+ if system not in ("darwin", "linux"):
+ _fail(f"Unsupported OS for mutagen install: {system}. hogli devbox:sync supports macOS and Linux only.")
+
+ machine = platform.machine().lower()
+ if machine in ("x86_64", "amd64"):
+ arch = "amd64"
+ elif machine in ("arm64", "aarch64"):
+ arch = "arm64"
+ else:
+ _fail(f"Unsupported CPU arch for mutagen install: {machine}. hogli devbox:sync supports amd64 and arm64 only.")
+
+ return system, arch
+
+
+def _mutagen_release_url(version: str = _MUTAGEN_VERSION) -> str:
+ """Build the GitHub release tarball URL for the current platform."""
+ system, arch = _mutagen_platform()
+ return _RELEASE_URL_TEMPLATE.format(version=version, os=system, arch=arch)
+
+
+def _mutagen_bin() -> str:
+ """Return the path to the hogli-managed mutagen binary, falling back to PATH."""
+ managed = _MANAGED_MUTAGEN_DIR / "mutagen"
+ if managed.is_file():
+ return str(managed)
+ return shutil.which("mutagen") or "mutagen"
+
+
+def _run(args: list[str], *, capture_output: bool = False) -> subprocess.CompletedProcess[str]:
+ """Run a mutagen subprocess with consistent text handling.
+
+ A leading ``"mutagen"`` arg is rewritten to the managed binary path so
+ callers can write the natural ``["mutagen", ...]`` invocation.
+ """
+ resolved = args
+ if args and args[0] == "mutagen":
+ resolved = [_mutagen_bin(), *args[1:]]
+ return subprocess.run(resolved, capture_output=capture_output, text=True)
+
+
+def mutagen_installed() -> bool:
+ """Return whether the mutagen CLI is available (managed or on PATH)."""
+ return (_MANAGED_MUTAGEN_DIR / "mutagen").is_file() or shutil.which("mutagen") is not None
+
+
+def get_installed_mutagen_version() -> str | None:
+ """Return the installed mutagen CLI version, or ``None`` if undetermined.
+
+ ``mutagen version`` prints ``X.Y.Z`` on a single line.
+ """
+ result = _run(["mutagen", "version"], capture_output=True)
+ if result.returncode != 0:
+ return None
+ version = (result.stdout or "").strip()
+ return version or None
+
+
+def _install_mutagen(*, verbose: bool = False) -> None:
+ """Install mutagen into ``~/.hogli/bin`` from the official GitHub release.
+
+ Downloads the release tarball, verifies it against the pinned SHA256, then
+ extracts both ``mutagen`` and ``mutagen-agents.tar.gz`` into the managed
+ directory. Verification happens before extraction so a tampered or MITMed
+ tarball never reaches disk as an executable. The agents archive is unpacked
+ lazily by mutagen on first sync to ``~/.mutagen-agents/`` -- we just have to
+ ship it next to the binary.
+ """
+ system, arch = _mutagen_platform()
+ expected_sha = _MUTAGEN_SHA256.get((system, arch))
+ if expected_sha is None:
+ _fail(f"No pinned mutagen checksum for {system}/{arch}; refusing to install an unverified binary.")
+
+ url = _mutagen_release_url()
+ click.echo(f"Installing mutagen CLI v{_MUTAGEN_VERSION}...")
+
+ _MANAGED_MUTAGEN_DIR.mkdir(parents=True, exist_ok=True)
+ tarball = _MANAGED_MUTAGEN_DIR / f"mutagen_{system}_{arch}_v{_MUTAGEN_VERSION}.tar.gz"
+
+ # Run curl and tar directly (no shell): the inputs aren't user-controlled,
+ # but argv avoids any quoting/injection surface and needs no pipefail dance.
+ download = ["curl", "-fsSL", "-o", str(tarball), url]
+ result = subprocess.run(download, text=True, capture_output=not verbose)
+ if result.returncode != 0:
+ if not verbose:
+ click.echo(result.stdout or "")
+ click.echo(result.stderr or "", err=True)
+ tarball.unlink(missing_ok=True)
+ _fail(f"Mutagen download failed.\nTry manually: {' '.join(download)}")
+
+ actual_sha = hashlib.sha256(tarball.read_bytes()).hexdigest()
+ if actual_sha != expected_sha:
+ tarball.unlink(missing_ok=True)
+ _fail(
+ f"Mutagen tarball checksum mismatch for {system}/{arch}.\n"
+ f" expected {expected_sha}\n"
+ f" got {actual_sha}\n"
+ "Refusing to install a tampered or corrupt binary."
+ )
+
+ extract = ["tar", "-xz", "-C", str(_MANAGED_MUTAGEN_DIR), "-f", str(tarball), "mutagen", "mutagen-agents.tar.gz"]
+ result = subprocess.run(extract, text=True, capture_output=not verbose)
+ tarball.unlink(missing_ok=True)
+ if result.returncode != 0:
+ if not verbose:
+ click.echo(result.stdout or "")
+ click.echo(result.stderr or "", err=True)
+ _fail(f"Mutagen extraction failed.\nTry manually: {' '.join(extract)}")
+
+ managed = _MANAGED_MUTAGEN_DIR / "mutagen"
+ if not managed.is_file():
+ _fail(f"Mutagen install reported success but {managed} is missing.")
+
+
+def ensure_mutagen_installed(*, verbose: bool = False) -> None:
+ """Install mutagen at the pinned version, or reinstall on mismatch."""
+ if not mutagen_installed():
+ _install_mutagen(verbose=verbose)
+ return
+
+ installed = get_installed_mutagen_version()
+ if installed is None:
+ # Binary is present but `mutagen version` failed -- treat it as broken
+ # (truncated download, incompatible libc) and reinstall rather than
+ # silently shipping a CLI that crashes on the next sync command.
+ click.echo("mutagen CLI is present but not runnable; reinstalling.")
+ _install_mutagen(verbose=verbose)
+ elif installed != _MUTAGEN_VERSION:
+ click.echo(f"mutagen CLI v{installed} does not match expected v{_MUTAGEN_VERSION}.")
+ _install_mutagen(verbose=verbose)
+ else:
+ click.echo("mutagen CLI is installed.")
+
+
+def register_daemon() -> None:
+ """Install the mutagen daemon's autostart hook (LaunchAgent / systemd user unit).
+
+ Idempotent on mutagen's side -- re-running just re-applies the same hook.
+ Best-effort: any failure is logged as a warning, not fatal, because the
+ daemon will still start on demand the first time a sync command runs;
+ autostart just means it survives reboots without intervention.
+ """
+ result = _run(["mutagen", "daemon", "register"], capture_output=True)
+ if result.returncode != 0:
+ stderr = (result.stderr or "").strip()
+ click.echo(
+ click.style(
+ "Warning: `mutagen daemon register` failed; sync will still work "
+ "but the daemon won't auto-restart after reboot.",
+ fg="yellow",
+ )
+ )
+ if stderr:
+ click.echo(f" {stderr}", err=True)
+
+
+# ---------------------------------------------------------------------------
+# User config
+# ---------------------------------------------------------------------------
+
+_USER_CONFIG_PATH = Path.home() / ".hogli" / "mutagen.yml"
+_PACKAGED_DEFAULTS = Path(__file__).parent / "mutagen_defaults.yml"
+
+
+def user_mutagen_config_path() -> Path:
+ """Return the path where the user-editable mutagen defaults live."""
+ return _USER_CONFIG_PATH
+
+
+def _config_seed_path(config_path: Path) -> Path:
+ """Sidecar recording the hash of the defaults we last seeded into ``config_path``."""
+ return config_path.with_name(f".{config_path.name}.seed")
+
+
+def ensure_user_mutagen_config() -> Path:
+ """Seed (and refresh) ``~/.hogli/mutagen.yml`` from the packaged defaults.
+
+ The user file is intentionally editable, so edits are never clobbered. But an
+ *untouched* copy is refreshed when the packaged defaults change: we record the
+ hash of what we seeded in a sidecar and overwrite only while the on-disk file
+ still matches that recorded seed. Without this, a shipped fix to the ignore
+ list (e.g. a newly-ignored build dir) would stay dead forever for anyone who
+ seeded an older copy. A file whose contents differ from the recorded seed is
+ treated as user-owned and left alone (so pre-sidecar files are preserved --
+ delete them to re-seed).
+ """
+ target = user_mutagen_config_path()
+ packaged = _PACKAGED_DEFAULTS.read_text()
+ packaged_hash = hashlib.sha256(packaged.encode()).hexdigest()
+ seed_path = _config_seed_path(target)
+
+ if not target.exists():
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(packaged)
+ seed_path.write_text(packaged_hash)
+ return target
+
+ current_hash = hashlib.sha256(target.read_text().encode()).hexdigest()
+ if current_hash == packaged_hash:
+ seed_path.write_text(packaged_hash) # keep the sidecar in step for the next bump
+ return target
+
+ seeded_hash = seed_path.read_text().strip() if seed_path.exists() else None
+ if seeded_hash == current_hash:
+ # Untouched since we seeded it, but the packaged defaults changed -- refresh.
+ target.write_text(packaged)
+ seed_path.write_text(packaged_hash)
+ return target
+
+
+# Single source of truth for the label hogli stamps on every sync session, so the
+# create side (sync_create) and the lookup side (selector) can never drift apart.
+_WORKSPACE_LABEL_KEY = "hogli-workspace"
+
+
+def workspace_labels(workspace: str) -> dict[str, str]:
+ """Return the labels hogli attaches when creating a sync session for ``workspace``."""
+ return {_WORKSPACE_LABEL_KEY: workspace}
+
+
+def workspace_label_selector(workspace: str) -> str:
+ """Return the mutagen ``--label-selector`` string for a hogli workspace."""
+ return f"{_WORKSPACE_LABEL_KEY}={workspace}"
+
+
+def conflict_count(session: dict[str, Any]) -> int:
+ """Return a session's true conflict count.
+
+ ``mutagen sync list`` caps the inline ``conflicts`` array (10 by default)
+ and reports the remainder as ``excludedConflicts`` -- summing both is the
+ only way to get the real total. Reading just ``len(conflicts)`` silently
+ undercounts and pins the display at 10 for any heavily-diverged sync.
+ """
+ shown = session.get("conflicts") or []
+ excluded = session.get("excludedConflicts") or 0
+ try:
+ return len(shown) + int(excluded)
+ except (TypeError, ValueError):
+ return len(shown)
+
+
+# ---------------------------------------------------------------------------
+# Sync session wrappers
+# ---------------------------------------------------------------------------
+
+# `mutagen sync list` exits 1 with "no sessions" when a label selector matches
+# nothing. We treat that as "empty list", not as an error.
+_NO_SESSIONS_MARKERS = ("no sessions", "no synchronization sessions")
+
+
+def sync_create(
+ *,
+ name: str,
+ src: str,
+ dst: str,
+ config_path: Path | None,
+ labels: dict[str, str],
+) -> None:
+ """Create a one-way-safe sync session from ``src`` to ``dst``.
+
+ ``one-way-safe`` propagates local->remote, preserves remote-only files
+ (so the AMI's prewarmed ``node_modules`` / ``target`` / ``.venv`` survive
+ even outside the ignore list), and surfaces conflicts when remote files
+ diverge from local.
+ """
+ args: list[str] = [
+ "mutagen",
+ "sync",
+ "create",
+ "--name",
+ name,
+ "--mode",
+ "one-way-safe",
+ "--ignore-vcs",
+ ]
+ if config_path is not None:
+ args += ["--configuration-file", str(config_path)]
+ for key, value in labels.items():
+ args += ["--label", f"{key}={value}"]
+ args += [src, dst]
+
+ result = _run(args)
+ if result.returncode != 0:
+ _fail(f"Failed to create mutagen sync session '{name}'.")
+
+
+def sync_list(*, label_selector: str | None = None) -> list[dict[str, Any]]:
+ """Return sync sessions as parsed JSON dicts.
+
+ Uses mutagen's ``--template '{{ json . }}'`` to render sessions through
+ its public model types. Returns ``[]`` when no matching session exists,
+ when mutagen isn't installed yet, or when the daemon is offline -- the
+ callers treat all three cases as "no active sync", which is correct.
+ """
+ if not mutagen_installed():
+ return []
+
+ args: list[str] = ["mutagen", "sync", "list", "--template", "{{ json . }}"]
+ if label_selector:
+ args += ["--label-selector", label_selector]
+
+ try:
+ result = _run(args, capture_output=True)
+ except FileNotFoundError:
+ return []
+ if result.returncode != 0:
+ return []
+
+ stdout = (result.stdout or "").strip()
+ if not stdout:
+ return []
+ try:
+ parsed = json.loads(stdout)
+ except json.JSONDecodeError:
+ return []
+ if not isinstance(parsed, list):
+ return []
+ return [s for s in parsed if isinstance(s, dict)]
+
+
+def _label_op(verb: str, label_selector: str) -> None:
+ """Run a label-scoped sync lifecycle command (terminate/pause/resume/flush).
+
+ No-ops when nothing matches the selector. ``sync_list`` is resilient to a
+ missing binary or an offline daemon, so this both keeps "no session" a
+ silent success and prevents a raw ``FileNotFoundError`` crash on a machine
+ that never installed mutagen (the lifecycle flags skip the install step).
+ """
+ if not label_selector:
+ _fail(f"Refusing to {verb} sync sessions without a label selector.")
+ if not sync_list(label_selector=label_selector):
+ return
+ args = ["mutagen", "sync", verb, "--label-selector", label_selector]
+ result = _run(args, capture_output=True)
+ if result.returncode != 0:
+ combined = (result.stdout or "") + (result.stderr or "")
+ # The session may have vanished between the list and the op (a race).
+ if any(marker in combined.lower() for marker in _NO_SESSIONS_MARKERS):
+ return
+ click.echo((result.stderr or result.stdout or "").strip(), err=True)
+ _fail(f"`mutagen sync {verb}` failed for selector {label_selector!r}.")
+
+
+def sync_terminate(label_selector: str) -> None:
+ """Terminate sync sessions matching the label selector. No-op if none exist."""
+ _label_op("terminate", label_selector)
+
+
+def sync_pause(label_selector: str) -> None:
+ """Pause sync sessions matching the label selector. No-op if none exist."""
+ _label_op("pause", label_selector)
+
+
+def sync_resume(label_selector: str) -> None:
+ """Resume sync sessions matching the label selector. No-op if none exist."""
+ _label_op("resume", label_selector)
+
+
+def sync_flush(label_selector: str) -> None:
+ """Flush sync sessions matching the label selector. No-op if none exist."""
+ _label_op("flush", label_selector)
diff --git a/tools/hogli-commands/hogli_commands/devbox/mutagen_defaults.yml b/tools/hogli-commands/hogli_commands/devbox/mutagen_defaults.yml
new file mode 100644
index 000000000000..278d541bd2f7
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/devbox/mutagen_defaults.yml
@@ -0,0 +1,73 @@
+sync:
+ defaults:
+ mode: one-way-safe
+ ignore:
+ vcs: true
+ paths:
+ # `vcs: true` ignores the `.git/` *directory*, but a git worktree
+ # checkout (e.g. `/wt`) has `.git` as a *file* (gitdir pointer),
+ # which it doesn't catch -- it would conflict with the remote's
+ # real `.git` directory on every sync. Ignore the name outright.
+ - '.git'
+
+ # Per-language deps -- OS-incompatible, prewarmed on remote AMI.
+ - 'node_modules'
+ - '.venv'
+ # PostHog's Python venv lives under `.flox/cache/venv` (flox), not
+ # `.venv`. Ignore only flox's machine-local subdirs (mirrors
+ # `.flox/.gitignore`); the tracked `.flox/env*` definition still
+ # syncs so dev-environment edits reach the box.
+ - '.flox/cache'
+ - '.flox/run'
+ - '.flox/lib'
+ - '.flox/log'
+ - '**/__pycache__'
+ - '*.pyc'
+ - '*.egg-info'
+ # Compiled native artifacts (e.g. the built hogql_parser
+ # extension) are OS-specific -- never round-trip macOS .so/.dylib
+ # onto the Linux box.
+ - '*.so'
+ - '*.dylib'
+ - '.pnpm-store'
+ - 'target'
+ - 'rust/target'
+ - 'funnel-udf/target'
+
+ # Generated source (don't round-trip).
+ - 'posthog/hogql/grammar/HogQLLexer.py'
+ - 'posthog/hogql/grammar/HogQLLexer.interp'
+ - 'posthog/hogql/grammar/HogQLLexer.tokens'
+ - 'posthog/hogql/grammar/HogQLParser.py'
+ - 'posthog/hogql/grammar/HogQLParser.interp'
+ - 'posthog/hogql/grammar/HogQLParser.tokens'
+ - 'posthog/hogql/grammar/HogQLParserVisitor.py'
+ # NB: don't ignore all of `common/hogql_parser` -- it holds
+ # hand-maintained C++ sources (error.cpp, parser_python.cpp,
+ # CMakeLists.txt...) that must sync. Its build outputs are caught
+ # by the *.so/build/dist/.cache/build_wasm ignores instead.
+ - 'common/hogql_parser/.cache'
+ - 'common/hogql_parser/build_wasm'
+ - 'frontend/types'
+ - 'frontend/dist'
+ - 'frontend/.cache'
+
+ # Build outputs.
+ - '.next'
+ - 'dist'
+ - 'build'
+ - '.turbo'
+ - '.parcel-cache'
+
+ # Runtime / user-local state.
+ - '.posthog/.generated'
+ - '.dagster_home'
+ - 'mprocs.log'
+ - 'bin/start.lock'
+ - '.env.local'
+
+ # Editor / OS.
+ - '.idea'
+ - '.vscode'
+ - '.cursor'
+ - '.DS_Store'
diff --git a/tools/hogli-commands/hogli_commands/devbox/sync.py b/tools/hogli-commands/hogli_commands/devbox/sync.py
new file mode 100644
index 000000000000..6d10b992fb13
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/devbox/sync.py
@@ -0,0 +1,237 @@
+"""`hogli devbox:sync` -- one-way-safe local->remote file sync for Coder devboxes.
+
+Lets engineers edit code locally while running the full PostHog dev stack
+on a Coder devbox. Local is the source of truth; nothing flows back to local
+automatically. Sessions are addressed by mutagen label, not name, so multiple
+workspaces stay independently controllable.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+from typing import Any
+
+import click
+
+from . import mutagen
+from .cli import _workspace_arg_suffix, resolve_workspace_name, workspace_argument
+from .coder import _fail, ensure_runtime_ready, get_workspace, get_workspace_status
+
+_REMOTE_REPO_PATH = "/home/coder/posthog"
+
+
+def _detect_local_posthog_checkout() -> Path:
+ """Find the local PostHog checkout root by walking up from cwd.
+
+ A checkout is identified by a co-located ``hogli.yaml`` and ``.git``
+ directory at the same level. Bails with a hint if we can't find one --
+ running ``hogli devbox:sync`` from anywhere outside the repo is almost
+ certainly a mistake.
+ """
+ cwd = Path.cwd().resolve()
+ for candidate in (cwd, *cwd.parents):
+ if (candidate / "hogli.yaml").is_file() and (candidate / ".git").exists():
+ return candidate
+ _fail(
+ "Could not find a PostHog checkout above the current directory.\n"
+ "Run `hogli devbox:sync` from inside a `posthog` clone."
+ )
+ raise SystemExit(1) # unreachable; helps the type checker see no fall-through
+
+
+def _ensure_ssh_config_for_workspace(workspace: str) -> None:
+ """Ensure ``ssh coder.{workspace}`` resolves before mutagen tries to dial it.
+
+ We check via ``ssh -G`` (which never connects, just resolves config). If
+ the host has no specific entry, mutagen would fail with an opaque SSH
+ error; we'd rather tell the user to rerun setup.
+ """
+ host = f"coder.{workspace}"
+ result = subprocess.run(["ssh", "-G", host], capture_output=True, text=True)
+ if result.returncode != 0:
+ _fail(
+ f"SSH config for `{host}` is missing. Run `hogli devbox:setup` to install "
+ "Coder workspace entries into your ~/.ssh/config."
+ )
+
+
+def _format_session_status(session: dict[str, Any]) -> str:
+ """Render a single mutagen session as a few short lines."""
+ name = session.get("name") or session.get("identifier", "?")
+ paused = session.get("paused", False)
+ status = session.get("status", "")
+ alpha = session.get("alpha", {})
+ beta = session.get("beta", {})
+ alpha_path = alpha.get("path", "?") if isinstance(alpha, dict) else "?"
+ beta_path = beta.get("path", "?") if isinstance(beta, dict) else "?"
+ state = "paused" if paused else (status or "running")
+ lines = [
+ f" {name}",
+ f" state: {state}",
+ f" alpha: {alpha_path}",
+ f" beta: {beta_path}",
+ ]
+ # Conflicts are the whole point of one-way-safe: a remote file diverged and
+ # mutagen refused to overwrite it. Surface them or the sync looks healthy
+ # while the user's edits silently never land. Conflicts are per-path: only
+ # the diverged paths are blocked, everything else keeps syncing.
+ conflicts = mutagen.conflict_count(session)
+ if conflicts:
+ lines.append(
+ f" conflicts: {conflicts} (these paths diverged on the remote and won't sync until resolved; other files are unaffected)"
+ )
+ last_error = session.get("lastError")
+ if last_error:
+ lines.append(f" error: {last_error}")
+ return "\n".join(lines)
+
+
+def _print_sessions(sessions: list[dict[str, Any]]) -> None:
+ """Print the sync sessions returned by mutagen, one per block."""
+ if not sessions:
+ click.echo("No active sync sessions.")
+ return
+ for session in sessions:
+ click.echo(_format_session_status(session))
+
+
+def _session_summary(session: dict[str, Any]) -> dict[str, Any]:
+ """Reduce a raw mutagen session to a stable shape for programmatic callers.
+
+ Agents driving the sync loop need to answer "am I synced, and is anything
+ conflicting?" without scraping human text. ``conflictPaths`` lists only the
+ roots mutagen inlines (capped at 10); ``conflicts`` is the true total, so a
+ caller compares ``len(conflictPaths)`` to ``conflicts`` to know it's seeing
+ a truncated sample.
+ """
+ paused = bool(session.get("paused", False))
+ status = str(session.get("status", "") or "").strip()
+ shown = session.get("conflicts") or []
+ alpha = session.get("alpha") if isinstance(session.get("alpha"), dict) else {}
+ beta = session.get("beta") if isinstance(session.get("beta"), dict) else {}
+ return {
+ "name": session.get("name") or session.get("identifier"),
+ "state": "paused" if paused else (status or "running"),
+ "paused": paused,
+ "conflicts": mutagen.conflict_count(session),
+ "conflictPaths": [c.get("root") for c in shown if isinstance(c, dict) and c.get("root")],
+ "lastError": session.get("lastError"),
+ "alpha": alpha.get("path"),
+ "beta": beta.get("path"),
+ }
+
+
[email protected](name="devbox:sync", help="Mirror your local PostHog checkout to a devbox")
+@workspace_argument
[email protected]("--status", "show_status", is_flag=True, help="Show the current sync state")
+ "--json", "as_json", is_flag=True, help="Print sync state as JSON (implies --status; for scripts and agents)"
+)
[email protected]("--pause", is_flag=True, help="Pause the sync session")
[email protected]("--resume", is_flag=True, help="Resume a paused sync session")
[email protected]("--terminate", is_flag=True, help="Tear down the sync session")
[email protected]("--flush", is_flag=True, help="Force a flush of pending changes")
[email protected]("-v", "--verbose", is_flag=True, help="Show full install output")
+def cmd_sync(
+ workspace: str | None,
+ show_status: bool,
+ as_json: bool,
+ pause: bool,
+ resume: bool,
+ terminate: bool,
+ flush: bool,
+ verbose: bool,
+) -> None:
+ """Create or manage a one-way-safe mutagen sync session for a devbox.
+
+ Default action is an idempotent create: re-running on a workspace that
+ already has a session just prints the status. Use the flag variants to
+ operate on an existing session by label.
+ """
+ chosen = sum([show_status, pause, resume, terminate, flush])
+ if chosen > 1:
+ raise click.UsageError("Pick at most one of --status, --pause, --resume, --terminate, --flush.")
+ if as_json and (pause or resume or terminate or flush):
+ raise click.UsageError("--json reports state only; it can't combine with --pause/--resume/--terminate/--flush.")
+ if workspace and workspace.startswith("@"):
+ # Local is the source of truth: syncing onto another user's box would
+ # push your checkout over theirs. v1 targets your own devboxes only.
+ _fail("devbox:sync only targets your own devboxes; `@user` shared targets are not supported.")
+
+ name, workspaces = resolve_workspace_name(workspace)
+ label = mutagen.workspace_label_selector(name)
+
+ # Lifecycle subcommands don't need the full runtime preflight -- they
+ # just talk to the local mutagen daemon. Keep them fast and offline-safe.
+ if as_json:
+ sessions = mutagen.sync_list(label_selector=label)
+ click.echo(json.dumps([_session_summary(s) for s in sessions]))
+ return
+ if show_status:
+ _print_sessions(mutagen.sync_list(label_selector=label))
+ return
+ if pause:
+ mutagen.sync_pause(label)
+ click.echo(f"Paused sync for {name}.")
+ return
+ if resume:
+ mutagen.sync_resume(label)
+ click.echo(f"Resumed sync for {name}.")
+ return
+ if terminate:
+ mutagen.sync_terminate(label)
+ click.echo(f"Terminated sync for {name}.")
+ return
+ if flush:
+ mutagen.sync_flush(label)
+ click.echo(f"Flushed sync for {name}.")
+ return
+
+ # Default path: idempotent create. Install mutagen and bring the daemon up
+ # first so the existing-session check sees sessions persisted across daemon
+ # restarts; a re-run then short-circuits before the heavier coder/SSH
+ # preflight below. (ensure_runtime_ready covers the coder install check.)
+ mutagen.ensure_mutagen_installed(verbose=verbose)
+ mutagen.register_daemon()
+ if mutagen.sync_list(label_selector=label):
+ click.echo(
+ f"Sync already running for {name}. Use `hogli devbox:sync{_workspace_arg_suffix(name)} --status` to inspect."
+ )
+ return
+
+ ensure_runtime_ready()
+ _ensure_workspace_running(name, workspaces)
+ _ensure_ssh_config_for_workspace(name)
+ config_path = mutagen.ensure_user_mutagen_config()
+
+ local_path = _detect_local_posthog_checkout()
+ click.echo(f"Creating sync: {local_path} -> coder.{name}:{_REMOTE_REPO_PATH}")
+ mutagen.sync_create(
+ name=f"ph-{name}",
+ src=str(local_path),
+ dst=f"coder.{name}:{_REMOTE_REPO_PATH}",
+ config_path=config_path,
+ labels=mutagen.workspace_labels(name),
+ )
+ click.echo("Sync created. Initial scan and copy may take a few minutes for large checkouts.")
+ click.echo(f"Inspect: hogli devbox:sync{_workspace_arg_suffix(name)} --status")
+
+
+def _ensure_workspace_running(name: str, workspaces: list[dict[str, Any]] | None) -> None:
+ """Fail early with a clear message if the target devbox isn't running.
+
+ mutagen dials the box over SSH; a stopped box otherwise surfaces as an
+ opaque connection error partway through the sync. Best-effort: when the
+ workspace list is unavailable (e.g. a shared ``@user`` target) we skip the
+ check rather than block on an unknowable state.
+ """
+ if not workspaces:
+ return
+ workspace = get_workspace(name, workspaces)
+ if workspace is None:
+ return
+ status = get_workspace_status(workspace)
+ if status != "running":
+ _fail(f"Devbox '{name}' is {status}, not running. Run `hogli devbox:start` first.")
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
index 4b49d0975d2c..fbe9b7b76e2b 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import csv
import json
import errno
+import hashlib
import subprocess
from collections.abc import Callable
from pathlib import Path
@@ -18,6 +19,8 @@ from hogli_commands.devbox import (
cli as devbox_cli,
coder,
config as devbox_config,
+ mutagen as devbox_mutagen,
+ sync as devbox_sync,
)
runner = CliRunner()
@@ -3178,3 +3181,659 @@ class TestSetupGitSigning:
devbox_cli.maybe_configure_git_signing(None)
assert upserts == []
+
+
+class TestMutagenReleaseUrl:
+ """Test the platform -> mutagen release URL mapping."""
+
+ @pytest.mark.parametrize(
+ "system, machine, expected_suffix",
+ [
+ ("Darwin", "arm64", "mutagen_darwin_arm64_v0.18.1.tar.gz"),
+ ("Darwin", "x86_64", "mutagen_darwin_amd64_v0.18.1.tar.gz"),
+ ("Linux", "x86_64", "mutagen_linux_amd64_v0.18.1.tar.gz"),
+ ("Linux", "aarch64", "mutagen_linux_arm64_v0.18.1.tar.gz"),
+ ],
+ )
+ def test_url_per_platform(
+ self, monkeypatch: pytest.MonkeyPatch, system: str, machine: str, expected_suffix: str
+ ) -> None:
+ monkeypatch.setattr(devbox_mutagen.platform, "system", lambda: system)
+ monkeypatch.setattr(devbox_mutagen.platform, "machine", lambda: machine)
+ url = devbox_mutagen._mutagen_release_url()
+ assert url.endswith(expected_suffix)
+ assert url.startswith("https://github.com/mutagen-io/mutagen/releases/download/")
+
+ def test_unsupported_os_fails(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_mutagen.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(devbox_mutagen.platform, "machine", lambda: "amd64")
+ with pytest.raises(SystemExit):
+ devbox_mutagen._mutagen_release_url()
+
+ def test_unsupported_arch_fails(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_mutagen.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(devbox_mutagen.platform, "machine", lambda: "riscv64")
+ with pytest.raises(SystemExit):
+ devbox_mutagen._mutagen_release_url()
+
+
+class TestMutagenInstall:
+ """Test the install + version-pinning flow for the managed mutagen binary."""
+
+ def _pin_platform(self, monkeypatch: pytest.MonkeyPatch, payload: bytes) -> None:
+ """Force a supported platform and pin its checksum to ``payload``'s hash."""
+ monkeypatch.setattr(devbox_mutagen.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(devbox_mutagen.platform, "machine", lambda: "x86_64")
+ monkeypatch.setattr(
+ devbox_mutagen, "_MUTAGEN_SHA256", {("linux", "amd64"): hashlib.sha256(payload).hexdigest()}
+ )
+
+ def test_install_verifies_checksum_then_extracts(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ managed = tmp_path / "bin"
+ monkeypatch.setattr(devbox_mutagen, "_MANAGED_MUTAGEN_DIR", managed)
+ payload = b"fake-mutagen-tarball"
+ self._pin_platform(monkeypatch, payload)
+
+ calls: list[list[str]] = []
+
+ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
+ calls.append(args)
+ if args[0] == "curl":
+ out = Path(args[args.index("-o") + 1])
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_bytes(payload)
+ elif args[0] == "tar":
+ (managed / "mutagen").touch()
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ monkeypatch.setattr(devbox_mutagen.subprocess, "run", fake_run)
+
+ devbox_mutagen._install_mutagen()
+
+ # curl downloads first, tar extracts only after the checksum passes.
+ assert [c[0] for c in calls] == ["curl", "tar"]
+ assert "mutagen" in calls[1] and "mutagen-agents.tar.gz" in calls[1]
+ assert (managed / "mutagen").is_file()
+ # the downloaded tarball is cleaned up after extraction.
+ assert not list(managed.glob("*.tar.gz"))
+
+ def test_install_aborts_on_checksum_mismatch(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ managed = tmp_path / "bin"
+ monkeypatch.setattr(devbox_mutagen, "_MANAGED_MUTAGEN_DIR", managed)
+ self._pin_platform(monkeypatch, b"expected")
+
+ calls: list[list[str]] = []
+
+ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
+ calls.append(args)
+ if args[0] == "curl":
+ out = Path(args[args.index("-o") + 1])
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_bytes(b"tampered")
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ monkeypatch.setattr(devbox_mutagen.subprocess, "run", fake_run)
+
+ with pytest.raises(SystemExit):
+ devbox_mutagen._install_mutagen()
+
+ # tar must never run on an unverified tarball, and nothing is left on disk.
+ assert [c[0] for c in calls] == ["curl"]
+ assert not (managed / "mutagen").exists()
+ assert not list(managed.glob("*.tar.gz"))
+
+ def test_install_fails_when_no_pinned_checksum(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(devbox_mutagen, "_MANAGED_MUTAGEN_DIR", tmp_path / "bin")
+ monkeypatch.setattr(devbox_mutagen.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(devbox_mutagen.platform, "machine", lambda: "x86_64")
+ monkeypatch.setattr(devbox_mutagen, "_MUTAGEN_SHA256", {})
+
+ ran: list[list[str]] = []
+ monkeypatch.setattr(
+ devbox_mutagen.subprocess,
+ "run",
+ lambda args, **kw: ran.append(args) or subprocess.CompletedProcess(args, 0, "", ""),
+ )
+
+ with pytest.raises(SystemExit):
+ devbox_mutagen._install_mutagen()
+ assert ran == [] # bail before any download
+
+ def test_install_fails_when_binary_missing_after_install(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ managed = tmp_path / "bin"
+ monkeypatch.setattr(devbox_mutagen, "_MANAGED_MUTAGEN_DIR", managed)
+ payload = b"valid-tarball"
+ self._pin_platform(monkeypatch, payload)
+
+ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
+ if args[0] == "curl":
+ out = Path(args[args.index("-o") + 1])
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_bytes(payload)
+ # tar reports success but extracts nothing.
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ monkeypatch.setattr(devbox_mutagen.subprocess, "run", fake_run)
+
+ with pytest.raises(SystemExit):
+ devbox_mutagen._install_mutagen()
+
+ def test_ensure_skips_install_when_version_matches(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_mutagen, "mutagen_installed", lambda: True)
+ monkeypatch.setattr(devbox_mutagen, "get_installed_mutagen_version", lambda: devbox_mutagen._MUTAGEN_VERSION)
+ installed: list[bool] = []
+ monkeypatch.setattr(devbox_mutagen, "_install_mutagen", lambda **kw: installed.append(True))
+
+ devbox_mutagen.ensure_mutagen_installed()
+ assert installed == []
+
+ def test_ensure_reinstalls_on_version_mismatch(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_mutagen, "mutagen_installed", lambda: True)
+ monkeypatch.setattr(devbox_mutagen, "get_installed_mutagen_version", lambda: "0.17.0")
+ installed: list[bool] = []
+ monkeypatch.setattr(devbox_mutagen, "_install_mutagen", lambda **kw: installed.append(True))
+
+ devbox_mutagen.ensure_mutagen_installed()
+ assert installed == [True]
+
+ def test_ensure_reinstalls_when_version_unreadable(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Binary present but `mutagen version` fails (corrupt download) -> reinstall.
+ monkeypatch.setattr(devbox_mutagen, "mutagen_installed", lambda: True)
+ monkeypatch.setattr(devbox_mutagen, "get_installed_mutagen_version", lambda: None)
+ installed: list[bool] = []
+ monkeypatch.setattr(devbox_mutagen, "_install_mutagen", lambda **kw: installed.append(True))
+
+ devbox_mutagen.ensure_mutagen_installed()
+ assert installed == [True]
+
+
+class TestMutagenSyncWrappers:
+ """Test the thin subprocess wrappers around `mutagen sync ...`."""
+
+ def test_sync_create_builds_one_way_safe_argv(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ captured: list[list[str]] = []
+
+ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
+ captured.append(args)
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ monkeypatch.setattr(devbox_mutagen, "_run", fake_run)
+
+ config_path = tmp_path / "mutagen.yml"
+ config_path.write_text("sync:\n")
+ devbox_mutagen.sync_create(
+ name="ph-devbox-test-user",
+ src="/local",
+ dst="coder.devbox-test-user:/home/coder/posthog",
+ config_path=config_path,
+ labels={"hogli-workspace": "devbox-test-user"},
+ )
+
+ assert len(captured) == 1
+ args = captured[0]
+ # Design invariant: never run in two-way modes. Local is source of truth.
+ assert "--mode" in args and args[args.index("--mode") + 1] == "one-way-safe"
+ assert "--ignore-vcs" in args
+ assert "--name" in args and args[args.index("--name") + 1] == "ph-devbox-test-user"
+ assert "--label" in args and args[args.index("--label") + 1] == "hogli-workspace=devbox-test-user"
+ assert args[-2:] == ["/local", "coder.devbox-test-user:/home/coder/posthog"]
+
+ def test_sync_list_returns_empty_when_mutagen_missing(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_mutagen, "mutagen_installed", lambda: False)
+ assert devbox_mutagen.sync_list(label_selector="hogli-workspace=devbox-test-user") == []
+
+ def test_sync_list_parses_json_template_output(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_mutagen, "mutagen_installed", lambda: True)
+ sessions = [{"name": "ph-devbox-test-user", "paused": False, "status": "watching"}]
+ monkeypatch.setattr(
+ devbox_mutagen,
+ "_run",
+ lambda args, **kw: subprocess.CompletedProcess(args, 0, json.dumps(sessions), ""),
+ )
+ assert devbox_mutagen.sync_list(label_selector="hogli-workspace=devbox-test-user") == sessions
+
+ def test_sync_list_returns_empty_on_failure(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_mutagen, "mutagen_installed", lambda: True)
+ monkeypatch.setattr(
+ devbox_mutagen,
+ "_run",
+ lambda args, **kw: subprocess.CompletedProcess(args, 1, "", "no sessions"),
+ )
+ assert devbox_mutagen.sync_list(label_selector="missing") == []
+
+ def test_lifecycle_uses_label_selector(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ captured: list[list[str]] = []
+ # _label_op short-circuits when no session matches, so present one.
+ monkeypatch.setattr(devbox_mutagen, "sync_list", lambda **kw: [{"name": "ph-x"}])
+ monkeypatch.setattr(
+ devbox_mutagen,
+ "_run",
+ lambda args, **kw: captured.append(args) or subprocess.CompletedProcess(args, 0, "", ""),
+ )
+ devbox_mutagen.sync_terminate("hogli-workspace=devbox-test-user")
+ devbox_mutagen.sync_pause("hogli-workspace=devbox-test-user")
+ devbox_mutagen.sync_resume("hogli-workspace=devbox-test-user")
+ devbox_mutagen.sync_flush("hogli-workspace=devbox-test-user")
+ verbs = [args[2] for args in captured]
+ assert verbs == ["terminate", "pause", "resume", "flush"]
+ for args in captured:
+ assert "--label-selector" in args
+ assert args[args.index("--label-selector") + 1] == "hogli-workspace=devbox-test-user"
+
+ def test_terminate_swallows_no_sessions(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # A session matches the precheck but vanishes before the op runs (race):
+ # mutagen exits 1 with a "no sessions" message, which must be swallowed.
+ monkeypatch.setattr(devbox_mutagen, "sync_list", lambda **kw: [{"name": "ph-x"}])
+ monkeypatch.setattr(
+ devbox_mutagen,
+ "_run",
+ lambda args, **kw: subprocess.CompletedProcess(args, 1, "", "No sessions found"),
+ )
+ # Should not raise -- "no sessions" matching the selector is the expected
+ # state when destroying a workspace without an active sync.
+ devbox_mutagen.sync_terminate("hogli-workspace=missing")
+
+ def test_label_op_noops_when_mutagen_missing(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Lifecycle flags skip the install step, so a machine that never synced
+ # must no-op rather than crash with FileNotFoundError from subprocess.
+ monkeypatch.setattr(devbox_mutagen, "mutagen_installed", lambda: False)
+
+ def fail_run(*a: object, **kw: object) -> subprocess.CompletedProcess[str]:
+ raise AssertionError("_run must not be invoked when mutagen is absent")
+
+ monkeypatch.setattr(devbox_mutagen, "_run", fail_run)
+ # No exception, no subprocess.
+ devbox_mutagen.sync_terminate("hogli-workspace=devbox-test-user")
+ devbox_mutagen.sync_pause("hogli-workspace=devbox-test-user")
+
+
+class TestConflictCount:
+ """Test that conflict counts include mutagen's truncated remainder."""
+
+ @pytest.mark.parametrize(
+ "session, expected",
+ [
+ # mutagen caps the inline list at 10 and reports the rest separately.
+ ({"conflicts": [{}, {}], "excludedConflicts": 31}, 33),
+ ({"conflicts": [], "excludedConflicts": 0}, 0),
+ ({"conflicts": [{}]}, 1), # no excludedConflicts key at all
+ ({}, 0),
+ ({"conflicts": [{}, {}], "excludedConflicts": "garbage"}, 2), # falls back to shown
+ ],
+ )
+ def test_sums_shown_and_excluded(self, session: dict, expected: int) -> None:
+ assert devbox_mutagen.conflict_count(session) == expected
+
+
+class TestWorkspaceLabels:
+ """The create-side labels and the lookup-side selector must share one key."""
+
+ def test_labels_and_selector_agree(self) -> None:
+ labels = devbox_mutagen.workspace_labels("devbox-test-user")
+ selector = devbox_mutagen.workspace_label_selector("devbox-test-user")
+ assert labels == {"hogli-workspace": "devbox-test-user"}
+ # Selector is exactly `key=value` for the single create-side label.
+ ((key, value),) = labels.items()
+ assert selector == f"{key}={value}"
+
+
+class TestEnsureUserMutagenConfig:
+ """Test that the user-side mutagen.yml is seeded from the packaged defaults."""
+
+ def test_copies_defaults_when_absent(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ target = tmp_path / "mutagen.yml"
+ monkeypatch.setattr(devbox_mutagen, "_USER_CONFIG_PATH", target)
+
+ result = devbox_mutagen.ensure_user_mutagen_config()
+
+ assert result == target
+ assert target.is_file()
+ contents = target.read_text()
+ assert "one-way-safe" in contents
+ # Lockfiles must NOT be ignored -- they need to reach the devbox so the
+ # AMI's prewarmed deps can be reconciled on next start.
+ assert "pnpm-lock.yaml" not in contents
+ assert "uv.lock" not in contents
+ assert "Cargo.lock" not in contents
+ # The worktree `.git` *file* must be ignored (`vcs: true` only catches the
+ # `.git/` directory). The flox venv lives under `.flox/cache`, so only
+ # flox's machine-local subdirs are ignored -- NOT all of `.flox` (that
+ # would drop the tracked `.flox/env` definition) and NOT the
+ # hand-maintained `common/hogql_parser` C++ sources.
+ assert "'.git'" in contents
+ assert "'.flox/cache'" in contents
+ assert "\n - '.flox'\n" not in contents
+ assert "'common/hogql_parser'" not in contents
+
+ def test_preserves_existing_config(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ target = tmp_path / "mutagen.yml"
+ target.write_text("custom: contents\n")
+ monkeypatch.setattr(devbox_mutagen, "_USER_CONFIG_PATH", target)
+
+ devbox_mutagen.ensure_user_mutagen_config()
+
+ assert target.read_text() == "custom: contents\n"
+
+ def test_refreshes_unmodified_copy_when_defaults_change(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ target = tmp_path / "mutagen.yml"
+ monkeypatch.setattr(devbox_mutagen, "_USER_CONFIG_PATH", target)
+ devbox_mutagen.ensure_user_mutagen_config()
+ original = target.read_text()
+
+ # Simulate a shipped bump to the packaged defaults.
+ new_defaults = tmp_path / "new_defaults.yml"
+ new_defaults.write_text(original + "\n# new ignore added upstream\n")
+ monkeypatch.setattr(devbox_mutagen, "_PACKAGED_DEFAULTS", new_defaults)
+
+ devbox_mutagen.ensure_user_mutagen_config()
+ # An untouched copy is refreshed in place rather than left stale.
+ assert target.read_text() == original + "\n# new ignore added upstream\n"
+
+ def test_does_not_clobber_user_edits_on_defaults_change(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ target = tmp_path / "mutagen.yml"
+ monkeypatch.setattr(devbox_mutagen, "_USER_CONFIG_PATH", target)
+ devbox_mutagen.ensure_user_mutagen_config()
+
+ target.write_text("# my hand-tuned ignores\n") # user edits their copy
+ new_defaults = tmp_path / "new_defaults.yml"
+ new_defaults.write_text("sync: {}\n# new ignore added upstream\n")
+ monkeypatch.setattr(devbox_mutagen, "_PACKAGED_DEFAULTS", new_defaults)
+
+ devbox_mutagen.ensure_user_mutagen_config()
+ assert target.read_text() == "# my hand-tuned ignores\n" # preserved
+
+
+class TestDevboxSyncCommand:
+ """Test the devbox:sync orchestrator."""
+
+ def test_status_prints_sessions(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_sync, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(
+ devbox_sync.mutagen,
+ "sync_list",
+ lambda label_selector=None: [{"name": "ph-devbox-test-user", "status": "watching"}],
+ )
+ result = runner.invoke(cli, ["devbox:sync", "--status"])
+ assert result.exit_code == 0, result.output
+ assert "ph-devbox-test-user" in result.output
+
+ def test_json_emits_summary_with_true_conflict_total(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_sync, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(
+ devbox_sync.mutagen,
+ "sync_list",
+ lambda label_selector=None: [
+ {
+ "name": "ph-devbox-test-user",
+ "status": "watching",
+ "paused": False,
+ "conflicts": [{"root": "a.py"}, {"root": "b.py"}],
+ "excludedConflicts": 31,
+ "alpha": {"path": "/local"},
+ "beta": {"path": "coder.devbox-test-user:/home/coder/posthog"},
+ }
+ ],
+ )
+ result = runner.invoke(cli, ["devbox:sync", "--json"])
+ assert result.exit_code == 0, result.output
+ payload = json.loads(result.output)
+ assert len(payload) == 1
+ session = payload[0]
+ # The whole point of the fix: 2 shown + 31 excluded, not a capped 2.
+ assert session["conflicts"] == 33
+ assert session["conflictPaths"] == ["a.py", "b.py"]
+ assert session["state"] == "watching"
+ assert session["beta"] == "coder.devbox-test-user:/home/coder/posthog"
+
+ def test_json_rejects_lifecycle_combo(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_sync, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ result = runner.invoke(cli, ["devbox:sync", "--json", "--terminate"])
+ assert result.exit_code != 0
+ assert "json" in result.output.lower()
+
+ def test_rejects_shared_at_user_target(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Syncing onto someone else's box would push your checkout over theirs;
+ # the guard must fire before any resolution/create work.
+ def boom(*a: object, **kw: object) -> tuple[str, None]:
+ raise AssertionError("resolve_workspace_name must not run for @user targets")
+
+ monkeypatch.setattr(devbox_sync, "resolve_workspace_name", boom)
+ result = runner.invoke(cli, ["devbox:sync", "@alice/api"])
+ assert result.exit_code != 0
+ assert "@user" in result.output or "own devboxes" in result.output
+
+ def test_terminate_invokes_label_scoped_terminate(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_sync, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ captured: list[str] = []
+ monkeypatch.setattr(devbox_sync.mutagen, "sync_terminate", lambda sel: captured.append(sel))
+
+ result = runner.invoke(cli, ["devbox:sync", "--terminate"])
+
+ assert result.exit_code == 0, result.output
+ assert captured == ["hogli-workspace=devbox-test-user"]
+
+ def test_default_run_is_idempotent_when_session_already_exists(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_sync, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ # The "inspect" hint calls _workspace_arg_suffix -> extract_workspace_label,
+ # which shells out to `coder whoami`; stub it so the test is hermetic.
+ monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
+ monkeypatch.setattr(devbox_sync, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_sync.mutagen, "ensure_mutagen_installed", lambda **kw: None)
+ monkeypatch.setattr(devbox_sync.mutagen, "register_daemon", lambda: None)
+ monkeypatch.setattr(devbox_sync, "_ensure_ssh_config_for_workspace", lambda ws: None)
+ monkeypatch.setattr(devbox_sync.mutagen, "ensure_user_mutagen_config", lambda: Path("/tmp/mutagen.yml"))
+ monkeypatch.setattr(
+ devbox_sync.mutagen,
+ "sync_list",
+ lambda label_selector=None: [{"name": "ph-devbox-test-user"}],
+ )
+
+ created: list[str] = []
+ monkeypatch.setattr(devbox_sync.mutagen, "sync_create", lambda **kw: created.append(kw["name"]))
+
+ result = runner.invoke(cli, ["devbox:sync"])
+
+ assert result.exit_code == 0, result.output
+ # Idempotent: don't recreate an existing session.
+ assert created == []
+ assert "Sync already running" in result.output
+
+ def test_default_run_creates_one_way_sync(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(devbox_sync, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ # The "inspect" hint calls _workspace_arg_suffix -> extract_workspace_label,
+ # which shells out to `coder whoami`; stub it so the test is hermetic.
+ monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
+ monkeypatch.setattr(devbox_sync, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_sync.mutagen, "ensure_mutagen_installed", lambda **kw: None)
+ monkeypatch.setattr(devbox_sync.mutagen, "register_daemon", lambda: None)
+ monkeypatch.setattr(devbox_sync, "_ensure_ssh_config_for_workspace", lambda ws: None)
+ config_path = tmp_path / "mutagen.yml"
+ config_path.write_text("sync: {}\n")
+ monkeypatch.setattr(devbox_sync.mutagen, "ensure_user_mutagen_config", lambda: config_path)
+ monkeypatch.setattr(devbox_sync.mutagen, "sync_list", lambda label_selector=None: [])
+ checkout = tmp_path / "posthog"
+ checkout.mkdir()
+ monkeypatch.setattr(devbox_sync, "_detect_local_posthog_checkout", lambda: checkout)
+
+ captured: dict[str, object] = {}
+ monkeypatch.setattr(
+ devbox_sync.mutagen,
+ "sync_create",
+ lambda **kw: captured.update(kw),
+ )
+
+ result = runner.invoke(cli, ["devbox:sync"])
+
+ assert result.exit_code == 0, result.output
+ assert captured["name"] == "ph-devbox-test-user"
+ assert captured["src"] == str(checkout)
+ assert captured["dst"] == "coder.devbox-test-user:/home/coder/posthog"
+ assert captured["labels"] == {"hogli-workspace": "devbox-test-user"}
+
+ def test_default_run_fails_when_workspace_stopped(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # A stopped box passes the SSH-config check but mutagen can't dial it;
+ # surface a clear error before creating the session.
+ monkeypatch.setattr(
+ devbox_sync,
+ "resolve_workspace_name",
+ lambda ws: ("devbox-test-user", [{"name": "devbox-test-user"}]),
+ )
+ monkeypatch.setattr(devbox_sync.mutagen, "ensure_mutagen_installed", lambda **kw: None)
+ monkeypatch.setattr(devbox_sync.mutagen, "register_daemon", lambda: None)
+ monkeypatch.setattr(devbox_sync.mutagen, "sync_list", lambda label_selector=None: [])
+ monkeypatch.setattr(devbox_sync, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_sync, "get_workspace", lambda name, workspaces: {"name": name})
+ monkeypatch.setattr(devbox_sync, "get_workspace_status", lambda ws: "stopped")
+ created: list[str] = []
+ monkeypatch.setattr(devbox_sync.mutagen, "sync_create", lambda **kw: created.append(kw["name"]))
+
+ result = runner.invoke(cli, ["devbox:sync"])
+
+ assert result.exit_code != 0
+ assert "not running" in result.output
+ assert created == []
+
+ def test_status_surfaces_conflicts_and_error(self) -> None:
+ rendered = devbox_sync._format_session_status(
+ {"name": "ph-x", "status": "watching", "conflicts": [{}, {}], "lastError": "boom"}
+ )
+ assert "conflicts: 2" in rendered
+ assert "boom" in rendered
+
+ def test_detect_local_checkout_walks_up_from_cwd(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ checkout = tmp_path / "ph"
+ (checkout / "subdir").mkdir(parents=True)
+ (checkout / "hogli.yaml").write_text("")
+ (checkout / ".git").mkdir()
+ monkeypatch.chdir(checkout / "subdir")
+ assert devbox_sync._detect_local_posthog_checkout() == checkout.resolve()
+
+ def test_detect_local_checkout_fails_outside_repo(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.chdir(tmp_path)
+ with pytest.raises(SystemExit):
+ devbox_sync._detect_local_posthog_checkout()
+
+ def test_mutually_exclusive_lifecycle_flags(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ result = runner.invoke(cli, ["devbox:sync", "--pause", "--resume"])
+ assert result.exit_code != 0
+ assert "at most one" in result.output
+
+
+class TestDevboxLifecycleSyncIntegration:
+ """Verify cli.py commands wire into mutagen sync at the right moments."""
+
+ def test_destroy_terminates_sync_before_deleting(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[str] = []
+
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
+ monkeypatch.setattr(
+ devbox_cli,
+ "get_workspace",
+ lambda name, workspaces=None: {"name": name, "latest_build": {"status": "running"}},
+ )
+ monkeypatch.setattr(devbox_cli.click, "confirm", lambda *a, **kw: True)
+ monkeypatch.setattr(devbox_cli.mutagen, "sync_list", lambda label_selector=None: [{"name": "ph-x"}])
+ monkeypatch.setattr(devbox_cli.mutagen, "sync_terminate", lambda sel: calls.append("terminate"))
+ monkeypatch.setattr(devbox_cli, "delete_workspace", lambda name, verbose=False: calls.append("delete"))
+
+ result = runner.invoke(cli, ["devbox:destroy"])
+
+ assert result.exit_code == 0, result.output
+ # terminate MUST run before delete: the remote endpoint disappearing
+ # mid-sync produces noisy daemon errors otherwise.
+ assert calls == ["terminate", "delete"]
+
+ def test_destroy_proceeds_when_no_sync_session(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[str] = []
+
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
+ monkeypatch.setattr(
+ devbox_cli,
+ "get_workspace",
+ lambda name, workspaces=None: {"name": name, "latest_build": {"status": "running"}},
+ )
+ monkeypatch.setattr(devbox_cli.click, "confirm", lambda *a, **kw: True)
+ monkeypatch.setattr(devbox_cli.mutagen, "sync_list", lambda label_selector=None: [])
+ monkeypatch.setattr(
+ devbox_cli.mutagen,
+ "sync_terminate",
+ lambda sel: calls.append("terminate"),
+ )
+ monkeypatch.setattr(devbox_cli, "delete_workspace", lambda name, verbose=False: calls.append("delete"))
+
+ result = runner.invoke(cli, ["devbox:destroy"])
+
+ assert result.exit_code == 0, result.output
+ assert calls == ["delete"]
+
+ def test_start_prints_sync_tip_when_no_session(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "get_workspace", lambda name, workspaces=None: None)
+ monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
+ monkeypatch.setattr(devbox_cli, "load_config", lambda: {})
+ monkeypatch.setattr(devbox_cli, "create_workspace", lambda *a, **kw: None)
+ monkeypatch.setattr(devbox_cli.mutagen, "sync_list", lambda label_selector=None: [])
+
+ result = runner.invoke(cli, ["devbox:start"])
+
+ assert result.exit_code == 0, result.output
+ assert "hogli devbox:sync" in result.output
+
+ def test_start_omits_sync_tip_when_session_exists(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "get_workspace", lambda name, workspaces=None: None)
+ monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
+ monkeypatch.setattr(devbox_cli, "load_config", lambda: {})
+ monkeypatch.setattr(devbox_cli, "create_workspace", lambda *a, **kw: None)
+ monkeypatch.setattr(devbox_cli.mutagen, "sync_list", lambda label_selector=None: [{"name": "ph-x"}])
+
+ result = runner.invoke(cli, ["devbox:start"])
+
+ assert result.exit_code == 0, result.output
+ assert "Tip: run `hogli devbox:sync" not in result.output
+
+
+class TestRenderSyncStatus:
+ """Test the one-line sync-state summary shown in devbox:list / devbox:status."""
+
+ def test_not_configured_when_no_session(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli.mutagen, "sync_list", lambda label_selector=None: [])
+ assert "not configured" in devbox_cli._render_sync_status("devbox-test-user")
+
+ def test_conflicts_render_as_warning(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ devbox_cli.mutagen,
+ "sync_list",
+ lambda label_selector=None: [{"status": "watching", "conflicts": [{}, {}]}],
+ )
+ assert "2 conflicts" in devbox_cli._render_sync_status("devbox-test-user")
+
+ def test_halted_status_is_not_green_healthy(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ devbox_cli.mutagen,
+ "sync_list",
+ lambda label_selector=None: [{"status": "halted-on-root-deletion"}],
+ )
+ rendered = devbox_cli._render_sync_status("devbox-test-user")
+ assert "halted-on-root-deletion" in rendered
+ assert "✗" in rendered
+
+ def test_watching_status_is_healthy(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ devbox_cli.mutagen,
+ "sync_list",
+ lambda label_selector=None: [{"status": "watching"}],
+ )
+ rendered = devbox_cli._render_sync_status("devbox-test-user")
+ assert "watching" in rendered
+ assert "●" in rendered