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): run worktree boxes on hogland (#126383)

Georges-Antoine Assiae036a07941c
diff --git a/.agents/skills/setting-up-devbox/SKILL.md b/.agents/skills/setting-up-devbox/SKILL.md
index 63fadd3cb439..abfb2cd469f3 100644
--- a/.agents/skills/setting-up-devbox/SKILL.md
+++ b/.agents/skills/setting-up-devbox/SKILL.md
@@ -184,6 +184,18 @@ hogli devbox:worktree --on-clean stop # save what worktrees:clean does
- A box whose worktree was already removed gets the same action on the next `worktrees:clean` run, within that run's `--repo` and `--source` selection. A moved or unmounted worktree does not count as removed.
- Clear the saved action with `hogli devbox:config:rm worktree-boxes`.
+### Run worktree boxes on Hogland
+
+`hogli devbox:worktree --provider hogland` gives the worktree a Hogland devbox, restored from the `devbox-golden` snapshot, instead of a Coder workspace.
+
+- It needs the `hogland` CLI, installed and signed in. A missing CLI fails with the install command.
+- The box is named `wt-<label>`, and Hogland caps the name at 32 characters.
+- hogli writes an SSH entry for `hogland.wt-<label>` under `~/.hogli/hogland-ssh/`, and the mirror goes to `/home/hog/posthog`. Open a shell with `hogland devbox ssh wt-<label>`, and start the stack there with `hogli start -d`.
+- Pass `--provider hogland` with `--auto` to save Hogland as the default, which automatic boxes then use. `hogli devbox:config:rm worktree-provider` goes back to Coder.
+- `worktrees:clean --stop-boxes` hibernates the box, and `--delete-boxes` deletes it.
+- A worktree that still has a box on the other provider is refused until that box is removed.
+- `--clone-from` and `--start-app` are Coder-only.
+
### Provision a box for every new worktree
`hogli devbox:worktree --auto claude,phw` saves the worktree sources that get a box automatically.
diff --git a/docs/internal/coder-workspaces.md b/docs/internal/coder-workspaces.md
index 22ae7f878203..16eb2bc1ad5c 100644
--- a/docs/internal/coder-workspaces.md
+++ b/docs/internal/coder-workspaces.md
@@ -71,6 +71,15 @@ It also handles boxes whose worktree was already removed some other way, but onl
To give every new worktree a box, run `hogli devbox:worktree --auto claude,phw` once with the worktree sources you want (`claude`, `codex`, `posthog-code`, `phw`, `other`). The husky `post-checkout` hook then runs `devbox:worktree` in the background after `git worktree add`, including for `claude -w`. Claude subagent worktrees are skipped. Turn it off with `--auto off`.
+**Worktree boxes on Hogland** —
+`hogli devbox:worktree --provider hogland` gives the worktree a Hogland devbox instead of a Coder workspace.
+It restores the box from the `devbox-golden` snapshot with `hogland devbox up`, so the `hogland` CLI must be installed and signed in.
+The box is named `wt-<label>` and the mirror goes to `/home/hog/posthog` over SSH.
+To make Hogland the default, including for automatic boxes, pass `--provider hogland` together with `--auto`.
+`hogli devbox:config:rm worktree-provider` goes back to Coder.
+`worktrees:clean --stop-boxes` hibernates a Hogland box, and `--delete-boxes` deletes it.
+`--clone-from` and `--start-app` work only with Coder.
+
## Prerequisites
- Access to the PostHog Tailscale tailnet (on macOS, the Tailscale app bundle CLI is detected automatically if `tailscale` isn't on PATH)
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.py
index 46932613045e..ee70ea365b07 100644
--- a/tools/hogli-commands/hogli_commands/devbox/cli.py
+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py
@@ -99,6 +99,7 @@ from .config import (
clear_region,
clear_worktree_auto_sources,
clear_worktree_box_cleanup,
+ clear_worktree_provider,
load_config,
save_dotfiles_uri,
save_git_identity,
@@ -1097,6 +1098,16 @@ def _reset_worktree_auto_sources() -> bool:
return True
+def _reset_worktree_provider() -> bool:
+ config = load_config()
+ if not config.get("worktree_provider"):
+ click.echo("Nothing to clear: worktree boxes already run on coder.")
+ return False
+ clear_worktree_provider(config)
+ click.echo("Worktree boxes run on coder again.")
+ return True
+
+
def _git_identity_status(config: DevboxConfig, _: set[str]) -> str | None:
name = config.get("git_name")
email = config.get("git_email")
@@ -1182,6 +1193,13 @@ _CONFIG_ITEMS: tuple[_ConfigItem, ...] = (
status=_field_status("worktree_auto_box"),
reset=_reset_worktree_auto_sources,
),
+ _ConfigItem(
+ cli_key="worktree-provider",
+ label="Worktree box provider",
+ needs_secrets=False,
+ status=_field_status("worktree_provider"),
+ reset=_reset_worktree_provider,
+ ),
)
@@ -1925,7 +1943,7 @@ def devbox_config_rm(keys: tuple[str, ...], reset_all: bool) -> None:
Valid keys mirror the matching ``--configure-*`` flags on ``devbox:setup``:
``git-identity``, ``git-signing``, ``region``, ``dotfiles``, ``claude``, ``worktree-boxes``,
- ``worktree-auto``.
+ ``worktree-auto``, ``worktree-provider``.
"""
by_key = _config_items_by_key()
valid_keys = tuple(by_key)
diff --git a/tools/hogli-commands/hogli_commands/devbox/config.py b/tools/hogli-commands/hogli_commands/devbox/config.py
index 5c36c58b5140..9debc6a1cd61 100644
--- a/tools/hogli-commands/hogli_commands/devbox/config.py
+++ b/tools/hogli-commands/hogli_commands/devbox/config.py
@@ -20,12 +20,23 @@ class DevboxConfig(TypedDict, total=False):
region: str
worktree_box_cleanup: str
worktree_auto_box: str
+ worktree_provider: str
-_PERSISTED_FIELDS = ("git_name", "git_email", "dotfiles_uri", "region", "worktree_box_cleanup", "worktree_auto_box")
+_PERSISTED_FIELDS = (
+ "git_name",
+ "git_email",
+ "dotfiles_uri",
+ "region",
+ "worktree_box_cleanup",
+ "worktree_auto_box",
+ "worktree_provider",
+)
WORKTREE_BOX_CLEANUP_ACTIONS = ("stop", "delete")
WORKTREE_AUTO_SOURCES = ("claude", "codex", "posthog-code", "phw", "other")
+WORKTREE_PROVIDERS = ("coder", "hogland")
+DEFAULT_WORKTREE_PROVIDER = "coder"
_WORKTREE_ID_FILE = "hogli-devbox-worktree-id"
@@ -175,6 +186,26 @@ def saved_worktree_auto_sources() -> frozenset[str]:
return frozenset(source.strip() for source in saved.split(",")) & frozenset(WORKTREE_AUTO_SOURCES)
+def save_worktree_provider(provider: str) -> DevboxConfig:
+ config = load_config()
+ config["worktree_provider"] = provider
+ save_config(config)
+ return config
+
+
+def clear_worktree_provider(config: DevboxConfig | None = None) -> DevboxConfig:
+ if config is None:
+ config = load_config()
+ config.pop("worktree_provider", None)
+ save_config(config)
+ return config
+
+
+def saved_worktree_provider() -> str:
+ provider = load_config().get("worktree_provider")
+ return provider if provider in WORKTREE_PROVIDERS else DEFAULT_WORKTREE_PROVIDER
+
+
def read_worktree_id(git_dir: Path) -> str | None:
try:
return (git_dir / _WORKTREE_ID_FILE).read_text().strip() or None
@@ -211,6 +242,7 @@ class WorktreeBoxRecord:
git_dir: str
workspace_id: str | None = None
worktree_id: str | None = None
+ provider: str = DEFAULT_WORKTREE_PROVIDER
def tracks_worktree(self, git_dir: Path) -> bool:
"""Whether the worktree with admin directory *git_dir* is the one this record was saved for.
@@ -257,12 +289,14 @@ def load_worktree_boxes() -> dict[str, WorktreeBoxRecord]:
continue
workspace, git_dir = entry.get("workspace"), entry.get("git_dir")
workspace_id, worktree_id = entry.get("workspace_id"), entry.get("worktree_id")
+ provider = entry.get("provider")
if isinstance(workspace, str) and workspace and isinstance(git_dir, str) and git_dir:
boxes[path] = WorktreeBoxRecord(
workspace=workspace,
git_dir=git_dir,
workspace_id=workspace_id if isinstance(workspace_id, str) and workspace_id else None,
worktree_id=worktree_id if isinstance(worktree_id, str) and worktree_id else None,
+ provider=provider if provider in WORKTREE_PROVIDERS else DEFAULT_WORKTREE_PROVIDER,
)
return boxes
diff --git a/tools/hogli-commands/hogli_commands/devbox/hogland.py b/tools/hogli-commands/hogli_commands/devbox/hogland.py
new file mode 100644
index 000000000000..801e0535f80a
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/devbox/hogland.py
@@ -0,0 +1,175 @@
+"""Hogland devboxes for `hogli devbox:worktree`, driven through the `hogland` CLI."""
+
+from __future__ import annotations
+
+import json
+import shlex
+import shutil
+import subprocess
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from .coder import _LABEL_RE, _fail
+
+REMOTE_REPO_PATH = "/home/hog/posthog"
+NAME_PREFIX = "wt-"
+NAME_MAX_LENGTH = 32
+_UP_TIMEOUT_SECONDS = 900
+_CALL_TIMEOUT_SECONDS = 120
+_SSH_DIR = Path.home() / ".hogli" / "hogland-ssh"
+
+
+@dataclass(frozen=True)
+class HoglandEndpoint:
+ box_id: str
+ host: str
+ port: int
+
+
+def ssh_config_path() -> Path:
+ return _SSH_DIR / "config"
+
+
+def ssh_alias(name: str) -> str:
+ return f"hogland.{name}"
+
+
+def name_for_label(label: str) -> str:
+ if not _LABEL_RE.match(label):
+ _fail(f"Invalid devbox label '{label}'. Use lowercase letters, digits and hyphens.")
+ return f"{NAME_PREFIX}{label}"
+
+
+def label_of(name: str) -> str | None:
+ if not name.startswith(NAME_PREFIX):
+ return None
+ return name[len(NAME_PREFIX) :] or None
+
+
+def ensure_cli() -> None:
+ if shutil.which("hogland") is None:
+ _fail(
+ "The `hogland` CLI is not installed. Install it with `brew install posthog/tap/hogland`, "
+ "then sign in with `hogland auth login`.",
+ cause="hogland_cli_missing",
+ )
+
+
+def _run_json(args: list[str], *, timeout: float) -> Any:
+ try:
+ result = subprocess.run(["hogland", *args], capture_output=True, text=True, timeout=timeout)
+ except subprocess.TimeoutExpired:
+ _fail(f"`hogland {shlex.join(args)}` did not finish within {int(timeout)}s.", cause="hogland_timeout")
+ if result.returncode != 0:
+ _fail(
+ f"`hogland {shlex.join(args)}` failed: {result.stderr.strip() or result.stdout.strip()}",
+ cause="hogland_command_failed",
+ )
+ try:
+ return json.loads(result.stdout)
+ except json.JSONDecodeError:
+ _fail(f"`hogland {shlex.join(args)}` did not print JSON.", cause="hogland_bad_output")
+
+
+def devbox_status(devbox: dict[str, Any]) -> str:
+ if devbox.get("current_box_id"):
+ return "running"
+ if devbox.get("latest_snapshot_id"):
+ return "hibernated"
+ return "stopped"
+
+
+def as_workspace(devbox: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "name": devbox.get("name"),
+ "id": devbox.get("created_at"),
+ "status": devbox_status(devbox),
+ "last_used_at": devbox.get("updated_at"),
+ }
+
+
+def fetch_devboxes() -> list[dict[str, Any]]:
+ devboxes = _run_json(["devbox", "list"], timeout=_CALL_TIMEOUT_SECONDS)
+ if not isinstance(devboxes, list):
+ _fail("`hogland devbox list` returned an unexpected shape.", cause="hogland_bad_output")
+ return [as_workspace(devbox) for devbox in devboxes if isinstance(devbox, dict)]
+
+
+def parse_endpoint(payload: Any) -> HoglandEndpoint:
+ box = payload.get("box") if isinstance(payload, dict) else None
+ if not isinstance(box, dict):
+ _fail("`hogland devbox up` returned no box.", cause="hogland_bad_output")
+ host, port, box_id = box.get("public_ip"), box.get("guest_ssh_port"), box.get("id")
+ if box.get("status") != "running" or not isinstance(host, str) or not isinstance(port, int):
+ _fail(
+ f"Hogland box {box_id} is {box.get('status')!r}, not running with SSH. "
+ f"{payload.get('warning', '')}".strip(),
+ cause="hogland_box_not_running",
+ )
+ return HoglandEndpoint(box_id=str(box_id), host=host, port=port)
+
+
+def up(name: str, branch: str | None) -> HoglandEndpoint:
+ args = ["devbox", "up", name, "--no-connect"]
+ if branch:
+ args += ["--branch", branch]
+ return parse_endpoint(_run_json(args, timeout=_UP_TIMEOUT_SECONDS))
+
+
+def hibernate(name: str) -> None:
+ _run_json(["devbox", "hibernate", name], timeout=_UP_TIMEOUT_SECONDS)
+
+
+def delete(name: str) -> None:
+ _run_json(["devbox", "delete", name], timeout=_CALL_TIMEOUT_SECONDS)
+
+
+def render_host_entry(name: str, endpoint: HoglandEndpoint, known_hosts: Path) -> str:
+ alias = ssh_alias(name)
+ return (
+ f"Host {alias}\n"
+ f" HostName {endpoint.host}\n"
+ f" Port {endpoint.port}\n"
+ " User hog\n"
+ f" HostKeyAlias {alias}\n"
+ " StrictHostKeyChecking accept-new\n"
+ f' UserKnownHostsFile "{known_hosts}"\n'
+ )
+
+
+def render_main_config(hosts_dir: Path) -> str:
+ return f'Include "{hosts_dir}/*.conf"\n\nMatch all\n Include ~/.ssh/config\n'
+
+
+def write_ssh_entry(name: str, endpoint: HoglandEndpoint) -> None:
+ hosts_dir = _SSH_DIR / "hosts"
+ known_hosts = _SSH_DIR / "known_hosts"
+ hosts_dir.mkdir(parents=True, exist_ok=True)
+ _SSH_DIR.chmod(0o700)
+ ssh_config_path().write_text(render_main_config(hosts_dir))
+ (hosts_dir / f"{name}.conf").write_text(render_host_entry(name, endpoint, known_hosts))
+ box_id_path = hosts_dir / f"{name}.box-id"
+ known_box_id = box_id_path.read_text().strip() if box_id_path.exists() else None
+ if known_box_id != endpoint.box_id and known_hosts.exists():
+ subprocess.run(
+ ["ssh-keygen", "-R", ssh_alias(name), "-f", str(known_hosts)],
+ capture_output=True,
+ check=False,
+ )
+ box_id_path.write_text(endpoint.box_id)
+
+
+def forget_ssh_entry(name: str) -> None:
+ hosts_dir = _SSH_DIR / "hosts"
+ (hosts_dir / f"{name}.conf").unlink(missing_ok=True)
+ (hosts_dir / f"{name}.box-id").unlink(missing_ok=True)
+
+
+def run_in_devbox(name: str, command: list[str], *, timeout: float) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ ["ssh", "-F", str(ssh_config_path()), ssh_alias(name), shlex.join(command)],
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ )
diff --git a/tools/hogli-commands/hogli_commands/devbox/mutagen.py b/tools/hogli-commands/hogli_commands/devbox/mutagen.py
index 05e7acf20e86..17a321433d80 100644
--- a/tools/hogli-commands/hogli_commands/devbox/mutagen.py
+++ b/tools/hogli-commands/hogli_commands/devbox/mutagen.py
@@ -20,6 +20,7 @@ from typing import Any
import click
from .coder import _fail
+from .hogland import ssh_config_path as hogland_ssh_config_path
_MANAGED_MUTAGEN_DIR = Path.home() / ".hogli" / "bin"
_MUTAGEN_VERSION = "0.18.1"
@@ -42,7 +43,7 @@ _KEEPALIVE_COUNT = 3
_CONNECT_TIMEOUT_SECONDS = 60
# Baked at generation time (see ensure_ssh_shim): only when the ssh/scp target is
-# a devbox (a `coder.*` host -- the sole thing hogli syncs to) do we bump
+# a devbox (a `coder.*` or `hogland.*` host -- the only things hogli syncs to) do we bump
# mutagen's count and turn off autostart; every other invocation passes through untouched, so a shared
# daemon's non-devbox syncs are unaffected. Execs the real ssh/scp by absolute
# path so a shim-dir entry on PATH can never make the shim re-invoke itself.
@@ -51,15 +52,21 @@ _SHIM_TEMPLATE = """#!/usr/bin/env bash
# Raises mutagen's intolerant `-oServerAliveCountMax=1` for devbox (coder.*)
# connections so the sync survives a Tailscale/DERP path reset instead of dying
# with a broken pipe, and stops those connections from starting a stopped box.
+# hogland.* hosts resolve through hogli's own ssh config, so they get -F.
# Any non-devbox ssh is passed through unchanged.
devbox=
+hogland=
for a in "$@"; do
- case "$a" in coder.*|*@coder.*) devbox=1 ;; esac
+ case "$a" in
+ coder.*|*@coder.*) devbox=1 ;;
+ hogland.*|*@hogland.*) devbox=1; hogland=1 ;;
+ esac
done
if [ -n "$devbox" ]; then
export CODER_SSH_DISABLE_AUTOSTART=true
fi
args=()
+[ -n "$hogland" ] && args+=(-F "{hogland_config}")
for a in "$@"; do
case "$a" in
-oConnectTimeout=*) [ -n "$devbox" ] && a="-oConnectTimeout={connect_timeout}" ;;
@@ -284,6 +291,7 @@ def ensure_ssh_shim() -> Path:
count=_KEEPALIVE_COUNT,
connect_timeout=_CONNECT_TIMEOUT_SECONDS,
real=_resolve_real_ssh(name),
+ hogland_config=hogland_ssh_config_path(),
)
if not target.exists() or target.read_text() != content:
_write_owner_only(target, content)
diff --git a/tools/hogli-commands/hogli_commands/devbox/sync.py b/tools/hogli-commands/hogli_commands/devbox/sync.py
index da207ea47ee9..1397da66cb39 100644
--- a/tools/hogli-commands/hogli_commands/devbox/sync.py
+++ b/tools/hogli-commands/hogli_commands/devbox/sync.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import json
import subprocess
+from collections.abc import Callable
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
@@ -17,7 +18,7 @@ from typing import Any
import click
-from . import mutagen
+from . import hogland, mutagen
from .cli import _workspace_arg_suffix, resolve_workspace_name, workspace_argument
from .coder import _fail, ensure_runtime_ready, get_workspace, get_workspace_status, run_in_workspace
@@ -84,6 +85,26 @@ class BoxGitState:
dirty: bool
+@dataclass(frozen=True)
+class BoxShell:
+ repo_path: str
+ run: Callable[[list[str], float], subprocess.CompletedProcess[str]]
+
+
+def _coder_shell(workspace: str) -> BoxShell:
+ return BoxShell(
+ repo_path=_REMOTE_REPO_PATH,
+ run=lambda command, timeout: run_in_workspace(workspace, command, timeout=timeout),
+ )
+
+
+def _hogland_shell(name: str) -> BoxShell:
+ return BoxShell(
+ repo_path=hogland.REMOTE_REPO_PATH,
+ run=lambda command, timeout: hogland.run_in_devbox(name, command, timeout=timeout),
+ )
+
+
class BoxCheckoutAction(Enum):
SKIP = "skip"
MATCHES = "matches"
@@ -139,17 +160,16 @@ def _read_local_head(local_path: Path) -> GitHead | None:
return GitHead(branch=lines[1], sha=lines[0])
-def _run_box_script(workspace: str, script: str, *args: str) -> subprocess.CompletedProcess[str] | None:
+def _run_box_script(shell: BoxShell, script: str, *args: str) -> subprocess.CompletedProcess[str] | None:
+ script = script.replace(_REMOTE_REPO_PATH, shell.repo_path)
try:
- return run_in_workspace(
- workspace, ["bash", "-c", script, "hogli-sync", *args], timeout=_REMOTE_GIT_TIMEOUT_SECONDS
- )
+ return shell.run(["bash", "-c", script, "hogli-sync", *args], _REMOTE_GIT_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired:
return None
-def _probe_box_state(workspace: str) -> BoxGitState | None:
- result = _run_box_script(workspace, _PROBE_BOX_HEAD_SCRIPT)
+def _probe_box_state(shell: BoxShell) -> BoxGitState | None:
+ result = _run_box_script(shell, _PROBE_BOX_HEAD_SCRIPT)
if result is None or result.returncode != 0:
return None
lines = result.stdout.split()
@@ -158,7 +178,9 @@ def _probe_box_state(workspace: str) -> BoxGitState | None:
return BoxGitState(head=GitHead(branch=lines[0], sha=lines[1]), dirty=lines[2] != "0")
-def _align_box_checkout(workspace: str, local_path: Path, requested: bool | None) -> None:
+def _align_box_checkout(
+ workspace: str, local_path: Path, requested: bool | None, shell: BoxShell | None = None
+) -> None:
"""Put the box on the local branch and commit before the first mirror is created.
A one-way-safe mirror has no common ancestor on its first scan, so every
@@ -170,6 +192,7 @@ def _align_box_checkout(workspace: str, local_path: Path, requested: bool | None
"""
if requested is False:
return
+ shell = shell or _coder_shell(workspace)
def give_up(message: str) -> None:
if requested:
@@ -180,7 +203,7 @@ def _align_box_checkout(workspace: str, local_path: Path, requested: bool | None
if local is None:
give_up("Couldn't read the local branch, so the devbox checkout was left as is.")
return
- box = _probe_box_state(workspace)
+ box = _probe_box_state(shell)
if box is None:
give_up("Couldn't read the devbox's git state, so its checkout was left as is.")
return
@@ -196,7 +219,7 @@ def _align_box_checkout(workspace: str, local_path: Path, requested: bool | None
return
click.echo(f"Devbox is on {box.head.describe()}. Checking out {local.describe()} there first...")
- result = _run_box_script(workspace, _CHECKOUT_SCRIPT, local.branch, local.sha)
+ result = _run_box_script(shell, _CHECKOUT_SCRIPT, local.branch, local.sha)
returncode = None if result is None else result.returncode
if returncode == 0:
click.echo("Devbox checkout matches local.")
@@ -440,3 +463,27 @@ def _ensure_workspace_running(name: str, workspaces: list[dict[str, Any]] | None
status = get_workspace_status(workspace)
if status != "running":
_fail(f"Devbox '{name}' is {status}, not running. Run `hogli devbox:start` first.")
+
+
+def ensure_hogland_sync_session(
+ name: str, local_path: Path, *, checkout_branch: bool | None = None, verbose: bool = False
+) -> None:
+ if sync_session_exists(name, verbose=verbose):
+ click.echo(f"Sync already running for {name}.")
+ return
+ create_hogland_sync_session(name, local_path, checkout_branch)
+ click.echo("Sync created. Initial scan and copy may take a few minutes for large checkouts.")
+
+
+def create_hogland_sync_session(name: str, local_path: Path, checkout_branch: bool | None = None) -> None:
+ config_path = mutagen.ensure_user_mutagen_config()
+ _align_box_checkout(name, local_path, checkout_branch, shell=_hogland_shell(name))
+ destination = f"{hogland.ssh_alias(name)}:{hogland.REMOTE_REPO_PATH}"
+ click.echo(f"Creating sync: {local_path} -> {destination}")
+ mutagen.sync_create(
+ name=f"ph-{name}",
+ src=str(local_path),
+ dst=destination,
+ config_path=config_path,
+ labels=mutagen.workspace_labels(name),
+ )
diff --git a/tools/hogli-commands/hogli_commands/devbox/worktree.py b/tools/hogli-commands/hogli_commands/devbox/worktree.py
index 1d2e4fffe667..2486129f3f45 100644
--- a/tools/hogli-commands/hogli_commands/devbox/worktree.py
+++ b/tools/hogli-commands/hogli_commands/devbox/worktree.py
@@ -7,6 +7,7 @@ import sys
import hashlib
import subprocess
import urllib.parse
+from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -14,7 +15,7 @@ from typing import Any
import click
from ..worktrees import worktree_source
-from . import mutagen
+from . import hogland, mutagen
from .cli import _preferred_region, devbox_clone, devbox_start, resolve_workspace_name
from .coder import (
REGION_NAME_SUFFIXES,
@@ -32,6 +33,7 @@ from .coder import (
from .config import (
WORKTREE_AUTO_SOURCES,
WORKTREE_BOX_CLEANUP_ACTIONS,
+ WORKTREE_PROVIDERS,
WorktreeBoxRecord,
claim_worktree_box,
clear_worktree_auto_sources,
@@ -41,10 +43,12 @@ from .config import (
record_worktree_box,
save_worktree_auto_sources,
save_worktree_box_cleanup,
+ save_worktree_provider,
saved_worktree_auto_sources,
+ saved_worktree_provider,
worktree_box_claimant,
)
-from .sync import _REMOTE_REPO_PATH, _detect_local_posthog_checkout, ensure_sync_session
+from .sync import _REMOTE_REPO_PATH, _detect_local_posthog_checkout, ensure_hogland_sync_session, ensure_sync_session
CODER_NAME_MAX_LENGTH = 32
_HASH_LENGTH = 4
@@ -91,10 +95,13 @@ def _is_linked_worktree(root: Path) -> bool:
return (root / ".git").is_file()
-def _current_branch(root: Path) -> str:
+def _checked_out_branch(root: Path) -> str | None:
result = subprocess.run(["git", "symbolic-ref", "--short", "-q", "HEAD"], cwd=root, capture_output=True, text=True)
- branch = result.stdout.strip() if result.returncode == 0 else ""
- return branch or root.name
+ return (result.stdout.strip() if result.returncode == 0 else "") or None
+
+
+def _current_branch(root: Path) -> str:
+ return _checked_out_branch(root) or root.name
def parse_auto_sources(value: str) -> tuple[str, ...]:
@@ -146,14 +153,64 @@ def _app_url(workspace_name: str) -> str:
class _WorktreeTarget:
workspace_name: str
label: str
+ abandoned_mirror: str | None = None
+
+
+@dataclass(frozen=True)
+class _BoxNaming:
+ provider: str
+ label_budget: int
+ max_length: int
+ name_for: Callable[[str], str]
+ destroy_command: Callable[[str], str]
+
+
+def _coder_naming(cloning: bool, clone_source: str | None) -> _BoxNaming:
+ if cloning:
+ region = region_from_workspace_name(resolve_workspace_name(clone_source)[0])
+ else:
+ region = _preferred_region()
+ return _BoxNaming(
+ provider="Coder",
+ label_budget=label_budget(get_username(), region),
+ max_length=CODER_NAME_MAX_LENGTH,
+ name_for=lambda resolved_label: get_workspace_name(resolved_label, region=region),
+ destroy_command=lambda name: f"hogli devbox:destroy {extract_workspace_label(name) or ''}",
+ )
+
+
+def _hogland_naming() -> _BoxNaming:
+ return _BoxNaming(
+ provider="Hogland",
+ label_budget=hogland.NAME_MAX_LENGTH - len(hogland.NAME_PREFIX),
+ max_length=hogland.NAME_MAX_LENGTH,
+ name_for=hogland.name_for_label,
+ destroy_command=lambda name: f"hogland devbox delete {name}",
+ )
+
+
+def _fail_if_other_provider_box_exists(record: WorktreeBoxRecord) -> None:
+ if record.provider == "hogland":
+ hogland.ensure_cli()
+ live = get_workspace(record.workspace, hogland.fetch_devboxes())
+ command = f"hogland devbox delete {record.workspace}"
+ else:
+ live = get_workspace(record.workspace, _list_workspaces_or_fail())
+ command = f"hogli devbox:destroy {extract_workspace_label(record.workspace) or ''}"
+ if live is not None and record.may_adopt(live):
+ _fail(
+ f"This worktree already has the {record.provider} devbox '{record.workspace}'. "
+ f"Remove it with `{command}` before you switch providers."
+ )
def _resolve_target(
root: Path,
label: str | None,
- cloning: bool,
- clone_source: str | None,
workspaces: list[dict[str, Any]],
+ provider: str,
+ label_of: Callable[[str], str | None],
+ naming: Callable[[], _BoxNaming],
) -> _WorktreeTarget:
"""Return the devbox this worktree uses.
@@ -165,27 +222,31 @@ def _resolve_target(
registered = boxes.get(str(root))
if registered is not None and registered.worktree_id is not None and not registered.tracks_worktree(_git_dir(root)):
registered = None
+ abandoned_mirror = None
+ if registered is not None and registered.provider != provider:
+ _fail_if_other_provider_box_exists(registered)
+ abandoned_mirror = registered.workspace
+ registered = None
registered_box = get_workspace(registered.workspace, workspaces) if registered is not None else None
if registered is not None and registered_box is not None and not registered.may_adopt(registered_box):
registered = registered_box = None
- registered_label = extract_workspace_label(registered.workspace) if registered is not None else None
+ registered_label = label_of(registered.workspace) if registered is not None else None
if registered is not None and registered_label is not None and label in (None, registered_label):
return _WorktreeTarget(workspace_name=registered.workspace, label=registered_label)
- if cloning:
- region = region_from_workspace_name(resolve_workspace_name(clone_source)[0])
- else:
- region = _preferred_region()
-
- resolved_label = label or derive_label(_current_branch(root), label_budget(get_username(), region))
- name = get_workspace_name(resolved_label, region=region)
- if len(name) > CODER_NAME_MAX_LENGTH:
- _fail(f"'{name}' is longer than Coder's {CODER_NAME_MAX_LENGTH}-character limit. Pick a shorter `--label`.")
+ box_naming = naming()
+ resolved_label = label or derive_label(_current_branch(root), box_naming.label_budget)
+ name = box_naming.name_for(resolved_label)
+ if len(name) > box_naming.max_length:
+ _fail(
+ f"'{name}' is longer than {box_naming.provider}'s {box_naming.max_length}-character limit. "
+ "Pick a shorter `--label`."
+ )
if registered is not None and registered.workspace != name and registered_box is not None:
_fail(
f"This worktree already has devbox '{registered.workspace}'. Remove it with "
- f"`hogli devbox:destroy {registered_label or ''}` before you pick another label."
+ f"`{box_naming.destroy_command(registered.workspace)}` before you pick another label."
)
existing = get_workspace(name, workspaces)
owner = worktree_box_claimant(boxes, root, name, existing)
@@ -196,7 +257,7 @@ def _resolve_target(
f"A devbox named '{name}' already exists and is not tied to this worktree. "
f"Pass `--label {resolved_label}` to use it anyway, or `--label <other>` for a new box."
)
- return _WorktreeTarget(workspace_name=name, label=resolved_label)
+ return _WorktreeTarget(workspace_name=name, label=resolved_label, abandoned_mirror=abandoned_mirror)
def _list_workspaces_or_fail() -> list[dict[str, Any]]:
@@ -240,6 +301,15 @@ def _list_workspaces_or_fail() -> list[dict[str, Any]]:
f"{', '.join(WORKTREE_AUTO_SOURCES)}. 'off' turns it off. Only saves the setting."
),
)
+ "--provider",
+ type=click.Choice(WORKTREE_PROVIDERS),
+ default=None,
+ help=(
+ "Where the box runs. Defaults to the saved provider, or coder. "
+ "With --auto, also saves it for automatic worktree boxes."
+ ),
+)
@click.option("--dry-run", is_flag=True, help="Print the plan without changing anything")
@click.option("-y", "--yes", is_flag=True, help="Skip the clone confirmation prompt")
@click.option("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")
@@ -251,12 +321,16 @@ def devbox_worktree(
start_app: bool | None,
on_clean: str | None,
auto_sources: str | None,
+ provider: str | None,
dry_run: bool,
yes: bool,
verbose: bool,
) -> None:
if auto_sources is not None:
_save_auto_sources(auto_sources)
+ if provider is not None:
+ save_worktree_provider(provider)
+ click.echo(f"Worktree devboxes now run on {provider}.")
return
root = _detect_local_posthog_checkout()
@@ -266,11 +340,24 @@ def devbox_worktree(
"Use `hogli devbox:start` and `hogli devbox:sync` for it."
)
+ if (provider or saved_worktree_provider()) == "hogland":
+ if clone_from is not None or start_app is not None:
+ raise click.UsageError("--clone-from and --start-app work only with --provider coder.")
+ _hogland_worktree(root, label, on_clean, dry_run, verbose)
+ return
+
ensure_runtime_ready()
workspaces = _list_workspaces_or_fail()
cloning = clone_from is not None
clone_source = None if clone_from in (None, "default") else clone_from
- target = _resolve_target(root, label, cloning, clone_source, workspaces)
+ target = _resolve_target(
+ root,
+ label,
+ workspaces,
+ "coder",
+ extract_workspace_label,
+ lambda: _coder_naming(cloning, clone_source),
+ )
existing = get_workspace(target.workspace_name, workspaces)
has_sync = bool(mutagen.sync_list(label_selector=mutagen.workspace_label_selector(target.workspace_name)))
@@ -288,6 +375,37 @@ def devbox_worktree(
else f"Mirror {root} to coder.{target.workspace_name}:{_REMOTE_REPO_PATH}"
)
+ if not _print_plan(root, box_step, sync_step, on_clean, dry_run):
+ return
+ git_dir, worktree_id = _claim_box(root, target, existing, on_clean, "coder")
+ _drop_abandoned_mirror(target)
+
+ region = region_from_workspace_name(target.workspace_name)
+ if existing is None and cloning:
+ ctx.invoke(devbox_clone, workspace=clone_source, new_label=target.label, yes=yes, verbose=verbose)
+ elif existing is None:
+ ctx.invoke(devbox_start, workspace=target.label, region=region, start_app=start_app, verbose=verbose)
+ else:
+ ctx.invoke(devbox_start, workspace=target.label, region=region, verbose=verbose)
+
+ workspaces = _list_workspaces_or_fail()
+ created = get_workspace(target.workspace_name, workspaces)
+ if existing is None and created is not None:
+ record_worktree_box(
+ root,
+ WorktreeBoxRecord(
+ workspace=target.workspace_name,
+ git_dir=str(git_dir),
+ workspace_id=created.get("id"),
+ worktree_id=worktree_id,
+ ),
+ )
+ ensure_sync_session(target.workspace_name, workspaces, root, verbose=verbose)
+ click.echo()
+ click.echo(f"App URL, once the stack runs on the box: {_app_url(target.workspace_name)}")
+
+
+def _print_plan(root: Path, box_step: str, sync_step: str, on_clean: str | None, dry_run: bool) -> bool:
click.echo(f"Worktree: {root}")
click.echo(f" 1. {box_step}")
click.echo(f" 2. {sync_step}")
@@ -295,8 +413,13 @@ def devbox_worktree(
click.echo(f" 3. Save worktrees:clean devbox action: {on_clean}")
if dry_run:
click.echo("[DRY-RUN] Nothing changed.")
- return
+ return False
+ return True
+
+def _claim_box(
+ root: Path, target: _WorktreeTarget, existing: dict[str, Any] | None, on_clean: str | None, provider: str
+) -> tuple[Path, str]:
git_dir = _git_dir(root)
worktree_id = ensure_worktree_id(git_dir)
owner = claim_worktree_box(
@@ -306,6 +429,7 @@ def devbox_worktree(
git_dir=str(git_dir),
workspace_id=None if existing is None else existing.get("id"),
worktree_id=worktree_id,
+ provider=provider,
),
existing,
)
@@ -315,30 +439,59 @@ def devbox_worktree(
clear_worktree_box_cleanup()
elif on_clean is not None:
save_worktree_box_cleanup(on_clean)
+ return git_dir, worktree_id
- region = region_from_workspace_name(target.workspace_name)
- if existing is None and cloning:
- ctx.invoke(devbox_clone, workspace=clone_source, new_label=target.label, yes=yes, verbose=verbose)
- elif existing is None:
- ctx.invoke(devbox_start, workspace=target.label, region=region, start_app=start_app, verbose=verbose)
+
+def _drop_abandoned_mirror(target: _WorktreeTarget) -> None:
+ if target.abandoned_mirror is not None:
+ mutagen.sync_terminate(mutagen.workspace_label_selector(target.abandoned_mirror))
+
+
+def _hogland_worktree(root: Path, label: str | None, on_clean: str | None, dry_run: bool, verbose: bool) -> None:
+ hogland.ensure_cli()
+ devboxes = hogland.fetch_devboxes()
+ target = _resolve_target(root, label, devboxes, "hogland", hogland.label_of, _hogland_naming)
+ name = target.workspace_name
+ existing = get_workspace(name, devboxes)
+ has_sync = bool(mutagen.sync_list(label_selector=mutagen.workspace_label_selector(name)))
+
+ if existing is None:
+ box_step = f"Create Hogland devbox '{name}'"
+ elif existing["status"] == "running":
+ box_step = f"Use running Hogland devbox '{name}'"
else:
- ctx.invoke(devbox_start, workspace=target.label, region=region, verbose=verbose)
+ box_step = f"Wake Hogland devbox '{name}' ({existing['status']})"
+ sync_step = (
+ "Keep the existing sync mirror"
+ if has_sync
+ else f"Mirror {root} to {hogland.ssh_alias(name)}:{hogland.REMOTE_REPO_PATH}"
+ )
+ if not _print_plan(root, box_step, sync_step, on_clean, dry_run):
+ return
+ git_dir, worktree_id = _claim_box(root, target, existing, on_clean, "hogland")
+ _drop_abandoned_mirror(target)
- workspaces = _list_workspaces_or_fail()
- created = get_workspace(target.workspace_name, workspaces)
+ click.echo(f"Bringing up Hogland devbox '{name}'...")
+ endpoint = hogland.up(name, _checked_out_branch(root))
+ hogland.write_ssh_entry(name, endpoint)
+
+ created = get_workspace(name, hogland.fetch_devboxes())
if existing is None and created is not None:
record_worktree_box(
root,
WorktreeBoxRecord(
- workspace=target.workspace_name,
+ workspace=name,
git_dir=str(git_dir),
workspace_id=created.get("id"),
worktree_id=worktree_id,
+ provider="hogland",
),
)
- ensure_sync_session(target.workspace_name, workspaces, root, verbose=verbose)
+ ensure_hogland_sync_session(name, root, verbose=verbose)
click.echo()
- click.echo(f"App URL, once the stack runs on the box: {_app_url(target.workspace_name)}")
+ click.echo(f" SSH hogland devbox ssh {name}")
+ click.echo(" Start cd ~/posthog && hogli start -d")
+ click.echo(f" Stop hogland devbox hibernate {name}")
@click.command(
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
index b9399ce2f258..5b384f1970c3 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
@@ -21,6 +21,7 @@ from hogli_commands.devbox import (
cli as devbox_cli,
coder,
config as devbox_config,
+ hogland as devbox_hogland,
mutagen as devbox_mutagen,
sync as devbox_sync,
worktree as devbox_worktree,
@@ -1088,6 +1089,49 @@ class TestDevboxWorktreeCommand:
assert str(other) in result.output
assert str(worktree_root) not in devbox_config.load_worktree_boxes()
+ @pytest.mark.parametrize(
+ "recorded_id, live_boxes, dry_run, expected_exit",
+ [
+ pytest.param("box-1", [{"name": "wt-feat", "id": "box-1"}], False, 1, id="live-box-blocks-the-switch"),
+ pytest.param(None, [{"name": "wt-feat", "id": "box-1"}], False, 1, id="live-box-with-unrecorded-id-blocks"),
+ pytest.param("box-1", [], False, 0, id="deleted-box-switches-and-drops-its-mirror"),
+ pytest.param("box-1", [], True, 0, id="dry-run-keeps-registration-and-mirror"),
+ ],
+ )
+ def test_switching_provider_away_from_hogland(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ worktree_root: Path,
+ recorded_id: str | None,
+ live_boxes: list[dict[str, str]],
+ dry_run: bool,
+ expected_exit: int,
+ ) -> None:
+ devbox_config.record_worktree_box(
+ worktree_root,
+ devbox_config.WorktreeBoxRecord(
+ workspace="wt-feat", git_dir="admin", workspace_id=recorded_id, provider="hogland"
+ ),
+ )
+ monkeypatch.setattr(devbox_worktree.hogland, "ensure_cli", lambda: None)
+ monkeypatch.setattr(devbox_worktree.hogland, "fetch_devboxes", lambda: live_boxes)
+ monkeypatch.setattr(devbox_worktree, "fetch_user_workspaces", lambda: [])
+ monkeypatch.setattr(devbox_cli, "list_user_workspaces", lambda: [])
+ monkeypatch.setattr(devbox_worktree, "devbox_start", lambda **kwargs: None)
+ monkeypatch.setattr(devbox_worktree, "ensure_sync_session", lambda *a, **kw: None)
+ terminated: list[str] = []
+ monkeypatch.setattr(devbox_worktree.mutagen, "sync_terminate", terminated.append)
+
+ result = runner.invoke(
+ cli, ["devbox:worktree", "--provider", "coder", "--label", "feat", *(["--dry-run"] if dry_run else [])]
+ )
+
+ assert result.exit_code == expected_exit, result.output
+ switched = expected_exit == 0 and not dry_run
+ expected_record = "devbox-test-user-feat" if switched else "wt-feat"
+ assert devbox_config.load_worktree_boxes()[str(worktree_root)].workspace == expected_record
+ assert terminated == ([devbox_worktree.mutagen.workspace_label_selector("wt-feat")] if switched else [])
+
class TestWorkspaceRegion:
"""Reading the region back from the workspace `region` metadata item."""
@@ -4139,8 +4183,8 @@ class TestKeepaliveShim:
@pytest.mark.parametrize(
"target, bumped",
- [("coder.devbox-test-user", True), ("[email protected]", False)],
- ids=["devbox-host-bumped", "non-devbox-host-untouched"],
+ [("coder.devbox-test-user", True), ("hogland.wt-test", True), ("[email protected]", False)],
+ ids=["devbox-host-bumped", "hogland-host-bumped-with-config", "non-devbox-host-untouched"],
)
def test_shim_rewrites_ssh_options_only_for_devbox_hosts(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, target: str, bumped: bool
@@ -4177,6 +4221,8 @@ class TestKeepaliveShim:
"-oConnectTimeout=": f"-oConnectTimeout={devbox_mutagen._CONNECT_TIMEOUT_SECONDS}",
}
expected = [next((v for k, v in rewrites.items() if a.startswith(k)), a) for a in incoming]
+ if target.startswith("hogland."):
+ expected = ["-F", str(devbox_mutagen.hogland_ssh_config_path()), *expected]
assert forwarded == expected
assert "-oServerAliveCountMax=1" not in forwarded
assert "-oConnectTimeout=5" not in forwarded
@@ -4870,3 +4916,52 @@ class TestRenderSyncStatus:
rendered = devbox_cli._render_sync_status("devbox-test-user")
assert "watching" in rendered
assert "●" in rendered
+
+
+class TestHoglandEndpoint:
+ @pytest.mark.parametrize(
+ "known_box_id, box_id, key_reset",
+ [
+ pytest.param("box-1", "box-1", False, id="same-box-keeps-host-key"),
+ pytest.param("box-1", "box-2", True, id="replacement-box-resets-host-key"),
+ pytest.param(None, "box-1", True, id="unknown-box-resets-host-key"),
+ ],
+ )
+ def test_host_key_resets_when_the_box_changes(
+ self,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ known_box_id: str | None,
+ box_id: str,
+ key_reset: bool,
+ ) -> None:
+ monkeypatch.setattr(devbox_hogland, "_SSH_DIR", tmp_path)
+ (tmp_path / "known_hosts").write_text("hogland.wt-feat ssh-ed25519 AAAA\n")
+ if known_box_id is not None:
+ (tmp_path / "hosts").mkdir()
+ (tmp_path / "hosts" / "wt-feat.box-id").write_text(known_box_id)
+ endpoint = devbox_hogland.parse_endpoint(
+ {
+ "action": "noop-already-running",
+ "box": {"id": box_id, "status": "running", "public_ip": "192.0.2.10", "guest_ssh_port": 2222},
+ }
+ )
+
+ with patch.object(devbox_hogland.subprocess, "run") as run:
+ devbox_hogland.write_ssh_entry("wt-feat", endpoint)
+
+ assert run.called is key_reset
+ assert (tmp_path / "hosts" / "wt-feat.box-id").read_text() == box_id
+
+ @pytest.mark.parametrize(
+ "label",
+ ["feat\n HostName 192.0.2.99", "../escape", "Feat", "-feat"],
+ ids=["newline-injects-ssh-directive", "path-traversal", "uppercase", "leading-hyphen"],
+ )
+ def test_unsafe_label_is_refused(self, label: str) -> None:
+ with pytest.raises(SystemExit):
+ devbox_hogland.name_for_label(label)
+
+ def test_box_without_ssh_fails(self) -> None:
+ with pytest.raises(SystemExit):
+ devbox_hogland.parse_endpoint({"action": "running", "box": {"id": "box-1", "status": "placing"}})
diff --git a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py b/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
index b65641d04b37..c9ee6cc20f75 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
@@ -477,6 +477,55 @@ class TestWorktreeBoxes:
kept = live_id == box_a.workspace_id and not acted
assert devbox_config.load_worktree_boxes() == ({str(tmp_path / "a"): box_a} if kept else {})
+ @pytest.mark.parametrize(
+ ("action", "status", "expected_calls"),
+ [
+ ("delete", "running", [("hogland-delete", "wt-a"), ("coder-delete", "devbox-test-user-b")]),
+ ("stop", "running", [("hogland-hibernate", "wt-a"), ("coder-stop", "devbox-test-user-b")]),
+ ("stop", "hibernated", [("coder-stop", "devbox-test-user-b")]),
+ ],
+ ids=["delete", "stop-hibernates", "stop-already-hibernated"],
+ )
+ def test_routes_each_box_to_its_own_provider(
+ self, tmp_path, monkeypatch, registry_path, action, status, expected_calls
+ ) -> None:
+ calls: list[tuple[str, str]] = []
+ monkeypatch.setattr(worktrees, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(
+ worktrees,
+ "fetch_user_workspaces",
+ lambda: [{"name": "devbox-test-user-b", "id": "id-b", "status": "running"}],
+ )
+ monkeypatch.setattr(worktrees, "get_workspace_status", lambda ws: ws["status"])
+ monkeypatch.setattr(worktrees, "delete_workspace", lambda name: calls.append(("coder-delete", name)))
+ monkeypatch.setattr(worktrees, "stop_workspace", lambda name: calls.append(("coder-stop", name)))
+ monkeypatch.setattr(worktrees.hogland, "ensure_cli", lambda: None)
+ monkeypatch.setattr(
+ worktrees.hogland, "fetch_devboxes", lambda: [{"name": "wt-a", "id": "created-a", "status": status}]
+ )
+ monkeypatch.setattr(worktrees.hogland, "delete", lambda name: calls.append(("hogland-delete", name)))
+ monkeypatch.setattr(worktrees.hogland, "hibernate", lambda name: calls.append(("hogland-hibernate", name)))
+ monkeypatch.setattr(worktrees.hogland, "forget_ssh_entry", lambda name: None)
+ monkeypatch.setattr(worktrees.mutagen, "sync_terminate", lambda selector: None)
+ devbox_config.record_worktree_box(
+ tmp_path / "a",
+ devbox_config.WorktreeBoxRecord(
+ workspace="wt-a", git_dir="admin", workspace_id="created-a", provider="hogland"
+ ),
+ )
+ devbox_config.record_worktree_box(tmp_path / "b", _box("devbox-test-user-b", workspace_id="id-b"))
+
+ _clean_worktree_boxes(
+ [
+ WorktreeBox(worktree_path=Path(path), record=record)
+ for path, record in devbox_config.load_worktree_boxes().items()
+ ],
+ action,
+ )
+
+ assert calls == expected_calls
+ assert devbox_config.load_worktree_boxes() == {}
+
@pytest.mark.parametrize(
"listed",
[[{"name": "devbox-test-user-a", "id": "id-a"}], None],
diff --git a/tools/hogli-commands/hogli_commands/worktrees.py b/tools/hogli-commands/hogli_commands/worktrees.py
index 315d41d3583a..b34a152e66e9 100644
--- a/tools/hogli-commands/hogli_commands/worktrees.py
+++ b/tools/hogli-commands/hogli_commands/worktrees.py
@@ -37,7 +37,7 @@ from pathlib import Path
import click
from hogli.manifest import REPO_ROOT
-from .devbox import mutagen
+from .devbox import hogland, mutagen
from .devbox.coder import (
delete_workspace,
ensure_runtime_ready,
@@ -520,6 +520,63 @@ def _box_last_used(workspace: Mapping[str, object]) -> float | None:
def _clean_worktree_boxes(boxes: list[WorktreeBox], box_action: str, idle_before: float = float("inf")) -> None:
+ hogland_boxes = [box for box in boxes if box.record.provider == "hogland"]
+ coder_boxes = [box for box in boxes if box.record.provider != "hogland"]
+ if hogland_boxes:
+ _clean_hogland_boxes(hogland_boxes, box_action, idle_before)
+ if coder_boxes:
+ _clean_coder_boxes(coder_boxes, box_action, idle_before)
+
+
+def _clean_hogland_boxes(boxes: list[WorktreeBox], box_action: str, idle_before: float) -> None:
+ try:
+ hogland.ensure_cli()
+ devboxes = hogland.fetch_devboxes()
+ except SystemExit:
+ names = " ".join(box.workspace for box in boxes)
+ click.echo(f" ⚠️ could not reach Hogland, so these devboxes were left as they are: {names}")
+ return
+ handled: list[Path] = []
+ for box in boxes:
+ devbox = get_workspace(box.workspace, devboxes)
+ if devbox is None:
+ click.echo(f" {box.workspace} no longer exists.")
+ hogland.forget_ssh_entry(box.workspace)
+ handled.append(box.worktree_path)
+ continue
+ if not box.record.owns(devbox):
+ click.echo(f" {box.workspace} was recreated after this worktree set it up, so it was left alone.")
+ handled.append(box.worktree_path)
+ continue
+ last_used = _box_last_used(devbox)
+ if idle_before != float("inf") and (last_used is None or last_used >= idle_before):
+ click.echo(
+ f" {box.workspace} was used after the cutoff, or its last use is unknown, so it was left alone."
+ )
+ continue
+ try:
+ mutagen.sync_terminate(mutagen.workspace_label_selector(box.workspace))
+ except SystemExit:
+ click.echo(f" ⚠️ could not remove the sync mirror for {box.workspace}; continuing.")
+ try:
+ if box_action == "delete":
+ click.echo(f"Deleting Hogland devbox {box.workspace}...")
+ hogland.delete(box.workspace)
+ hogland.forget_ssh_entry(box.workspace)
+ elif devbox["status"] == "running":
+ click.echo(f"Hibernating Hogland devbox {box.workspace}...")
+ hogland.hibernate(box.workspace)
+ else:
+ click.echo(f" {box.workspace} is already {devbox['status']}.")
+ except SystemExit:
+ command = "delete" if box_action == "delete" else "hibernate"
+ click.echo(f" ⚠️ could not {box_action} {box.workspace}. Run `hogland devbox {command} {box.workspace}`.")
+ continue
+ handled.append(box.worktree_path)
+ forget_worktree_boxes(handled)
+
+
+def _clean_coder_boxes(boxes: list[WorktreeBox], box_action: str, idle_before: float) -> None:
try:
ensure_runtime_ready()
except SystemExit: