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): per-worktree boxes and branch-aligned sync (#122350)

Georges-Antoine Assi08b39ee99a35
diff --git a/.agents/skills/setting-up-devbox/SKILL.md b/.agents/skills/setting-up-devbox/SKILL.md
index 14234f27e02e..63fadd3cb439 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: Starts, connects to, and troubleshoots a PostHog devbox, a remote Coder workspace for PostHog development that can also run the full stack, through `hogli devbox:*` commands. Use when asked to spin up or resume a devbox, open a shell or editor on it, run a command on it, mirror a local checkout to it (devbox:sync), run the PostHog app on it and share a link, clone, update, share, or free disk on a devbox, store gh or Claude Code tokens for it, or diagnose a failing devbox command (tailnet, DNS, Coder CLI version, SSH). Not for running the stack on the local machine or for changing the Coder template in posthog-cloud-infra.
+description: Starts, connects to, and troubleshoots a PostHog devbox, a remote Coder workspace for PostHog development that can also run the full stack, through `hogli devbox:*` commands. Use when asked to spin up or resume a devbox, open a shell or editor on it, run a command on it, mirror a local checkout to it (devbox:sync), give each git worktree its own box (devbox:worktree), run the PostHog app on it and share a link, clone, update, share, or free disk on a devbox, store gh or Claude Code tokens for it, or diagnose a failing devbox command (tailnet, DNS, Coder CLI version, SSH). Not for running the stack on the local machine or for changing the Coder template in posthog-cloud-infra.
---
# Setting up a PostHog devbox
@@ -91,6 +91,7 @@ Match what the user asked for:
- **Commands from an agent:** `hogli devbox:exec`, described in [Run commands on the box](#run-commands-on-the-box).
- **Edit locally, run on the box:** read [references/sync.md](references/sync.md) before using `hogli devbox:sync`.
- **The running app:** follow [Run the PostHog app](#run-the-posthog-app).
+- **A box per git worktree:** follow [One devbox per worktree](#one-devbox-per-worktree).
### 5. Stop when done
@@ -163,6 +164,40 @@ Coder runs the template's health check against the app, so read that status inst
It tunnels box port 8010 to `localhost:8010` and holds the terminal until stopped.
Pass `--port 8011` when a local stack already uses 8010.
+## One devbox per worktree
+
+Use this when the user runs several local git worktrees and wants each one to run its stack on its own box.
+Run `hogli devbox:worktree` from inside the linked worktree, never through `devbox:exec`.
+
+```bash
+hogli devbox:worktree --dry-run # print the box and sync plan
+hogli devbox:worktree # start or create the box, then create the mirror
+hogli devbox:worktree --clone-from default -y # create the box as a clone of a running box
+hogli devbox:worktree --on-clean stop # save what worktrees:clean does with the box
+```
+
+- The label comes from the branch name, lowercased, with `/` and `_` turned into `-` and a leading `worktree-` dropped. Coder caps workspace names at 32 characters, so a long branch gets a shortened label with a 4-character hash. Pass `--label` to choose one.
+- hogli records the worktree path and box name in `~/.config/posthog/hogli_devbox_worktrees.json`. A re-run reuses that box, even after a branch rename, and keeps an existing mirror.
+- It refuses a derived label whose box already exists and is not recorded for this worktree, so it never takes over a box the user made by hand. Pass `--label <label>` to use that box on purpose. It always refuses a box recorded for another worktree.
+- `--clone-from` uses `devbox:clone`, so the source must be running and the clone asks for confirmation unless `-y` is passed. Pass `-y` only after the user agrees.
+- `hogli worktrees:clean --mode full --stop-boxes` stops the recorded box of each worktree it removes, and `--delete-boxes` deletes it with its disk. With neither flag, it uses the action saved by `--on-clean`, and `--keep-boxes` overrides that. It acts only on boxes in the record file, and skips a box that was recreated under the same name. A box it leaves alone is dropped from the record file, so a later run never touches it. `--dry-run` lists the boxes, and the confirmation prompt counts them.
+- 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`.
+
+### Provision a box for every new worktree
+
+`hogli devbox:worktree --auto claude,phw` saves the worktree sources that get a box automatically.
+The sources are `claude`, `codex`, `posthog-code`, `phw`, and `other` for a worktree outside those folders.
+It only saves the setting, so run it from any checkout.
+After that, the husky `post-checkout` hook runs `hogli devbox:worktree -y` in the background each time `git worktree add` creates a worktree from one of those sources.
+That covers `claude -w`, Codex, PostHog Desktop, `phw`, and a plain `git worktree add`.
+
+- Claude subagent worktrees (`.claude/worktrees/agent-*`) never get a box, so a fan-out of agents doesn't create one box per agent.
+- The hook returns at once. Output goes to `hogli-devbox-worktree.log` in the worktree's git directory. Read it with `cat "$(git rev-parse --git-dir)/hogli-devbox-worktree.log"`.
+- The hook skips the box when the main checkout has no Python environment to borrow, or when this worktree's `uv.lock` differs from the main checkout's.
+- Turn it off with `hogli devbox:worktree --auto off` or `hogli devbox:config:rm worktree-auto`.
+- Boxes keep running until `hogli worktrees:clean` removes their worktree, so pair this with `--on-clean stop`.
+
## Other tasks
- **Tokens on the box:** store them as Coder user secrets, which reach every box the user owns. `hogli devbox:secret:set GH_TOKEN` reads the value from a hidden prompt or from `--file`. Never put a token on a command line or in the conversation. A secret reaches only boxes started after it is set, so run `hogli devbox:restart` on a running box. The template documents `CLAUDE_CODE_OAUTH_TOKEN`, `GH_TOKEN`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, and `POSTHOG_GIT_SIGNING_KEY`, which `hogli devbox:setup --configure-git-signing` sets. `devbox:secret:list` shows names, env vars, and descriptions, never values.
diff --git a/.agents/skills/setting-up-devbox/references/sync.md b/.agents/skills/setting-up-devbox/references/sync.md
index c327b0cf7118..be70134a8666 100644
--- a/.agents/skills/setting-up-devbox/references/sync.md
+++ b/.agents/skills/setting-up-devbox/references/sync.md
@@ -19,7 +19,7 @@ hogli devbox:sync --terminate # remove the mirror when done
- **Run it locally, from the checkout to mirror.** It walks up from the working directory to find `hogli.yaml` and `.git`, so run it from the repo root being edited, including a worktree. Never run it through `devbox:exec`.
- **Remote-only files stay.** The sync mode is `one-way-safe`, so the box's prewarmed `node_modules`, virtualenv, and `target/` are never deleted. Files that exist on the box but not locally when the mirror is created also stay, such as files the branch deleted, so remove them on the box when a check could pick them up. Lockfiles do sync, so after a lockfile change install dependencies on the box through `devbox:exec` before trusting its checks.
-- **A feature branch conflicts on first sync.** A new box is on `master`, so every file the branch changed shows as a conflict in the sync state. Conflicts are per path: other files, including new ones, still sync. Resolve a path, or check out the same branch on the box, only when that file must be mirrored.
+- **The first sync puts the box on the local branch.** A new box is on `master`, and the first mirror shows every tracked file that differs between the two checkouts as a conflict. So before it creates the mirror, `devbox:sync` compares the local branch and SHA with the box's checkout. When they differ and the box has no uncommitted changes, it fetches the local SHA from `origin` on the box and checks it out there. Push the branch first, because the box can't fetch local-only commits. When the box has uncommitted changes, the SHA isn't on `origin`, or the box branch has commits the local one lacks, it leaves the box alone, warns, and mirrors anyway. Pass `--checkout-branch` to fail instead, or `--no-checkout-branch` to skip the check. Local uncommitted edits still conflict on the first sync. Conflicts are per path: other files, including new ones, still sync.
- **A stopped box's mirror waits paused.** `devbox:stop` pauses the mirror, and `devbox:start` resumes it once the box is up. A plain `devbox:sync` leaves a paused mirror paused, so resume one that a box started elsewhere with `--resume`.
- **The mirror never starts a box.** Its SSH connections run with Coder's autostart off, so a mirror to a box Coder stopped fails until the box runs again.
- **Don't edit mirrored files on the box.** Remote edits fight the local source of truth. `devbox:open --vscode` and `--cursor` warn when a sync is active.
diff --git a/.husky/post-checkout b/.husky/post-checkout
index 30564f32f794..ed7c7840cc04 100755
--- a/.husky/post-checkout
+++ b/.husky/post-checkout
@@ -16,6 +16,21 @@
HOOK_DIR="$(cd "$(dirname "$0")" && pwd)"
if [ -f "$HOOK_DIR/../bin/helpers/worktree-borrow.sh" ]; then
. "$HOOK_DIR/../bin/helpers/worktree-borrow.sh"
+
+ # `git worktree add` checks out from the all-zeros ref. The grep keeps
+ # Python off the path of everyone who has not run `devbox:worktree --auto`.
+ # hogli, its manifest, its tools and its imports come from the hook's
+ # checkout or the main clone, never from the new worktree, whose branch may
+ # not be trusted. PYTHONPATH could name the worktree through `.` despite -P.
+ case "$1" in
+ *[!0]*) ;;
+ *)
+ if grep -qs '"worktree_auto_box"' "$HOME/.config/posthog/hogli_devbox.json"; then
+ (unset PYTHONPATH && posthog_worktree_borrow main-only && HOGLI_MANIFEST="$HOOK_DIR/../hogli.yaml" "$HOOK_DIR/../bin/hogli" devbox:worktree:auto) || echo "husky: couldn't start the automatic devbox. Run 'hogli devbox:worktree'."
+ fi
+ ;;
+ esac
+
posthog_worktree_borrow node
fi
diff --git a/bin/helpers/worktree-borrow.sh b/bin/helpers/worktree-borrow.sh
index 6cf5cbfd6923..2839a241a9ee 100644
--- a/bin/helpers/worktree-borrow.sh
+++ b/bin/helpers/worktree-borrow.sh
@@ -57,8 +57,10 @@ posthog_export_ca_bundle() {
# Borrow the main clone's toolchain into the current shell's environment.
# Must be called with cwd = repo root (the hooks guarantee that). Scope $1 is
-# `node` or `all` (default): post-checkout only needs the node borrow, so it
-# skips the venv work (including the uv.lock compare, which isn't free).
+# `node`, `all` (default) or `main-only`: post-checkout only needs the node
+# borrow, so it skips the venv work (including the uv.lock compare, which isn't
+# free). `main-only` is `all` without the worktree's flox env, for callers that
+# run with the user's credentials in a worktree whose branch may not be trusted.
posthog_worktree_borrow() {
_ph_scope="${1:-all}"
_ph_main="$(posthog_main_repo "$(pwd)")"
@@ -69,12 +71,14 @@ posthog_worktree_borrow() {
# flox-activated shell. Prefer the worktree's own flox env, because the
# main clone's can pin older tools than this worktree's branch requires.
_ph_flox_root="$_ph_main"
- for _ph_bin in .flox/run/*/bin; do
- if [ -d "$_ph_bin" ]; then
- _ph_flox_root="$(pwd)"
- break
- fi
- done
+ if [ "$_ph_scope" != "main-only" ]; then
+ for _ph_bin in .flox/run/*/bin; do
+ if [ -d "$_ph_bin" ]; then
+ _ph_flox_root="$(pwd)"
+ break
+ fi
+ done
+ fi
if [ -d "$_ph_flox_root/.flox/run" ]; then
_ph_flox_on_path=""
for _ph_bin in "$_ph_flox_root/.flox/run"/*/bin; do
@@ -97,7 +101,7 @@ posthog_worktree_borrow() {
fi
fi
- if [ "$_ph_scope" = "all" ] && [ -z "$(posthog_find_venv "$(pwd)")" ]; then
+ if [ "$_ph_scope" != "node" ] && [ -z "$(posthog_find_venv "$(pwd)")" ]; then
_ph_main_venv="$(posthog_find_venv "$_ph_main")"
if [ -n "$_ph_main_venv" ]; then
if cmp -s uv.lock "$_ph_main/uv.lock"; then
diff --git a/bin/hogli b/bin/hogli
index 8d45ffeed514..2cf58d8017ab 100755
--- a/bin/hogli
+++ b/bin/hogli
@@ -29,7 +29,10 @@ fi
# Migration aid: after the common/hogli/ -> tools/hogli/ + tools/hogli-commands/
# restructure, users with stale venvs see `ModuleNotFoundError: hogli`. Catch it
# early and point at `uv sync`. Safe to delete once everyone has re-activated.
-HOGLI_IMPORT_ERR="$("$PYTHON_CMD" -c "import hogli" 2>&1)" || true
+# -P keeps the current directory off sys.path. Hooks run this from the worktree
+# being checked out, whose branch could otherwise ship a `hogli` package that
+# shadows the installed one.
+HOGLI_IMPORT_ERR="$("$PYTHON_CMD" -P -c "import hogli" 2>&1)" || true
if [[ -n "$HOGLI_IMPORT_ERR" && "$HOGLI_IMPORT_ERR" == *"No module named 'hogli'"* ]]; then
cat >&2 <<'EOF'
error: the `hogli` package is not importable from your active venv.
@@ -45,4 +48,4 @@ EOF
exit 127
fi
-exec "$PYTHON_CMD" -m hogli "$@"
+exec "$PYTHON_CMD" -P -m hogli "$@"
diff --git a/docs/internal/coder-workspaces.md b/docs/internal/coder-workspaces.md
index 6e06e168541b..22ae7f878203 100644
--- a/docs/internal/coder-workspaces.md
+++ b/docs/internal/coder-workspaces.md
@@ -63,6 +63,14 @@ hogli devbox:sync --terminate # tear down when done
`devbox:open --vscode` / `--cursor` warns when sync is active, since editing over Remote-SSH while the mirror is live would conflict with the local source of truth.
+**One devbox per git worktree** —
+Run `hogli devbox:worktree` from a linked worktree to give it its own labeled box and sync mirror. The label comes from the branch name, shortened with a hash when it would push the workspace name past Coder's 32-character limit. Re-running reuses the same box and mirror. `--clone-from <label>` creates the box with `devbox:clone`, and `--dry-run` prints the plan.
+
+`hogli worktrees:clean --mode full --stop-boxes` (or `--delete-boxes`) also stops (or deletes) the box of each worktree it removes. Save a default with `hogli devbox:worktree --on-clean stop|delete|keep`, and override it with `--keep-boxes`. Only boxes that `devbox:worktree` set up are touched.
+It also handles boxes whose worktree was already removed some other way, but only once the box itself has not been used since the `--before` cutoff.
+
+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`.
+
## 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/hogli.yaml b/hogli.yaml
index 20ba6062933f..b752fdb5a878 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -207,6 +207,13 @@ devbox:
devbox:sync:
click: hogli_commands.devbox.sync:cmd_sync
description: Mirror your local PostHog checkout to a devbox
+ devbox:worktree:
+ click: hogli_commands.devbox.worktree:devbox_worktree
+ description: Give this worktree its own devbox and sync mirror
+ devbox:worktree:auto:
+ click: hogli_commands.devbox.worktree:devbox_worktree_auto
+ description: Start devbox:worktree in the background for a new worktree, if auto-provisioning is on
+ hidden: true
devbox:secret:list:
click: hogli_commands.devbox.cli:devbox_secret_list
description: List your Coder user secrets
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.py
index 685cb9d10d19..8aac6514f8f0 100644
--- a/tools/hogli-commands/hogli_commands/devbox/cli.py
+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py
@@ -96,6 +96,8 @@ from .config import (
clear_dotfiles_uri,
clear_git_identity,
clear_region,
+ clear_worktree_auto_sources,
+ clear_worktree_box_cleanup,
load_config,
save_dotfiles_uri,
save_git_identity,
@@ -1053,6 +1055,26 @@ def _reset_dotfiles() -> bool:
return True
+def _reset_worktree_box_cleanup() -> bool:
+ config = load_config()
+ if not config.get("worktree_box_cleanup"):
+ click.echo("Nothing to clear: worktree box cleanup was not set.")
+ return False
+ clear_worktree_box_cleanup(config)
+ click.echo("Cleared worktree box cleanup. `hogli worktrees:clean` now leaves devboxes alone by default.")
+ return True
+
+
+def _reset_worktree_auto_sources() -> bool:
+ config = load_config()
+ if not config.get("worktree_auto_box"):
+ click.echo("Nothing to clear: automatic worktree boxes were off.")
+ return False
+ clear_worktree_auto_sources(config)
+ click.echo("Turned off automatic worktree boxes. New worktrees no longer get a devbox.")
+ return True
+
+
def _git_identity_status(config: DevboxConfig, _: set[str]) -> str | None:
name = config.get("git_name")
email = config.get("git_email")
@@ -1124,6 +1146,20 @@ _CONFIG_ITEMS: tuple[_ConfigItem, ...] = (
status=_secret_status(CLAUDE_CODE_OAUTH_ENV),
reset=lambda: _reset_user_secret(CLAUDE_CODE_OAUTH_ENV),
),
+ _ConfigItem(
+ cli_key="worktree-boxes",
+ label="Worktree box cleanup",
+ needs_secrets=False,
+ status=_field_status("worktree_box_cleanup"),
+ reset=_reset_worktree_box_cleanup,
+ ),
+ _ConfigItem(
+ cli_key="worktree-auto",
+ label="Automatic worktree boxes",
+ needs_secrets=False,
+ status=_field_status("worktree_auto_box"),
+ reset=_reset_worktree_auto_sources,
+ ),
)
@@ -1866,7 +1902,8 @@ def devbox_config_rm(keys: tuple[str, ...], reset_all: bool) -> None:
"""Remove one or more saved devbox configuration items.
Valid keys mirror the matching ``--configure-*`` flags on ``devbox:setup``:
- ``git-identity``, ``git-signing``, ``region``, ``dotfiles``, ``claude``.
+ ``git-identity``, ``git-signing``, ``region``, ``dotfiles``, ``claude``, ``worktree-boxes``,
+ ``worktree-auto``.
"""
by_key = _config_items_by_key()
valid_keys = tuple(by_key)
diff --git a/tools/hogli-commands/hogli_commands/devbox/coder.py b/tools/hogli-commands/hogli_commands/devbox/coder.py
index 92383c3393d3..abe8f2f921a4 100644
--- a/tools/hogli-commands/hogli_commands/devbox/coder.py
+++ b/tools/hogli-commands/hogli_commands/devbox/coder.py
@@ -1153,19 +1153,23 @@ def get_default_workspace_prefix() -> str:
def _list_workspaces(*, timeout: float | None = None) -> list[dict[str, Any]]:
"""Return raw workspace payloads from the Coder CLI."""
+ return _fetch_workspaces(timeout=timeout) or []
+
+
+def _fetch_workspaces(*, timeout: float | None = None) -> list[dict[str, Any]] | None:
try:
result = _run(["coder", "list", "--output", "json"], capture_output=True, timeout=timeout)
except subprocess.TimeoutExpired:
- return []
+ return None
if result.returncode != 0:
- return []
+ return None
try:
workspaces = json.loads(result.stdout)
except json.JSONDecodeError:
- return []
+ return None
- return workspaces if isinstance(workspaces, list) else []
+ return workspaces if isinstance(workspaces, list) else None
def extract_workspace_label(workspace_name: str) -> str | None:
@@ -1208,8 +1212,16 @@ def region_from_workspace_name(workspace_name: str) -> str:
def list_user_workspaces() -> list[dict[str, Any]]:
"""Return all workspaces belonging to the current user with the devbox prefix."""
+ return fetch_user_workspaces() or []
+
+
+def fetch_user_workspaces() -> list[dict[str, Any]] | None:
+ """Like ``list_user_workspaces``, but ``None`` when Coder could not list workspaces."""
+ workspaces = _fetch_workspaces()
+ if workspaces is None:
+ return None
prefix = get_default_workspace_prefix()
- return [ws for ws in _list_workspaces() if ws.get("name") == prefix or ws.get("name", "").startswith(f"{prefix}-")]
+ return [ws for ws in workspaces if ws.get("name") == prefix or ws.get("name", "").startswith(f"{prefix}-")]
def get_workspace(name: str, workspaces: list[dict[str, Any]] | None = None) -> dict[str, Any] | None:
@@ -1836,6 +1848,20 @@ def exec_replace(name: str, command: list[str]) -> None:
_execvp("ssh", ["ssh", _ssh_host_alias(name), shlex.join(command)])
+def run_in_workspace(name: str, command: list[str], *, timeout: float) -> subprocess.CompletedProcess[str]:
+ """Run one command in the workspace like :func:`exec_replace`, but capture its result.
+
+ For callers that must act on the remote exit code and output instead of
+ handing the terminal over to the command.
+ """
+ return subprocess.run(
+ ["ssh", _ssh_host_alias(name), shlex.join(command)],
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ )
+
+
def coder_ssh_alias_configured(name: str) -> bool:
"""Return whether ssh resolves a Coder ``ProxyCommand`` for the workspace host alias.
diff --git a/tools/hogli-commands/hogli_commands/devbox/config.py b/tools/hogli-commands/hogli_commands/devbox/config.py
index 79d52cf407ba..5c36c58b5140 100644
--- a/tools/hogli-commands/hogli_commands/devbox/config.py
+++ b/tools/hogli-commands/hogli_commands/devbox/config.py
@@ -2,9 +2,15 @@
from __future__ import annotations
+import os
import json
+import uuid
+import fcntl
+from collections.abc import Iterator, Mapping, Sequence
+from contextlib import contextmanager
+from dataclasses import asdict, dataclass
from pathlib import Path
-from typing import TypedDict
+from typing import Any, TypedDict
class DevboxConfig(TypedDict, total=False):
@@ -12,9 +18,15 @@ class DevboxConfig(TypedDict, total=False):
git_email: str
dotfiles_uri: str
region: str
+ worktree_box_cleanup: str
+ worktree_auto_box: str
-_PERSISTED_FIELDS = ("git_name", "git_email", "dotfiles_uri", "region")
+_PERSISTED_FIELDS = ("git_name", "git_email", "dotfiles_uri", "region", "worktree_box_cleanup", "worktree_auto_box")
+
+WORKTREE_BOX_CLEANUP_ACTIONS = ("stop", "delete")
+WORKTREE_AUTO_SOURCES = ("claude", "codex", "posthog-code", "phw", "other")
+_WORKTREE_ID_FILE = "hogli-devbox-worktree-id"
def get_config_path() -> Path:
@@ -22,6 +34,10 @@ def get_config_path() -> Path:
return Path.home() / ".config" / "posthog" / "hogli_devbox.json"
+def get_worktree_boxes_path() -> Path:
+ return Path.home() / ".config" / "posthog" / "hogli_devbox_worktrees.json"
+
+
def load_config() -> DevboxConfig:
"""Load persisted hogli devbox preferences from disk."""
try:
@@ -117,3 +133,211 @@ def clear_region(config: DevboxConfig | None = None) -> DevboxConfig:
config.pop("region", None)
save_config(config)
return config
+
+
+def save_worktree_box_cleanup(action: str) -> DevboxConfig:
+ config = load_config()
+ config["worktree_box_cleanup"] = action
+ save_config(config)
+ return config
+
+
+def clear_worktree_box_cleanup(config: DevboxConfig | None = None) -> DevboxConfig:
+ if config is None:
+ config = load_config()
+ config.pop("worktree_box_cleanup", None)
+ save_config(config)
+ return config
+
+
+def saved_worktree_box_cleanup() -> str | None:
+ action = load_config().get("worktree_box_cleanup")
+ return action if action in WORKTREE_BOX_CLEANUP_ACTIONS else None
+
+
+def save_worktree_auto_sources(sources: Sequence[str]) -> DevboxConfig:
+ config = load_config()
+ config["worktree_auto_box"] = ",".join(sources)
+ save_config(config)
+ return config
+
+
+def clear_worktree_auto_sources(config: DevboxConfig | None = None) -> DevboxConfig:
+ if config is None:
+ config = load_config()
+ config.pop("worktree_auto_box", None)
+ save_config(config)
+ return config
+
+
+def saved_worktree_auto_sources() -> frozenset[str]:
+ saved = load_config().get("worktree_auto_box", "")
+ return frozenset(source.strip() for source in saved.split(",")) & frozenset(WORKTREE_AUTO_SOURCES)
+
+
+def read_worktree_id(git_dir: Path) -> str | None:
+ try:
+ return (git_dir / _WORKTREE_ID_FILE).read_text().strip() or None
+ except OSError:
+ return None
+
+
+def ensure_worktree_id(git_dir: Path) -> str:
+ """Return the random ID stored in this worktree's admin directory, writing one first if it has none.
+
+ Git reuses an admin directory name when a worktree is recreated at the same
+ path, but the new directory starts empty, so the ID tells the two apart.
+ """
+ existing = read_worktree_id(git_dir)
+ if existing is not None:
+ return existing
+ worktree_id = uuid.uuid4().hex
+ (git_dir / _WORKTREE_ID_FILE).write_text(f"{worktree_id}\n")
+ return worktree_id
+
+
+@dataclass(frozen=True)
+class WorktreeBoxRecord:
+ """The devbox that `devbox:worktree` set up for one worktree.
+
+ ``workspace_id`` is Coder's immutable ID, so a box destroyed and recreated
+ under the same name is never mistaken for this one. ``git_dir`` is the
+ worktree's admin directory in the shared git dir, which survives
+ `git worktree move` and an unmounted checkout. ``worktree_id`` is the ID
+ that `ensure_worktree_id` stored in that directory.
+ """
+
+ workspace: str
+ git_dir: str
+ workspace_id: str | None = None
+ worktree_id: str | None = None
+
+ def tracks_worktree(self, git_dir: Path) -> bool:
+ """Whether the worktree with admin directory *git_dir* is the one this record was saved for.
+
+ A record without the ID cannot answer that, so it answers no, and
+ `worktrees:clean` leaves its box alone.
+ """
+ return self.worktree_id is not None and read_worktree_id(git_dir) == self.worktree_id
+
+ def owns(self, workspace: Mapping[str, Any]) -> bool:
+ """Whether *workspace* is the box this record was saved for.
+
+ A record without the ID cannot answer that, so it answers no: a run
+ that stopped between provisioning and the workspace lookup saves no ID,
+ and a box recreated under the same name must never be taken for the one
+ this worktree set up and deleted with it.
+ """
+ return self.workspace_id is not None and workspace.get("id") == self.workspace_id
+
+ def may_adopt(self, workspace: Mapping[str, Any]) -> bool:
+ """Whether `devbox:worktree` may keep using *workspace* for this worktree.
+
+ A record without the ID matches the box by name once more, which lets
+ the re-run store the ID that `owns` needs.
+ """
+ return self.workspace_id is None or self.owns(workspace)
+
+
+def load_worktree_boxes() -> dict[str, WorktreeBoxRecord]:
+ """Map each worktree path that `devbox:worktree` set up to the workspace it owns.
+
+ `worktrees:clean` acts only on boxes listed here, so a hand-made labeled box
+ that happens to share a name with a branch is never stopped or deleted.
+ """
+ try:
+ data = json.loads(get_worktree_boxes_path().read_text())
+ except Exception:
+ return {}
+ if not isinstance(data, dict):
+ return {}
+ boxes: dict[str, WorktreeBoxRecord] = {}
+ for path, entry in data.items():
+ if not isinstance(path, str) or not isinstance(entry, dict):
+ continue
+ workspace, git_dir = entry.get("workspace"), entry.get("git_dir")
+ workspace_id, worktree_id = entry.get("workspace_id"), entry.get("worktree_id")
+ 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,
+ )
+ return boxes
+
+
+@contextmanager
+def _locked_worktree_boxes() -> Iterator[None]:
+ path = get_worktree_boxes_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.with_name(f"{path.name}.lock").open("a") as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ yield
+
+
+def _save_worktree_boxes(boxes: dict[str, WorktreeBoxRecord]) -> None:
+ path = get_worktree_boxes_path()
+ staging = path.with_name(f"{path.name}.{os.getpid()}.tmp")
+ serialized = {key: asdict(record) for key, record in sorted(boxes.items())}
+ staging.write_text(json.dumps(serialized, indent=2) + "\n")
+ staging.replace(path)
+
+
+def worktree_box_claimant(
+ boxes: Mapping[str, WorktreeBoxRecord],
+ worktree_path: Path,
+ workspace: str,
+ live_workspace: Mapping[str, Any] | None,
+) -> str | None:
+ """The other worktree that holds *workspace*, or None when the name is free.
+
+ A record holds the name from the moment it is written, so two worktrees
+ that derive the same label cannot both provision it. A record without
+ Coder's ID still holds the name after the box appears, because its
+ worktree may still be setting the box up. Once the ID is saved, only the
+ record that matches it holds the box, and a record left behind by a
+ worktree that is gone holds nothing.
+ """
+ for path, record in boxes.items():
+ if path == str(worktree_path) or record.workspace != workspace:
+ continue
+ if live_workspace is not None and record.owns(live_workspace):
+ return path
+ if (live_workspace is None or record.workspace_id is None) and Path(path).exists():
+ return path
+ return None
+
+
+def record_worktree_box(worktree_path: Path, record: WorktreeBoxRecord) -> None:
+ with _locked_worktree_boxes():
+ boxes = load_worktree_boxes()
+ boxes[str(worktree_path)] = record
+ _save_worktree_boxes(boxes)
+
+
+def claim_worktree_box(
+ worktree_path: Path, record: WorktreeBoxRecord, live_workspace: Mapping[str, Any] | None
+) -> str | None:
+ """Register *record* for this worktree unless another worktree holds the name.
+
+ Returns the worktree that holds it, or None once the claim is saved. The
+ check and the write share the registry lock, so two worktrees racing for the
+ same label cannot both start the same box.
+ """
+ with _locked_worktree_boxes():
+ boxes = load_worktree_boxes()
+ owner = worktree_box_claimant(boxes, worktree_path, record.workspace, live_workspace)
+ if owner is not None:
+ return owner
+ boxes[str(worktree_path)] = record
+ _save_worktree_boxes(boxes)
+ return None
+
+
+def forget_worktree_boxes(worktree_paths: list[Path]) -> None:
+ with _locked_worktree_boxes():
+ boxes = load_worktree_boxes()
+ remaining = {path: record for path, record in boxes.items() if path not in {str(p) for p in worktree_paths}}
+ if remaining != boxes:
+ _save_worktree_boxes(remaining)
diff --git a/tools/hogli-commands/hogli_commands/devbox/sync.py b/tools/hogli-commands/hogli_commands/devbox/sync.py
index 6f99f70e6c46..da207ea47ee9 100644
--- a/tools/hogli-commands/hogli_commands/devbox/sync.py
+++ b/tools/hogli-commands/hogli_commands/devbox/sync.py
@@ -10,6 +10,8 @@ from __future__ import annotations
import json
import subprocess
+from dataclasses import dataclass
+from enum import Enum
from pathlib import Path
from typing import Any
@@ -17,9 +19,93 @@ 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
+from .coder import _fail, ensure_runtime_ready, get_workspace, get_workspace_status, run_in_workspace
_REMOTE_REPO_PATH = "/home/coder/posthog"
+_REMOTE_GIT_TIMEOUT_SECONDS = 120
+_DETACHED = "HEAD"
+
+_PROBE_BOX_HEAD_SCRIPT = f"""
+cd {_REMOTE_REPO_PATH} || exit 1
+git symbolic-ref --quiet --short HEAD || echo {_DETACHED}
+git rev-parse HEAD
+git status --porcelain --untracked-files=no | head -n 1 | wc -l
+"""
+
+# Exit codes of the checkout script, read by _align_box_checkout.
+_CHECKOUT_DIRTY = 3
+_CHECKOUT_SHA_UNAVAILABLE = 2
+_CHECKOUT_BRANCH_DIVERGED = 4
+_CHECKOUT_DETACHED_UNSAVED = 5
+
+# The dirty check repeats inside the script so that an edit made on the box
+# after the probe still blocks the checkout. `checkout -B` only runs when the
+# box's branch is an ancestor of the target, and a detached HEAD is left only
+# when a ref or the target still reaches it, so box-only commits are never
+# dropped. `--no-overwrite-ignore` keeps ignored files such as `.env.local`.
+# Hooks stay off for every git call, fetches included, because the box's branch
+# may carry an untrusted hook, and the session forwards the user's SSH agent.
+_CHECKOUT_SCRIPT = f"""
+branch="$1"; sha="$2"
+export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=core.hooksPath GIT_CONFIG_VALUE_0=/dev/null
+cd {_REMOTE_REPO_PATH} || exit 1
+[ -z "$(git status --porcelain --untracked-files=no)" ] || exit {_CHECKOUT_DIRTY}
+has_sha() {{ git cat-file -e "$sha^{{commit}}" 2>/dev/null; }}
+has_sha || [ "$branch" = {_DETACHED} ] || git fetch --quiet origin "$branch" 2>/dev/null || true
+has_sha || git fetch --quiet origin "$sha" 2>/dev/null || true
+has_sha || exit {_CHECKOUT_SHA_UNAVAILABLE}
+if ! git symbolic-ref --quiet HEAD >/dev/null \\
+ && ! git merge-base --is-ancestor HEAD "$sha" \\
+ && [ -z "$(git for-each-ref --contains HEAD --count=1)" ]; then
+ exit {_CHECKOUT_DETACHED_UNSAVED}
+fi
+[ "$branch" = {_DETACHED} ] && exec git checkout --quiet --no-overwrite-ignore --detach "$sha"
+if git rev-parse --verify --quiet "refs/heads/$branch" >/dev/null \\
+ && ! git merge-base --is-ancestor "refs/heads/$branch" "$sha"; then
+ exit {_CHECKOUT_BRANCH_DIVERGED}
+fi
+exec git checkout --quiet --no-overwrite-ignore -B "$branch" "$sha"
+"""
+
+
+@dataclass(frozen=True)
+class GitHead:
+ branch: str
+ sha: str
+
+ def describe(self) -> str:
+ where = "a detached HEAD" if self.branch == _DETACHED else f"`{self.branch}`"
+ return f"{where} at {self.sha[:10]}"
+
+
+@dataclass(frozen=True)
+class BoxGitState:
+ head: GitHead
+ dirty: bool
+
+
+class BoxCheckoutAction(Enum):
+ SKIP = "skip"
+ MATCHES = "matches"
+ CHECKOUT = "checkout"
+ WARN_DIRTY = "warn_dirty"
+ FAIL_DIRTY = "fail_dirty"
+
+
+def decide_box_checkout(local: GitHead, box: BoxGitState, requested: bool | None) -> BoxCheckoutAction:
+ """Decide whether to move the box's checkout to the local branch before the first mirror.
+
+ ``requested`` is the ``--checkout-branch`` flag: ``None`` checks out only
+ on a clean box, ``True`` fails on a dirty one, ``False`` never touches it.
+ """
+ if requested is False:
+ return BoxCheckoutAction.SKIP
+ same_branch = local.branch == box.head.branch or local.branch == _DETACHED
+ if local.sha == box.head.sha and same_branch:
+ return BoxCheckoutAction.MATCHES
+ if box.dirty:
+ return BoxCheckoutAction.FAIL_DIRTY if requested else BoxCheckoutAction.WARN_DIRTY
+ return BoxCheckoutAction.CHECKOUT
def _detect_local_posthog_checkout() -> Path:
@@ -41,6 +127,93 @@ def _detect_local_posthog_checkout() -> Path:
raise SystemExit(1) # unreachable; helps the type checker see no fall-through
+def _read_local_head(local_path: Path) -> GitHead | None:
+ result = subprocess.run(
+ ["git", "-C", str(local_path), "rev-parse", "HEAD", "--abbrev-ref", "HEAD"],
+ capture_output=True,
+ text=True,
+ )
+ lines = result.stdout.split()
+ if result.returncode != 0 or len(lines) != 2:
+ return None
+ return GitHead(branch=lines[1], sha=lines[0])
+
+
+def _run_box_script(workspace: str, script: str, *args: str) -> subprocess.CompletedProcess[str] | None:
+ try:
+ return run_in_workspace(
+ workspace, ["bash", "-c", script, "hogli-sync", *args], timeout=_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)
+ if result is None or result.returncode != 0:
+ return None
+ lines = result.stdout.split()
+ if len(lines) != 3:
+ return 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:
+ """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
+ tracked file that differs between the two checkouts becomes a conflict.
+ Matching the box's HEAD to the local HEAD first leaves only local
+ uncommitted edits to differ. Any failure here falls back to the previous
+ behavior (mirror over the box's current checkout) unless the user passed
+ ``--checkout-branch``.
+ """
+ if requested is False:
+ return
+
+ def give_up(message: str) -> None:
+ if requested:
+ _fail(f"{message}\nRun without --checkout-branch to sync anyway.")
+ click.echo(click.style(f"{message}\nFiles that differ will show as sync conflicts.", fg="yellow"))
+
+ local = _read_local_head(local_path)
+ 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)
+ if box is None:
+ give_up("Couldn't read the devbox's git state, so its checkout was left as is.")
+ return
+
+ action = decide_box_checkout(local, box, requested)
+ if action is BoxCheckoutAction.MATCHES:
+ return
+ if action in (BoxCheckoutAction.WARN_DIRTY, BoxCheckoutAction.FAIL_DIRTY):
+ give_up(
+ f"The devbox has uncommitted changes on {box.head.describe()}, so hogli didn't switch it to "
+ f"{local.describe()}. Commit or discard them on the devbox before the next sync to let hogli switch it."
+ )
+ 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)
+ returncode = None if result is None else result.returncode
+ if returncode == 0:
+ click.echo("Devbox checkout matches local.")
+ return
+ if returncode == _CHECKOUT_SHA_UNAVAILABLE:
+ give_up(f"The devbox couldn't fetch {local.sha[:10]} from origin. Push the branch to avoid this.")
+ elif returncode == _CHECKOUT_BRANCH_DIVERGED:
+ give_up(f"The devbox has commits on `{local.branch}` that your local branch doesn't, so hogli left it alone.")
+ elif returncode == _CHECKOUT_DETACHED_UNSAVED:
+ give_up("The devbox has commits on a detached HEAD that no branch holds, so hogli left it alone.")
+ elif returncode == _CHECKOUT_DIRTY:
+ give_up("The devbox got uncommitted changes before the checkout, so hogli left it alone.")
+ else:
+ stderr = "" if result is None else result.stderr.strip()
+ give_up(f"Checking out {local.describe()} on the devbox failed. {stderr}".strip())
+
+
def _ensure_ssh_config_for_workspace(workspace: str) -> None:
"""Ensure ``ssh coder.{workspace}`` resolves before mutagen tries to dial it.
@@ -133,6 +306,16 @@ def _session_summary(session: dict[str, Any]) -> dict[str, Any]:
@click.option("--resume", is_flag=True, help="Resume a paused sync session")
@click.option("--terminate", is_flag=True, help="Tear down the sync session")
@click.option("--flush", is_flag=True, help="Force a flush of pending changes")
+ "--checkout-branch/--no-checkout-branch",
+ "checkout_branch",
+ default=None,
+ help=(
+ "Before creating the sync, check out your local branch and commit on the devbox so the first sync "
+ "has no branch conflicts. By default this happens only when the devbox has no uncommitted changes; "
+ "--checkout-branch fails instead of skipping, --no-checkout-branch never touches the devbox checkout."
+ ),
+)
@click.option("-v", "--verbose", is_flag=True, help="Show full install output")
def cmd_sync(
workspace: str | None,
@@ -142,6 +325,7 @@ def cmd_sync(
resume: bool,
terminate: bool,
flush: bool,
+ checkout_branch: bool | None,
verbose: bool,
) -> None:
"""Create or manage a one-way-safe mutagen sync session for a devbox.
@@ -193,20 +377,43 @@ def cmd_sync(
# 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.ensure_daemon_with_shim()
- if mutagen.sync_list(label_selector=label):
+ ensure_sync_session(name, workspaces, None, checkout_branch=checkout_branch, verbose=verbose)
+
+
+def ensure_sync_session(
+ name: str,
+ workspaces: list[dict[str, Any]] | None,
+ local_path: Path | None,
+ *,
+ checkout_branch: bool | None = None,
+ verbose: bool = False,
+) -> None:
+ if sync_session_exists(name, verbose=verbose):
click.echo(
f"Sync already running for {name}. Use `hogli devbox:sync{_workspace_arg_suffix(name)} --status` to inspect."
)
return
ensure_runtime_ready()
+ create_sync_session(name, workspaces, local_path or _detect_local_posthog_checkout(), checkout_branch)
+ 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 sync_session_exists(name: str, *, verbose: bool = False) -> bool:
+ mutagen.ensure_mutagen_installed(verbose=verbose)
+ mutagen.ensure_daemon_with_shim()
+ return bool(mutagen.sync_list(label_selector=mutagen.workspace_label_selector(name)))
+
+
+def create_sync_session(
+ name: str, workspaces: list[dict[str, Any]] | None, local_path: Path, checkout_branch: bool | None = None
+) -> None:
_ensure_workspace_running(name, workspaces)
_ensure_ssh_config_for_workspace(name)
config_path = mutagen.ensure_user_mutagen_config()
- local_path = _detect_local_posthog_checkout()
+ _align_box_checkout(name, local_path, checkout_branch)
click.echo(f"Creating sync: {local_path} -> coder.{name}:{_REMOTE_REPO_PATH}")
mutagen.sync_create(
name=f"ph-{name}",
@@ -215,8 +422,6 @@ def cmd_sync(
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:
diff --git a/tools/hogli-commands/hogli_commands/devbox/worktree.py b/tools/hogli-commands/hogli_commands/devbox/worktree.py
new file mode 100644
index 000000000000..1d2e4fffe667
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/devbox/worktree.py
@@ -0,0 +1,368 @@
+"""`hogli devbox:worktree` gives a local git worktree its own labeled devbox and sync mirror."""
+
+from __future__ import annotations
+
+import re
+import sys
+import hashlib
+import subprocess
+import urllib.parse
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import click
+
+from ..worktrees import worktree_source
+from . import mutagen
+from .cli import _preferred_region, devbox_clone, devbox_start, resolve_workspace_name
+from .coder import (
+ REGION_NAME_SUFFIXES,
+ _fail,
+ ensure_runtime_ready,
+ extract_workspace_label,
+ fetch_user_workspaces,
+ get_coder_url,
+ get_username,
+ get_workspace,
+ get_workspace_name,
+ get_workspace_status,
+ region_from_workspace_name,
+)
+from .config import (
+ WORKTREE_AUTO_SOURCES,
+ WORKTREE_BOX_CLEANUP_ACTIONS,
+ WorktreeBoxRecord,
+ claim_worktree_box,
+ clear_worktree_auto_sources,
+ clear_worktree_box_cleanup,
+ ensure_worktree_id,
+ load_worktree_boxes,
+ record_worktree_box,
+ save_worktree_auto_sources,
+ save_worktree_box_cleanup,
+ saved_worktree_auto_sources,
+ worktree_box_claimant,
+)
+from .sync import _REMOTE_REPO_PATH, _detect_local_posthog_checkout, ensure_sync_session
+
+CODER_NAME_MAX_LENGTH = 32
+_HASH_LENGTH = 4
+_BRANCH_PREFIXES_TO_DROP = ("worktree-",)
+_RESERVED_SUFFIXES = tuple(suffix for suffix in REGION_NAME_SUFFIXES.values() if suffix)
+_AUTO_OFF = "off"
+_AUTO_LOG_NAME = "hogli-devbox-worktree.log"
+_SUBAGENT_WORKTREE_PREFIX = "agent-"
+
+
+def label_budget(username: str, region: str) -> int:
+ region_suffix = REGION_NAME_SUFFIXES.get(region, "")
+ used = len(f"devbox-{username}-") + (len(region_suffix) + 1 if region_suffix else 0)
+ return CODER_NAME_MAX_LENGTH - used
+
+
+def derive_label(branch: str, max_length: int) -> str:
+ """Turn a branch name into a devbox label that fits Coder's 32-character workspace name limit.
+
+ A label that had to be shortened or repaired gets a hash of the full branch
+ name, so two long branches with a shared prefix still map to different boxes.
+ """
+ if max_length < _HASH_LENGTH:
+ _fail(
+ f"Your Coder username leaves room for only {max(max_length, 0)} label characters. "
+ "Pass `--label <label>` with a short label instead."
+ )
+ slug = branch.lower()
+ for prefix in _BRANCH_PREFIXES_TO_DROP:
+ if slug.startswith(prefix) and len(slug) > len(prefix):
+ slug = slug[len(prefix) :]
+ slug = re.sub(r"[^a-z0-9]+", "-", slug).strip("-")
+ reserved = any(slug == suffix or slug.endswith(f"-{suffix}") for suffix in _RESERVED_SUFFIXES)
+ if slug and len(slug) <= max_length and not reserved:
+ return slug
+
+ digest = hashlib.sha256(branch.encode()).hexdigest()[:_HASH_LENGTH]
+ stem_length = max_length - _HASH_LENGTH - 1
+ stem = slug[:stem_length].rstrip("-") if stem_length > 0 else ""
+ return f"{stem}-{digest}" if stem else digest
+
+
+def _is_linked_worktree(root: Path) -> bool:
+ return (root / ".git").is_file()
+
+
+def _current_branch(root: Path) -> str:
+ 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
+
+
+def parse_auto_sources(value: str) -> tuple[str, ...]:
+ if value.strip() == _AUTO_OFF:
+ return ()
+ sources = tuple(dict.fromkeys(source.strip() for source in value.split(",") if source.strip()))
+ unknown = [source for source in sources if source not in WORKTREE_AUTO_SOURCES]
+ if unknown or not sources:
+ raise click.BadParameter(
+ f"Use a comma-separated list of {', '.join(WORKTREE_AUTO_SOURCES)}, or '{_AUTO_OFF}'.",
+ param_hint="--auto",
+ )
+ return sources
+
+
+def should_auto_provision(root: Path, source: str, enabled: frozenset[str]) -> bool:
+ # A Claude subagent worktree lives for one task, and a fan-out would create one box per agent.
+ if source == "claude" and root.name.startswith(_SUBAGENT_WORKTREE_PREFIX):
+ return False
+ return source in enabled
+
+
+def _save_auto_sources(value: str) -> None:
+ sources = parse_auto_sources(value)
+ if not sources:
+ clear_worktree_auto_sources()
+ click.echo("Turned off automatic worktree boxes.")
+ return
+ save_worktree_auto_sources(sources)
+ click.echo(
+ f"New worktrees from {', '.join(sources)} now get their own devbox. "
+ "The husky post-checkout hook starts `hogli devbox:worktree` in the background when one is created."
+ )
+
+
+def _git_dir(root: Path) -> Path:
+ result = subprocess.run(
+ ["git", "rev-parse", "--absolute-git-dir"], cwd=root, capture_output=True, text=True, check=True
+ )
+ return Path(result.stdout.strip())
+
+
+def _app_url(workspace_name: str) -> str:
+ host = urllib.parse.urlparse(get_coder_url()).hostname or ""
+ return f"https://app--{workspace_name}--{get_username()}.{host}"
+
+
+@dataclass(frozen=True)
+class _WorktreeTarget:
+ workspace_name: str
+ label: str
+
+
+def _resolve_target(
+ root: Path,
+ label: str | None,
+ cloning: bool,
+ clone_source: str | None,
+ workspaces: list[dict[str, Any]],
+) -> _WorktreeTarget:
+ """Return the devbox this worktree uses.
+
+ A worktree that already has a registered box keeps it, even after a branch
+ rename, so a re-run never creates a second box. A record saved for an
+ earlier worktree at the same path does not count.
+ """
+ boxes = load_worktree_boxes()
+ 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
+ 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
+ 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`.")
+
+ 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."
+ )
+ existing = get_workspace(name, workspaces)
+ owner = worktree_box_claimant(boxes, root, name, existing)
+ if owner is not None:
+ _fail(f"Devbox '{name}' belongs to the worktree at {owner}. Pick another `--label`.")
+ if label is None and registered is None and existing is not None:
+ _fail(
+ 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)
+
+
+def _list_workspaces_or_fail() -> list[dict[str, Any]]:
+ workspaces = fetch_user_workspaces()
+ if workspaces is None:
+ _fail(
+ "Couldn't list your devboxes, so hogli can't tell which one belongs to this worktree. "
+ "Run `hogli devbox:doctor`."
+ )
+ raise SystemExit(1) # unreachable; helps the type checker see no fall-through
+ return workspaces
+
+
[email protected](name="devbox:worktree", help="Give this worktree its own devbox and sync mirror")
[email protected]("--label", default=None, help="Devbox label to use instead of one derived from the branch name")
+ "--clone-from",
+ default=None,
+ metavar="LABEL",
+ help="Create the box as a clone of this running devbox (see devbox:clone). Use 'default' for your default box.",
+)
+ "--start-app/--no-start-app",
+ "start_app",
+ default=None,
+ help="Bring the PostHog app up on every start. Applies only when the box is created.",
+)
+ "--on-clean",
+ type=click.Choice([*WORKTREE_BOX_CLEANUP_ACTIONS, "keep"]),
+ default=None,
+ help="Save what `hogli worktrees:clean` does with a worktree's devbox when it removes the worktree.",
+)
+ "--auto",
+ "auto_sources",
+ default=None,
+ metavar="SOURCES",
+ help=(
+ "Save which new worktrees get a devbox automatically, as a comma-separated list of "
+ f"{', '.join(WORKTREE_AUTO_SOURCES)}. 'off' turns it off. Only saves the setting."
+ ),
+)
[email protected]("--dry-run", is_flag=True, help="Print the plan without changing anything")
[email protected]("-y", "--yes", is_flag=True, help="Skip the clone confirmation prompt")
[email protected]("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")
+def devbox_worktree(
+ ctx: click.Context,
+ label: str | None,
+ clone_from: str | None,
+ start_app: bool | None,
+ on_clean: str | None,
+ auto_sources: str | None,
+ dry_run: bool,
+ yes: bool,
+ verbose: bool,
+) -> None:
+ if auto_sources is not None:
+ _save_auto_sources(auto_sources)
+ return
+
+ root = _detect_local_posthog_checkout()
+ if not _is_linked_worktree(root):
+ _fail(
+ f"{root} is the main checkout, not a linked worktree. "
+ "Use `hogli devbox:start` and `hogli devbox:sync` for it."
+ )
+
+ 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)
+ existing = get_workspace(target.workspace_name, workspaces)
+ has_sync = bool(mutagen.sync_list(label_selector=mutagen.workspace_label_selector(target.workspace_name)))
+
+ if existing is None:
+ box_step = (
+ f"Clone '{clone_from}' into '{target.workspace_name}'" if cloning else f"Create '{target.workspace_name}'"
+ )
+ elif get_workspace_status(existing) == "running":
+ box_step = f"Use running devbox '{target.workspace_name}'"
+ else:
+ box_step = f"Start devbox '{target.workspace_name}' ({get_workspace_status(existing)})"
+ sync_step = (
+ "Keep the existing sync mirror"
+ if has_sync
+ else f"Mirror {root} to coder.{target.workspace_name}:{_REMOTE_REPO_PATH}"
+ )
+
+ click.echo(f"Worktree: {root}")
+ click.echo(f" 1. {box_step}")
+ click.echo(f" 2. {sync_step}")
+ if on_clean is not None:
+ click.echo(f" 3. Save worktrees:clean devbox action: {on_clean}")
+ if dry_run:
+ click.echo("[DRY-RUN] Nothing changed.")
+ return
+
+ git_dir = _git_dir(root)
+ worktree_id = ensure_worktree_id(git_dir)
+ owner = claim_worktree_box(
+ root,
+ WorktreeBoxRecord(
+ workspace=target.workspace_name,
+ git_dir=str(git_dir),
+ workspace_id=None if existing is None else existing.get("id"),
+ worktree_id=worktree_id,
+ ),
+ existing,
+ )
+ if owner is not None:
+ _fail(f"Devbox '{target.workspace_name}' belongs to the worktree at {owner}. Pick another `--label`.")
+ if on_clean == "keep":
+ clear_worktree_box_cleanup()
+ elif on_clean is not None:
+ save_worktree_box_cleanup(on_clean)
+
+ 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)}")
+
+
+ name="devbox:worktree:auto",
+ help="Start devbox:worktree in the background for this new worktree, if `devbox:worktree --auto` covers it",
+)
+def devbox_worktree_auto() -> None:
+ enabled = saved_worktree_auto_sources()
+ if not enabled:
+ return
+ root = _detect_local_posthog_checkout()
+ if not _is_linked_worktree(root) or not should_auto_provision(root, worktree_source(root), enabled):
+ return
+
+ log_path = _git_dir(root) / _AUTO_LOG_NAME
+ with log_path.open("ab") as log:
+ subprocess.Popen(
+ # -P keeps the worktree off sys.path, so a `hogli` package committed to the
+ # branch being checked out cannot shadow the installed one and run here.
+ [sys.executable, "-P", "-m", "hogli", "devbox:worktree", "--yes"],
+ cwd=root,
+ stdin=subprocess.DEVNULL,
+ stdout=log,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ click.echo(f"hogli: creating a devbox for this worktree in the background. Log: {log_path}")
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
index 6e0334af7d2e..3f291bb93139 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
@@ -23,11 +23,32 @@ from hogli_commands.devbox import (
config as devbox_config,
mutagen as devbox_mutagen,
sync as devbox_sync,
+ worktree as devbox_worktree,
)
runner = CliRunner()
+def _git(repo: Path, *args: str) -> str:
+ return subprocess.run(
+ [
+ "git",
+ "-C",
+ str(repo),
+ "-c",
+ "user.name=t",
+ "-c",
+ "-c",
+ "commit.gpgsign=false",
+ *args,
+ ],
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+
+
@pytest.fixture(autouse=True)
def agent_ready_immediately(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(devbox_cli, "wait_for_agent_ready", lambda name: "ready")
@@ -870,6 +891,204 @@ class TestWorkspaceNaming:
assert coder.resolve_shared_workspace_name(user, label) == expected
+class TestWorktreeLabel:
+ @pytest.mark.parametrize(
+ "username, region, expected",
+ [
+ ("test-user", "us-east-1", 15),
+ ("test-user", "eu-central-1", 12),
+ ("fifteen-chars-x", "us-east-1", 9),
+ ],
+ ids=["short-user-us", "short-user-eu", "long-user-us"],
+ )
+ def test_budget_fills_coder_name_limit(self, username: str, region: str, expected: int) -> None:
+ assert devbox_worktree.label_budget(username, region) == expected
+
+ @pytest.mark.parametrize(
+ "branch, expected",
+ [
+ ("feat/session-replay", "feat-session-replay"),
+ ("Fix_Cohort__Query", "fix-cohort-query"),
+ ("worktree-agent-abc", "agent-abc"),
+ ],
+ ids=["slash", "case-and-underscores", "claude-worktree-prefix"],
+ )
+ def test_short_branch_becomes_readable_label(self, branch: str, expected: str) -> None:
+ assert devbox_worktree.derive_label(branch, 20) == expected
+
+ @pytest.mark.parametrize(
+ "branch, budget",
+ [
+ ("worktree-agent-afae8d7b61efe10c8", 9),
+ ("feat/a-very-long-branch-name-about-replay", 15),
+ ("fix-eu", 12),
+ ("///", 12),
+ ("release/2026-10", 4),
+ ],
+ ids=["truncated", "truncated-wider", "region-suffix", "no-alphanumerics", "hash-only-budget"],
+ )
+ def test_repaired_label_is_a_valid_workspace_name(
+ self, monkeypatch: pytest.MonkeyPatch, branch: str, budget: int
+ ) -> None:
+ monkeypatch.setattr(coder, "get_username", lambda: "test-user")
+ label = devbox_worktree.derive_label(branch, budget)
+
+ assert len(label) <= budget
+ name = coder.get_workspace_name(label, region="eu-central-1")
+ assert coder.extract_workspace_label(name) == label
+
+ def test_truncated_branches_with_shared_prefix_get_different_labels(self) -> None:
+ first = devbox_worktree.derive_label("feat/session-replay-export", 9)
+ second = devbox_worktree.derive_label("feat/session-replay-import", 9)
+ assert first != second
+ assert devbox_worktree.derive_label("feat/session-replay-export", 9) == first
+
+ def test_budget_too_small_for_hash_fails(self) -> None:
+ with pytest.raises(SystemExit):
+ devbox_worktree.derive_label("feat/x", 3)
+
+
+class TestWorktreeAutoProvision:
+ @pytest.mark.parametrize(
+ "worktree_name, source, enabled, expected",
+ [
+ ("zesty-gliding-bunny", "claude", {"claude"}, True),
+ ("agent-afae8d7b", "claude", {"claude"}, False),
+ ("agent-afae8d7b", "phw", {"phw"}, True),
+ ("feat-x", "codex", {"claude", "phw"}, False),
+ ("feat-x", "other", {"other"}, True),
+ ],
+ ids=["claude-session", "claude-subagent", "phw-named-agent", "source-not-enabled", "plain-git-worktree"],
+ )
+ def test_only_enabled_sources_get_a_box_and_never_subagents(
+ self, worktree_name: str, source: str, enabled: set[str], expected: bool
+ ) -> None:
+ root = Path("/work") / worktree_name
+ assert devbox_worktree.should_auto_provision(root, source, frozenset(enabled)) is expected
+
+
+class TestDevboxWorktreeCommand:
+ @pytest.fixture
+ def worktree_root(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ root = tmp_path / "wt"
+ root.mkdir()
+ (root / ".git").write_text("gitdir: elsewhere\n")
+ (root / "admin").mkdir()
+ monkeypatch.setattr(devbox_config, "get_worktree_boxes_path", lambda: tmp_path / "boxes.json")
+ monkeypatch.setattr(coder, "get_username", lambda: "test-user")
+ monkeypatch.setattr(devbox_worktree, "get_username", lambda: "test-user")
+ monkeypatch.setattr(devbox_worktree, "get_coder_url", lambda: "https://coder.example.com")
+ monkeypatch.setattr(devbox_worktree, "_detect_local_posthog_checkout", lambda: root)
+ monkeypatch.setattr(devbox_worktree, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_worktree, "_preferred_region", lambda: "us-east-1")
+ monkeypatch.setattr(devbox_worktree.mutagen, "sync_list", lambda label_selector=None: [])
+ monkeypatch.setattr(devbox_worktree, "_git_dir", lambda root: root / "admin")
+ return root
+
+ @pytest.mark.parametrize(
+ "label, existing, expected_exit, expected_box",
+ [
+ pytest.param(
+ None,
+ ["devbox-test-user-feat-eu", "devbox-test-user-feat"],
+ 0,
+ "devbox-test-user-feat-eu",
+ id="registered-box-wins-over-same-label-in-preferred-region",
+ ),
+ pytest.param(
+ "feat",
+ ["devbox-test-user-feat-eu", "devbox-test-user-feat"],
+ 0,
+ "devbox-test-user-feat-eu",
+ id="registered-label-passed-explicitly",
+ ),
+ pytest.param(
+ "other",
+ ["devbox-test-user-feat-eu"],
+ 1,
+ "devbox-test-user-feat-eu",
+ id="new-label-refused-while-registered-box-exists",
+ ),
+ pytest.param("other", [], 0, "devbox-test-user-other", id="new-label-allowed-once-registered-box-is-gone"),
+ pytest.param(
+ "shared",
+ ["devbox-test-user-shared"],
+ 1,
+ "devbox-test-user-feat-eu",
+ id="label-of-another-worktrees-box-refused",
+ ),
+ pytest.param(None, None, 1, "devbox-test-user-feat-eu", id="listing-failure-refused"),
+ ],
+ )
+ def test_keeps_the_registered_box_through_start_and_sync(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ worktree_root: Path,
+ label: str | None,
+ existing: list[str] | None,
+ expected_exit: int,
+ expected_box: str,
+ ) -> None:
+ workspaces = (
+ None
+ if existing is None
+ else [{"name": name, "id": f"id-{name}", "latest_build": {"status": "running"}} for name in existing]
+ )
+ monkeypatch.setattr(devbox_worktree, "fetch_user_workspaces", lambda: workspaces)
+ monkeypatch.setattr(devbox_cli, "list_user_workspaces", lambda: workspaces or [])
+ devbox_config.record_worktree_box(
+ worktree_root,
+ devbox_config.WorktreeBoxRecord(
+ workspace="devbox-test-user-feat-eu", git_dir="admin", workspace_id="id-devbox-test-user-feat-eu"
+ ),
+ )
+ devbox_config.record_worktree_box(
+ worktree_root.parent / "other-worktree",
+ devbox_config.WorktreeBoxRecord(
+ workspace="devbox-test-user-shared", git_dir="admin", workspace_id="id-devbox-test-user-shared"
+ ),
+ )
+ started: list[str] = []
+ synced: list[str] = []
+
+ def fake_start(workspace: str, region: str, verbose: bool, start_app: bool | None = None) -> None:
+ started.append(devbox_cli.resolve_workspace_name(workspace, region=region)[0])
+
+ monkeypatch.setattr(devbox_worktree, "devbox_start", fake_start)
+ monkeypatch.setattr(devbox_worktree, "ensure_sync_session", lambda name, *a, **kw: synced.append(name))
+
+ result = runner.invoke(cli, ["devbox:worktree", *(["--label", label] if label else [])])
+
+ assert result.exit_code == expected_exit, result.output
+ expected_calls = [expected_box] if expected_exit == 0 else []
+ assert (started, synced) == (expected_calls, expected_calls)
+ assert devbox_config.load_worktree_boxes()[str(worktree_root)].workspace == expected_box
+
+ @pytest.mark.parametrize("box_exists", [False, True], ids=["before-the-box-exists", "while-the-box-is-set-up"])
+ def test_label_claimed_by_another_worktree_is_refused(
+ self, monkeypatch: pytest.MonkeyPatch, worktree_root: Path, box_exists: bool
+ ) -> None:
+ other = worktree_root.parent / "other-worktree"
+ other.mkdir()
+ devbox_config.record_worktree_box(
+ other, devbox_config.WorktreeBoxRecord(workspace="devbox-test-user-shared", git_dir="admin")
+ )
+ workspaces = (
+ [{"name": "devbox-test-user-shared", "id": "id-shared", "latest_build": {"status": "running"}}]
+ if box_exists
+ else []
+ )
+ monkeypatch.setattr(devbox_worktree, "fetch_user_workspaces", lambda: workspaces)
+ monkeypatch.setattr(devbox_cli, "list_user_workspaces", lambda: workspaces)
+ monkeypatch.setattr(devbox_worktree, "devbox_start", lambda **kwargs: pytest.fail("started a claimed box"))
+
+ result = runner.invoke(cli, ["devbox:worktree", "--label", "shared"])
+
+ assert result.exit_code == 1, result.output
+ assert str(other) in result.output
+ assert str(worktree_root) not in devbox_config.load_worktree_boxes()
+
+
class TestWorkspaceRegion:
"""Reading the region back from the workspace `region` metadata item."""
@@ -4331,6 +4550,7 @@ class TestDevboxSyncCommand:
checkout = tmp_path / "posthog"
checkout.mkdir()
monkeypatch.setattr(devbox_sync, "_detect_local_posthog_checkout", lambda: checkout)
+ monkeypatch.setattr(devbox_sync, "_align_box_checkout", lambda name, path, requested: None)
captured: dict[str, object] = {}
monkeypatch.setattr(
@@ -4347,6 +4567,60 @@ class TestDevboxSyncCommand:
assert captured["dst"] == "coder.devbox-test-user:/home/coder/posthog"
assert captured["labels"] == {"hogli-workspace": "devbox-test-user"}
+ @pytest.mark.parametrize(
+ "box_head, box_dirty, flag, expect_checkout, expect_created",
+ [
+ pytest.param("master abc", False, [], True, True, id="clean_box_on_master_is_switched"),
+ pytest.param("feat/x local", False, [], False, True, id="matching_box_is_left_alone"),
+ pytest.param("master abc", True, [], False, True, id="dirty_box_is_left_alone_and_synced"),
+ pytest.param("master abc", True, ["--checkout-branch"], False, False, id="dirty_box_fails_when_forced"),
+ pytest.param("master abc", False, ["--no-checkout-branch"], False, True, id="opt_out_skips_box"),
+ ],
+ )
+ def test_default_run_aligns_box_branch_before_first_mirror(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ box_head: str,
+ box_dirty: bool,
+ flag: list[str],
+ expect_checkout: bool,
+ expect_created: bool,
+ ) -> None:
+ monkeypatch.setattr(devbox_sync, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ 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, "ensure_daemon_with_shim", lambda: None)
+ monkeypatch.setattr(devbox_sync, "_ensure_ssh_config_for_workspace", lambda ws: None)
+ monkeypatch.setattr(devbox_sync.mutagen, "ensure_user_mutagen_config", lambda: tmp_path / "mutagen.yml")
+ monkeypatch.setattr(devbox_sync.mutagen, "sync_list", lambda label_selector=None: [])
+ monkeypatch.setattr(devbox_sync, "_detect_local_posthog_checkout", lambda: tmp_path)
+ monkeypatch.setattr(
+ devbox_sync, "_read_local_head", lambda path: devbox_sync.GitHead(branch="feat/x", sha="local")
+ )
+ created: list[str] = []
+ monkeypatch.setattr(devbox_sync.mutagen, "sync_create", lambda **kw: created.append(kw["name"]))
+
+ remote_calls: list[list[str]] = []
+
+ def fake_run_in_workspace(name: str, command: list[str], *, timeout: float) -> subprocess.CompletedProcess[str]:
+ remote_calls.append(command)
+ is_probe = command[2] == devbox_sync._PROBE_BOX_HEAD_SCRIPT
+ stdout = f"{box_head} {int(box_dirty)}\n" if is_probe else ""
+ return subprocess.CompletedProcess(command, 0, stdout=stdout, stderr="")
+
+ monkeypatch.setattr(devbox_sync, "run_in_workspace", fake_run_in_workspace)
+
+ result = runner.invoke(cli, ["devbox:sync", *flag])
+
+ checkouts = [c for c in remote_calls if c[2] == devbox_sync._CHECKOUT_SCRIPT]
+ assert checkouts == (
+ [["bash", "-c", devbox_sync._CHECKOUT_SCRIPT, "hogli-sync", "feat/x", "local"]] if expect_checkout else []
+ )
+ assert (result.exit_code == 0) is expect_created, result.output
+ assert created == (["ph-devbox-test-user"] if expect_created else [])
+
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.
@@ -4385,6 +4659,80 @@ class TestDevboxSyncCommand:
monkeypatch.chdir(checkout / "subdir")
assert devbox_sync._detect_local_posthog_checkout() == checkout.resolve()
+ @pytest.mark.parametrize("detach, expected_branch", [(False, "feat/x"), (True, "HEAD")], ids=["branch", "detached"])
+ def test_read_local_head_returns_branch_and_full_sha(
+ self, tmp_path: Path, detach: bool, expected_branch: str
+ ) -> None:
+ _git(tmp_path, "init", "--quiet", "--initial-branch=feat/x")
+ _git(tmp_path, "commit", "--quiet", "--allow-empty", "-m", "init")
+ sha = _git(tmp_path, "rev-parse", "HEAD")
+ if detach:
+ _git(tmp_path, "checkout", "--quiet", "--detach")
+
+ assert devbox_sync._read_local_head(tmp_path) == devbox_sync.GitHead(branch=expected_branch, sha=sha)
+
+ @pytest.mark.parametrize(
+ "box_state, expected_exit, box_keeps_head",
+ [
+ ("detached-on-master", 0, False),
+ ("detached-with-unsaved-commit", devbox_sync._CHECKOUT_DETACHED_UNSAVED, True),
+ ("ignored-file-tracked-on-target", None, True),
+ ],
+ ids=["reachable-detached-head-is-switched", "unsaved-detached-commit-kept", "ignored-file-kept"],
+ )
+ def test_checkout_script_never_drops_box_work(
+ self, tmp_path: Path, box_state: str, expected_exit: int | None, box_keeps_head: bool
+ ) -> None:
+ _git(tmp_path, "init", "--quiet", "--initial-branch=master")
+ (tmp_path / ".gitignore").write_text(".env.local\n")
+ _git(tmp_path, "add", ".gitignore")
+ _git(tmp_path, "commit", "--quiet", "-m", "init")
+ _git(tmp_path, "checkout", "--quiet", "-b", "feat/x")
+ if box_state == "ignored-file-tracked-on-target":
+ (tmp_path / ".env.local").write_text("from branch\n")
+ _git(tmp_path, "add", "--force", ".env.local")
+ _git(tmp_path, "commit", "--quiet", "--allow-empty", "-m", "target")
+ target = _git(tmp_path, "rev-parse", "HEAD")
+ (tmp_path / ".env.local").unlink(missing_ok=True)
+ _git(tmp_path, "checkout", "--quiet", "--detach", "master")
+ if box_state == "detached-with-unsaved-commit":
+ _git(tmp_path, "commit", "--quiet", "--allow-empty", "-m", "box only")
+ (tmp_path / ".env.local").write_text("box secret\n")
+ box_head = _git(tmp_path, "rev-parse", "HEAD")
+
+ script = devbox_sync._CHECKOUT_SCRIPT.replace(devbox_sync._REMOTE_REPO_PATH, str(tmp_path))
+ result = subprocess.run(["bash", "-c", script, "hogli-sync", "feat/x", target], capture_output=True, text=True)
+
+ if expected_exit is None:
+ assert result.returncode != 0
+ else:
+ assert result.returncode == expected_exit, result.stderr
+ assert _git(tmp_path, "rev-parse", "HEAD") == (box_head if box_keeps_head else target)
+ assert (tmp_path / ".env.local").read_text() == "box secret\n"
+
+ def test_checkout_script_runs_no_box_hook_while_fetching(self, tmp_path: Path) -> None:
+ origin, box = tmp_path / "origin", tmp_path / "box"
+ _git(tmp_path, "init", "--quiet", "--initial-branch=master", str(origin))
+ _git(origin, "commit", "--quiet", "--allow-empty", "-m", "init")
+ _git(tmp_path, "clone", "--quiet", str(origin), str(box))
+ _git(origin, "checkout", "--quiet", "-b", "feat/x")
+ _git(origin, "commit", "--quiet", "--allow-empty", "-m", "target")
+ target = _git(origin, "rev-parse", "HEAD")
+ marker = tmp_path / "hook-ran"
+ for hook in ("reference-transaction", "post-checkout"):
+ hook_path = box / ".hooks" / hook
+ hook_path.parent.mkdir(exist_ok=True)
+ hook_path.write_text(f"#!/bin/sh\ntouch {marker}\n")
+ hook_path.chmod(0o755)
+ _git(box, "config", "core.hooksPath", ".hooks")
+
+ script = devbox_sync._CHECKOUT_SCRIPT.replace(devbox_sync._REMOTE_REPO_PATH, str(box))
+ result = subprocess.run(["bash", "-c", script, "hogli-sync", "feat/x", target], capture_output=True, text=True)
+
+ assert result.returncode == 0, result.stderr
+ assert _git(box, "rev-parse", "HEAD") == target
+ assert not marker.exists()
+
def test_detect_local_checkout_fails_outside_repo(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
monkeypatch.chdir(tmp_path)
with pytest.raises(SystemExit):
diff --git a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py b/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
index 6d6e58d39e8a..b65641d04b37 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
@@ -2,14 +2,20 @@ from __future__ import annotations
import math
import subprocess
+from datetime import UTC, datetime
from pathlib import Path
import pytest
import click
+from hogli_commands import worktrees
+from hogli_commands.devbox import config as devbox_config
from hogli_commands.worktrees import (
Worktree,
+ WorktreeBox,
_belongs_to_repo,
+ _boxes_of_removed_worktrees,
+ _clean_worktree_boxes,
_collect_deps_items,
_compute_git_state,
_discover_root_worktrees,
@@ -17,14 +23,24 @@ from hogli_commands.worktrees import (
_execute,
_include_orphans,
_is_under,
+ _match_worktree_boxes,
_parse_cutoff,
_reclaimed_bytes,
_registered_worktrees,
+ _resolve_box_action,
_resolve_orphan_policy,
_worktree_roots,
)
+def _box(
+ name: str, git_dir: Path | str = "admin", workspace_id: str | None = None, worktree_id: str | None = None
+) -> devbox_config.WorktreeBoxRecord:
+ return devbox_config.WorktreeBoxRecord(
+ workspace=name, git_dir=str(git_dir), workspace_id=workspace_id, worktree_id=worktree_id
+ )
+
+
def _make_worktree(path: Path) -> Worktree:
return Worktree(source="claude", path=path, registered=True, locked=False, branch="", last_activity=0.0)
@@ -308,6 +324,195 @@ class TestOrphanPolicy:
assert _include_orphans("ask", [_make_worktree(tmp_path)], dry_run=dry_run, yes=yes) is True
+class TestResolveBoxAction:
+ @pytest.mark.parametrize(
+ ("flags", "saved", "mode", "expected"),
+ [
+ ((False, False, False), None, "full", None),
+ ((False, False, False), "delete", "full", "delete"),
+ ((True, False, False), "delete", "full", "stop"),
+ ((False, True, False), None, "full", "delete"),
+ ((False, False, True), "stop", "full", None),
+ ((False, False, False), "stop", "deps", None),
+ ],
+ ids=["default-off", "saved-config", "flag-beats-config", "delete-flag", "keep-beats-config", "deps-ignores"],
+ )
+ def test_flags_and_saved_config(self, monkeypatch, flags, saved, mode, expected) -> None:
+ monkeypatch.setattr(worktrees, "saved_worktree_box_cleanup", lambda: saved)
+ assert _resolve_box_action(*flags, mode) == expected
+
+ @pytest.mark.parametrize(
+ ("flags", "mode"),
+ [((True, True, False), "full"), ((True, False, False), "deps")],
+ ids=["two-flags", "deps-mode"],
+ )
+ def test_conflicting_flags_rejected(self, flags, mode) -> None:
+ with pytest.raises(click.UsageError):
+ _resolve_box_action(*flags, mode)
+
+
+class TestWorktreeBoxes:
+ @pytest.fixture
+ def registry_path(self, tmp_path, monkeypatch) -> Path:
+ path = tmp_path / "boxes.json"
+ monkeypatch.setattr(devbox_config, "get_worktree_boxes_path", lambda: path)
+ return path
+
+ @pytest.mark.parametrize(
+ ("case", "matched"),
+ [("same-path", True), ("moved", True), ("recreated-at-same-path", False), ("no-worktree-id-recorded", False)],
+ )
+ def test_matches_a_worktree_only_by_the_id_in_its_admin_directory(self, tmp_path, case, matched) -> None:
+ admin = tmp_path / "repo" / ".git" / "worktrees" / "feature"
+ admin.mkdir(parents=True)
+ registered_path = tmp_path / "old" / "feature"
+ current = tmp_path / "moved" / "feature" if case == "moved" else registered_path
+ current.mkdir(parents=True)
+ (current / ".git").write_text(f"gitdir: {admin}\n")
+ worktree_id = devbox_config.ensure_worktree_id(admin)
+ if case == "recreated-at-same-path":
+ (admin / "hogli-devbox-worktree-id").unlink()
+ record = _box(
+ "devbox-test-user-feature",
+ git_dir=admin,
+ worktree_id=None if case == "no-worktree-id-recorded" else worktree_id,
+ )
+
+ boxes = _match_worktree_boxes([_make_worktree(current)], {str(registered_path): record})
+
+ expected = [WorktreeBox(worktree_path=registered_path, record=record, current_path=current)]
+ assert boxes == (expected if matched else [])
+
+ @pytest.mark.parametrize(
+ ("case", "sources", "pending"),
+ [
+ ("removed", None, True),
+ ("removed", {"claude"}, True),
+ ("removed", {"phw"}, False),
+ ("moved", None, False),
+ ("admin-dir-reused", None, True),
+ ("other-repo", None, False),
+ ],
+ ids=[
+ "removed",
+ "removed-source-selected",
+ "source-not-selected",
+ "moved-or-unmounted",
+ "admin-dir-reused-by-another-worktree",
+ "other-repo",
+ ],
+ )
+ def test_pending_boxes_need_a_removed_worktree_in_the_selected_scope(
+ self, tmp_path, case, sources, pending
+ ) -> None:
+ repo = tmp_path / "repo"
+ common = repo / ".git"
+ other_common = tmp_path / "other" / ".git"
+ (common / "worktrees").mkdir(parents=True)
+ (other_common / "worktrees").mkdir(parents=True)
+ admin = (other_common if case == "other-repo" else common) / "worktrees" / "feature"
+ if case in ("moved", "admin-dir-reused"):
+ admin.mkdir()
+ worktree_id = devbox_config.ensure_worktree_id(admin) if case == "moved" else "id-of-the-removed-worktree"
+ record = _box("devbox-test-user-feature", git_dir=admin, worktree_id=worktree_id)
+ registry = {str(repo / ".claude" / "worktrees" / "feature"): record}
+
+ boxes = _boxes_of_removed_worktrees(registry, repo, common, sources)
+
+ expected = [WorktreeBox(worktree_path=repo / ".claude" / "worktrees" / "feature", record=record)]
+ assert boxes == (expected if pending else [])
+
+ @pytest.mark.parametrize(
+ ("action", "status", "live_id", "last_used_at", "expected_calls"),
+ [
+ ("delete", "running", "id-a", None, [("delete", "devbox-test-user-a")]),
+ ("stop", "running", "id-a", None, [("stop", "devbox-test-user-a")]),
+ ("stop", "stopped", "id-a", None, []),
+ ("delete", "running", "id-recreated", None, []),
+ ("delete", "running", "id-a", "2026-01-01T00:00:00.123456789Z", [("delete", "devbox-test-user-a")]),
+ ("delete", "running", "id-a", "2026-03-01T00:00:00Z", []),
+ ("delete", "running", "id-a", "", []),
+ ],
+ ids=[
+ "delete",
+ "stop-running",
+ "stop-already-stopped",
+ "recreated-box-left-alone",
+ "idle-past-cutoff",
+ "used-after-cutoff-kept",
+ "unknown-last-use-kept",
+ ],
+ )
+ def test_acts_on_existing_box_and_forgets_it(
+ self, tmp_path, monkeypatch, registry_path, action, status, live_id, last_used_at, expected_calls
+ ) -> None:
+ calls: list[tuple[str, str]] = []
+ terminated: list[str] = []
+ monkeypatch.setattr(worktrees, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(
+ worktrees,
+ "fetch_user_workspaces",
+ lambda: [{"name": "devbox-test-user-a", "id": live_id, "status": status, "last_used_at": last_used_at}],
+ )
+ monkeypatch.setattr(worktrees, "get_workspace_status", lambda ws: ws["status"])
+ monkeypatch.setattr(worktrees, "delete_workspace", lambda name: calls.append(("delete", name)))
+ monkeypatch.setattr(worktrees, "stop_workspace", lambda name: calls.append(("stop", name)))
+ monkeypatch.setattr(worktrees.mutagen, "sync_terminate", terminated.append)
+ box_a, box_b = _box("devbox-test-user-a", workspace_id="id-a"), _box("devbox-test-user-b")
+ devbox_config.record_worktree_box(tmp_path / "a", box_a)
+ devbox_config.record_worktree_box(tmp_path / "b", box_b)
+
+ _clean_worktree_boxes(
+ [
+ WorktreeBox(worktree_path=tmp_path / "a", record=box_a),
+ WorktreeBox(worktree_path=tmp_path / "b", record=box_b),
+ ],
+ action,
+ **({} if last_used_at is None else {"idle_before": datetime(2026, 2, 1, tzinfo=UTC).timestamp()}),
+ )
+
+ assert calls == expected_calls
+ acted = live_id == box_a.workspace_id and (last_used_at is None or bool(expected_calls))
+ assert terminated == ([worktrees.mutagen.workspace_label_selector("devbox-test-user-a")] if acted else [])
+ 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(
+ "listed",
+ [[{"name": "devbox-test-user-a", "id": "id-a"}], None],
+ ids=["delete-fails", "listing-fails"],
+ )
+ def test_failed_box_action_keeps_registry_entry(self, tmp_path, monkeypatch, registry_path, listed) -> None:
+ def fail(name: str) -> None:
+ raise SystemExit(1)
+
+ monkeypatch.setattr(worktrees, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(worktrees, "fetch_user_workspaces", lambda: listed)
+ monkeypatch.setattr(worktrees, "delete_workspace", fail)
+ monkeypatch.setattr(worktrees, "extract_workspace_label", lambda name: "a")
+ monkeypatch.setattr(worktrees.mutagen, "sync_terminate", lambda selector: None)
+ record = _box("devbox-test-user-a", workspace_id="id-a")
+ devbox_config.record_worktree_box(tmp_path / "a", record)
+
+ _clean_worktree_boxes([WorktreeBox(worktree_path=tmp_path / "a", record=record)], "delete")
+
+ assert devbox_config.load_worktree_boxes() == {str(tmp_path / "a"): record}
+
+ def test_box_without_a_workspace_id_is_left_alone(self, tmp_path, monkeypatch, registry_path) -> None:
+ deleted: list[str] = []
+ monkeypatch.setattr(worktrees, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(
+ worktrees, "fetch_user_workspaces", lambda: [{"name": "devbox-test-user-a", "id": "id-recreated"}]
+ )
+ monkeypatch.setattr(worktrees, "delete_workspace", deleted.append)
+ monkeypatch.setattr(worktrees.mutagen, "sync_terminate", lambda selector: None)
+ devbox_config.record_worktree_box(tmp_path / "a", _box("devbox-test-user-a"))
+
+ _clean_worktree_boxes([WorktreeBox(worktree_path=tmp_path / "a", record=_box("devbox-test-user-a"))], "delete")
+
+ assert deleted == []
+
+
class TestReclaimedBytes:
def test_sums_per_device_increase_and_clamps_negatives(self) -> None:
before = {1: 1_000, 2: 5_000}
diff --git a/tools/hogli-commands/hogli_commands/worktrees.py b/tools/hogli-commands/hogli_commands/worktrees.py
index ae998da3ca0d..315d41d3583a 100644
--- a/tools/hogli-commands/hogli_commands/worktrees.py
+++ b/tools/hogli-commands/hogli_commands/worktrees.py
@@ -28,7 +28,7 @@ import re
import time
import shutil
import subprocess
-from collections.abc import Callable, Sequence
+from collections.abc import Callable, Mapping, Sequence
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from datetime import datetime
@@ -37,6 +37,23 @@ from pathlib import Path
import click
from hogli.manifest import REPO_ROOT
+from .devbox import mutagen
+from .devbox.coder import (
+ delete_workspace,
+ ensure_runtime_ready,
+ extract_workspace_label,
+ fetch_user_workspaces,
+ get_workspace,
+ get_workspace_status,
+ stop_workspace,
+)
+from .devbox.config import (
+ WorktreeBoxRecord,
+ forget_worktree_boxes,
+ load_worktree_boxes,
+ read_worktree_id,
+ saved_worktree_box_cleanup,
+)
from .doctor import _format_size
@@ -55,6 +72,18 @@ def _worktree_roots(repo_root: Path) -> list[tuple[str, Path]]:
]
+def worktree_source(path: Path) -> str:
+ """Name the tool whose worktree root holds *path*, or ``other`` for a worktree made elsewhere."""
+ return _source_under(_resolve(path), _resolve_repo(str(path)))
+
+
+def _source_under(resolved_path: Path, repo_root: Path) -> str:
+ for source, root in _worktree_roots(repo_root):
+ if _is_under(resolved_path, root):
+ return source
+ return "other"
+
+
# Dependency/build-artifact directory names removed in --mode deps. Matched at
# any depth and never descended into once matched, so walking stays cheap.
DEPS_RECURSIVE_DIRS = frozenset(
@@ -133,6 +162,28 @@ class Worktree:
return self.dirty or self.unpushed > 0 or self.state_unknown
+@dataclass(frozen=True)
+class WorktreeBox:
+ """A registered devbox paired with the worktree it was set up for.
+
+ ``worktree_path`` is the registry key, which `git worktree move` leaves
+ behind. ``current_path`` carries where the checkout is now, so a move does
+ not hide the box from cleanup or strand its registry entry.
+ """
+
+ worktree_path: Path
+ record: WorktreeBoxRecord
+ current_path: Path | None = None
+
+ @property
+ def workspace(self) -> str:
+ return self.record.workspace
+
+ @property
+ def checkout_path(self) -> Path:
+ return self.current_path or self.worktree_path
+
+
@click.command(
name="worktrees:clean",
help="Clear out unused Claude Code / Codex / PostHog Desktop / phw worktrees by age",
@@ -178,6 +229,22 @@ class Worktree:
"committed work is safe in branch refs). yes=include, no=skip, ask=prompt when any are found. "
"Default: yes for --mode deps, ask for --mode full.",
)
+ "--stop-boxes",
+ is_flag=True,
+ help="In --mode full, also stop the devbox that `hogli devbox:worktree` set up for each removed worktree.",
+)
+ "--delete-boxes",
+ is_flag=True,
+ help="In --mode full, also delete the devbox that `hogli devbox:worktree` set up for each removed worktree, "
+ "including its disk.",
+)
+ "--keep-boxes",
+ is_flag=True,
+ help="Leave devboxes alone, overriding the action saved with `hogli devbox:worktree --on-clean`.",
+)
@click.option("--dry-run", is_flag=True, help="Show what would be removed without deleting.")
@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.")
def worktrees_clean(
@@ -187,6 +254,9 @@ def worktrees_clean(
repo: str | None,
include_dirty: bool,
orphans: str | None,
+ stop_boxes: bool,
+ delete_boxes: bool,
+ keep_boxes: bool,
dry_run: bool,
yes: bool,
) -> None:
@@ -206,12 +276,16 @@ def worktrees_clean(
)
mode = mode.lower()
+ box_action = _resolve_box_action(stop_boxes, delete_boxes, keep_boxes, mode)
orphan_policy = _resolve_orphan_policy(orphans, mode)
repo_root = _resolve_repo(repo)
repo_common = _git_common_dir(repo_root)
cutoff, cutoff_label = _parse_cutoff(before)
selected_sources = {s.lower() for s in sources} if sources else None
+ if box_action:
+ pending = _boxes_of_removed_worktrees(load_worktree_boxes(), repo_root, repo_common, selected_sources)
+ _clean_boxes_of_removed_worktrees(pending, box_action, cutoff, dry_run, yes)
protected = _protected_paths(repo_root)
registry = _registered_worktrees(repo_root)
@@ -298,14 +372,25 @@ def worktrees_clean(
"(cloned/hardlinked deps free less — the actual reclaimed total is measured after deletion)."
)
+ registered_boxes = _match_worktree_boxes(stale, load_worktree_boxes()) if mode == "full" else []
+ boxes = registered_boxes if box_action else []
+ if boxes:
+ click.echo(f"\nWould {box_action} {len(boxes)} devbox(es) set up for these worktrees:")
+ for box in boxes:
+ click.echo(f" {box.workspace} {_display_path(box.checkout_path)}")
+
if dry_run:
click.echo("[DRY-RUN] Nothing deleted.")
return
- if not yes and not click.confirm(f"\nProceed to {action} these {len(stale)} worktree(s)?", default=False):
+ box_prompt = f" and {box_action} {len(boxes)} devbox(es)" if boxes else ""
+ if not yes and not click.confirm(
+ f"\nProceed to {action} these {len(stale)} worktree(s){box_prompt}?", default=False
+ ):
click.echo("Aborted.")
return
+ _stop_worktree_mirrors(registered_boxes)
reclaimed, removed, failed = _execute(stale, mode, repo_root)
if reclaimed >= 0:
summary = f"\n✓ Done. Reclaimed ~{_format_size(reclaimed)} of disk across {removed}/{len(stale)} worktree(s)."
@@ -315,6 +400,176 @@ def worktrees_clean(
summary += f" {failed} could not be fully removed (see warnings above)."
click.echo(summary)
+ removed_boxes = [box for box in registered_boxes if not box.checkout_path.exists()]
+ if box_action and removed_boxes:
+ _clean_worktree_boxes(removed_boxes, box_action)
+ elif removed_boxes:
+ # A box left alone on purpose must not look like a failed cleanup to a later run.
+ forget_worktree_boxes([box.worktree_path for box in removed_boxes])
+ names = " ".join(box.workspace for box in removed_boxes)
+ click.echo(f"Left these devboxes as they are. worktrees:clean no longer tracks them: {names}")
+
+
+def _resolve_box_action(stop_boxes: bool, delete_boxes: bool, keep_boxes: bool, mode: str) -> str | None:
+ if sum([stop_boxes, delete_boxes, keep_boxes]) > 1:
+ raise click.UsageError("Pass at most one of --stop-boxes, --delete-boxes, --keep-boxes.")
+ if (stop_boxes or delete_boxes) and mode != "full":
+ raise click.UsageError(
+ "--stop-boxes and --delete-boxes need --mode full, because --mode deps keeps the worktree."
+ )
+ if keep_boxes or mode != "full":
+ return None
+ if stop_boxes:
+ return "stop"
+ if delete_boxes:
+ return "delete"
+ return saved_worktree_box_cleanup()
+
+
+def _boxes_of_removed_worktrees(
+ registry: dict[str, WorktreeBoxRecord],
+ repo_root: Path,
+ repo_common: Path | None,
+ selected_sources: set[str] | None,
+) -> list[WorktreeBox]:
+ """Registered boxes whose worktree is gone, limited to the selected repo and sources.
+
+ The admin directory in the shared git dir outlives a moved or unmounted
+ checkout, so only its absence shows that the worktree was removed. A
+ record without a worktree ID cannot tell its admin directory from a
+ reused one, so any directory at that path counts as its own.
+ """
+ if repo_common is None:
+ return []
+ boxes: list[WorktreeBox] = []
+ for path, record in registry.items():
+ admin_dir = Path(record.git_dir)
+ admin_dir_is_its_own = record.tracks_worktree(admin_dir) if record.worktree_id else admin_dir.exists()
+ if Path(path).exists() or admin_dir_is_its_own or _resolve(admin_dir.parent.parent) != _resolve(repo_common):
+ continue
+ if selected_sources is not None and _source_under(_resolve(Path(path)), repo_root) not in selected_sources:
+ continue
+ boxes.append(WorktreeBox(worktree_path=Path(path), record=record))
+ return boxes
+
+
+def _clean_boxes_of_removed_worktrees(
+ boxes: list[WorktreeBox], box_action: str, cutoff: float, dry_run: bool, yes: bool
+) -> None:
+ """Act on the boxes of removed worktrees that have been idle since *cutoff*.
+
+ The worktree is gone, so the box's own last use stands in for its age.
+ """
+ if not boxes:
+ return
+ click.echo(f"{len(boxes)} devbox(es) belong to worktrees that were already removed:")
+ for box in boxes:
+ click.echo(f" {box.workspace} {_display_path(box.worktree_path)}")
+ if dry_run:
+ which = "them" if cutoff == float("inf") else "the ones not used since the cutoff"
+ click.echo(f"[DRY-RUN] Would {box_action} {which}.\n")
+ return
+ if yes or click.confirm(f"{box_action.capitalize()} them now?", default=False):
+ _clean_worktree_boxes(boxes, box_action, idle_before=cutoff)
+ click.echo()
+
+
+def _match_worktree_boxes(worktrees: list[Worktree], registry: dict[str, WorktreeBoxRecord]) -> list[WorktreeBox]:
+ """Pair each worktree with the devbox registered for it.
+
+ The match uses the ID that `devbox:worktree` stored in the worktree's admin
+ directory. `git worktree move` carries that directory over, so a moved
+ worktree still matches. A worktree recreated at a reused path gets a new,
+ empty admin directory, so it never matches its predecessor's box.
+ """
+ registry_by_worktree_id = {
+ record.worktree_id: (Path(path), record) for path, record in registry.items() if record.worktree_id
+ }
+ boxes: list[WorktreeBox] = []
+ for wt in worktrees:
+ git_dir = _gitdir_for(wt.path)
+ worktree_id = read_worktree_id(git_dir) if git_dir is not None else None
+ match = registry_by_worktree_id.get(worktree_id) if worktree_id is not None else None
+ if match is not None:
+ boxes.append(WorktreeBox(worktree_path=match[0], record=match[1], current_path=wt.path))
+ return boxes
+
+
+def _stop_worktree_mirrors(boxes: list[WorktreeBox]) -> None:
+ """Stop the sync mirrors before their worktrees go away.
+
+ A mirror that still runs while the local files disappear copies the
+ deletions to the devbox, which would empty the checkout that `--stop-boxes`
+ and `--keep-boxes` exist to keep.
+ """
+ for box in boxes:
+ try:
+ mutagen.sync_terminate(mutagen.workspace_label_selector(box.workspace))
+ except SystemExit:
+ click.echo(f" ⚠️ could not stop the sync mirror for {box.workspace}; its devbox copy may lose files.")
+
+
+def _box_last_used(workspace: Mapping[str, object]) -> float | None:
+ last_used = workspace.get("last_used_at")
+ if not isinstance(last_used, str):
+ return None
+ try:
+ return datetime.fromisoformat(last_used).timestamp()
+ except ValueError:
+ return None
+
+
+def _clean_worktree_boxes(boxes: list[WorktreeBox], box_action: str, idle_before: float = float("inf")) -> None:
+ try:
+ ensure_runtime_ready()
+ except SystemExit:
+ names = " ".join(box.workspace for box in boxes)
+ click.echo(f" ⚠️ could not reach Coder, so these devboxes were left as they are: {names}")
+ return
+
+ workspaces = fetch_user_workspaces()
+ if workspaces is None:
+ names = " ".join(box.workspace for box in boxes)
+ click.echo(f" ⚠️ could not list your devboxes, so these were left as they are: {names}")
+ return
+ handled: list[Path] = []
+ for box in boxes:
+ workspace = get_workspace(box.workspace, workspaces)
+ if workspace is None:
+ click.echo(f" {box.workspace} no longer exists.")
+ handled.append(box.worktree_path)
+ continue
+ if not box.record.owns(workspace):
+ 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(workspace)
+ 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 devbox {box.workspace}...")
+ delete_workspace(box.workspace)
+ elif get_workspace_status(workspace) != "stopped":
+ click.echo(f"Stopping devbox {box.workspace}...")
+ stop_workspace(box.workspace)
+ else:
+ click.echo(f" {box.workspace} is already stopped.")
+ except SystemExit:
+ command = "devbox:destroy" if box_action == "delete" else "devbox:stop"
+ label = extract_workspace_label(box.workspace) or ""
+ click.echo(f" ⚠️ could not {box_action} {box.workspace}. Run `hogli {command} {label}`.")
+ continue
+ handled.append(box.worktree_path)
+ forget_worktree_boxes(handled)
+
def _resolve_orphan_policy(explicit: str | None, mode: str) -> str:
"""Resolve --orphans, defaulting per mode: deps cleans orphans (their deps are