: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(devbox): drive worktree devboxes from agent app hooks (#129381)
Georges-Antoine Assi645a3d75fe25
diff --git a/.agents/skills/setting-up-devbox/SKILL.md b/.agents/skills/setting-up-devbox/SKILL.mdindex abfb2cd469f3..4d87e2de762f 100644--- a/.agents/skills/setting-up-devbox/SKILL.md+++ b/.agents/skills/setting-up-devbox/SKILL.md@@ -176,12 +176,14 @@ hogli devbox:worktree --clone-from default -y # create the box as a clone of ahogli 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.+- The label comes from the branch name, lowercased, with `/` and `_` turned into `-` and a leading `worktree-` or `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.+- A worktree recreated at the same path, as t3code does when it resumes a thread it cleaned up, takes over the box of the worktree it replaced while that box still exists, and gets a new 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.+- `hogli devbox:worktree:prune` acts only on those boxes of removed worktrees, without removing any worktree. It uses the saved action, or stops the boxes when none is saved. Pass `--stop` or `--delete` to choose, `--path <worktree>` to limit it to one worktree, and `--dry-run` to list them. Use it after t3code, herdr or a plain `git worktree remove` deleted a worktree.- Clear the saved action with `hogli devbox:config:rm worktree-boxes`.### Run worktree boxes on Hogland@@ -199,16 +201,24 @@ hogli devbox:worktree --on-clean stop # save what worktrees:clean does### 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.+The sources are `claude`, `codex`, `posthog-code`, `phw`, `t3code`, `herdr`, `superset`, `emdash`, `orca`, `conductor`, `worktrunk`, and `other` for a plain `git worktree add`.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`.+Two triggers start `hogli devbox:worktree -y` in the background, and the first one for a worktree wins:++- The husky `post-checkout` hook, for `claude`, `codex`, `posthog-code` and `phw`, which it recognizes by their worktree folders, and for `other`.+- The app's own create hook, which runs `bin/devbox-worktree-hook created <source>`. The repo checks these hooks in for Superset (`.superset/config.json`), Emdash (`.emdash.json`), Orca (`orca.yaml`) and worktrunk (`.config/wt.toml`). Orca and worktrunk ask each user to approve the commands once. Conductor would let a checked-in script replace each user's own scripts, so `--auto conductor` writes its hooks to the main checkout's uncommitted `.conductor/settings.local.toml` instead, and leaves an existing file for you to edit. t3code does not run `t3.json` by itself: each user imports it once from **Import from t3.json** in the project's scripts menu or in Settings → Projects → Actions. t3code runs only the first script set to run on worktree creation, so a project that already has its own setup script skips this one. herdr has no repo hook file, so run `herdr plugin link <main checkout>/tools/herdr-devbox-plugin` once.++The script runs the main checkout's hogli, so pull the main checkout after a change to these commands.- 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`.+- Superset, Orca and worktrunk run `bin/devbox-worktree-hook removing` before they delete a worktree. It runs `hogli devbox:worktree:teardown --background`, which stops the mirror while the files still exist and then stops the box in the background (log: `~/.config/posthog/hogli-devbox-teardown.log`). The box's record is then dropped, so the box no longer belongs to any worktree.+- Emdash and Conductor run `bin/devbox-worktree-hook archiving` instead, because they keep an archived worktree on disk. It adds `--keep-record`, so when the app restores the worktree, its create hook starts the same box again.+- herdr reports a removal only after the folder is gone, so its plugin runs `devbox:worktree:prune --path <worktree>`. t3code has no removal hook, so run `hogli devbox:worktree:prune` by hand.+- A t3code worktree restored from a cleaned-up thread skips setup scripts, so it gets a box only when `other` is enabled.## Other tasksdiff --git a/.config/wt.toml b/.config/wt.tomlnew file mode 100644index 000000000000..29eeeac0d77a--- /dev/null+++ b/.config/wt.toml@@ -0,0 +1,2 @@+post-start = "bin/devbox-worktree-hook created worktrunk"+pre-remove = "bin/devbox-worktree-hook removing"diff --git a/.emdash.json b/.emdash.jsonnew file mode 100644index 000000000000..ce46e910a4fc--- /dev/null+++ b/.emdash.json@@ -0,0 +1,6 @@+{+ "scripts": {+ "setup": "bin/devbox-worktree-hook created emdash",+ "teardown": "bin/devbox-worktree-hook archiving"+ }+}diff --git a/.gitignore b/.gitignoreindex 287a99e5e1c5..a78c90b9cb66 100644--- a/.gitignore+++ b/.gitignore@@ -160,6 +160,9 @@ posthog/management/commands/clear_demo_data.py.claude/scheduled_tasks.lock.claude/plans/+# Ignore Conductor local settings+.conductor/settings.local.toml+# Ignore local mprocs configsbin/mprocs*.local.yamldiff --git a/.superset/config.json b/.superset/config.jsonnew file mode 100644index 000000000000..ac8580190f15--- /dev/null+++ b/.superset/config.json@@ -0,0 +1,4 @@+{+ "setup": ["bin/devbox-worktree-hook created superset"],+ "teardown": ["bin/devbox-worktree-hook removing"]+}diff --git a/bin/devbox-worktree-hook b/bin/devbox-worktree-hooknew file mode 100755index 000000000000..6e17a8e23fba--- /dev/null+++ b/bin/devbox-worktree-hook@@ -0,0 +1,46 @@+#!/bin/sh+# Called by the create and remove hooks of apps that run coding agents in worktrees,+# with the worktree as the working directory:+#+# bin/devbox-worktree-hook created <source> after the app creates the worktree+# bin/devbox-worktree-hook removing before the app deletes the worktree+# bin/devbox-worktree-hook archiving before the app archives a worktree it keeps on disk+#+# It always exits 0, so a devbox problem never blocks the app. Like .husky/post-checkout,+# it runs the main clone's hogli and venv, because a new worktree has no venv of its own.++[ -f .git ] || exit 0++case "${1:-}" in+ created)+ # hogli telemetry reports this file as `worktree_tool` for every command run in the worktree.+ case "${2:-}" in+ "" | *[!a-z0-9-]*) ;;+ *) printf '%s\n' "$2" >"$(git rev-parse --absolute-git-dir)/hogli-worktree-source" 2>/dev/null ;;+ esac+ # Python stays off the path of everyone who has not run `devbox:worktree --auto`.+ grep -qs '"worktree_auto_box"' "$HOME/.config/posthog/hogli_devbox.json" || exit 0+ set -- devbox:worktree:auto --source "${2:-other}"+ ;;+ removing | archiving)+ [ -s "$HOME/.config/posthog/hogli_devbox_worktrees.json" ] || exit 0+ # The box action runs in the background, because Superset and Orca kill a remove hook after 60 and 120 seconds.+ # An archived worktree can be restored, and its create hook then starts the box again from the kept record.+ if [ "$1" = archiving ]; then+ set -- devbox:worktree:teardown --background --keep-record+ else+ set -- devbox:worktree:teardown --background+ fi+ ;;+ *)+ exit 0+ ;;+esac++. "$(cd "$(dirname "$0")" && pwd)/helpers/worktree-borrow.sh"+main="$(posthog_main_repo "$(pwd)")"+[ -n "$main" ] && [ -x "$main/bin/hogli" ] || exit 0++(unset PYTHONPATH && posthog_worktree_borrow main-only && HOGLI_MANIFEST="$main/hogli.yaml" "$main/bin/hogli" "$@") ||+ echo "devbox-worktree-hook: \`hogli $*\` failed. Run it by hand to see why." >&2+exit 0diff --git a/docs/internal/coder-workspaces.md b/docs/internal/coder-workspaces.mdindex 16eb2bc1ad5c..cc5b1aebb774 100644--- a/docs/internal/coder-workspaces.md+++ b/docs/internal/coder-workspaces.md@@ -68,8 +68,9 @@ Run `hogli devbox:worktree` from a linked worktree to give it its own labeled bo`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.+`hogli devbox:worktree:prune` handles only those boxes, with no cutoff, after t3code, herdr or `git worktree remove` deleted the worktree.-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`.+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`, `t3code`, `herdr`, `superset`, `emdash`, `orca`, `conductor`, `worktrunk`, `other`). The husky `post-checkout` hook then runs `devbox:worktree` in the background after `git worktree add`, including for `claude -w`. Superset, Emdash, Orca and worktrunk run it from the create hooks checked into the repo, and stop the box from their remove hooks. For Conductor, `--auto conductor` adds the same hooks to your uncommitted `.conductor/settings.local.toml`, so other people's Conductor scripts stay as they are. t3code runs it only after you import `t3.json` once with **Import from t3.json** in the project's scripts. herdr users link `tools/herdr-devbox-plugin` with `herdr plugin link`. Claude subagent worktrees are skipped. Turn it off with `--auto off`.**Worktree boxes on Hogland** —`hogli devbox:worktree --provider hogland` gives the worktree a Hogland devbox instead of a Coder workspace.diff --git a/hogli.yaml b/hogli.yamlindex bd548b69b7a2..4a67030ffe29 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -210,6 +210,12 @@ devbox:devbox:worktree:click: hogli_commands.devbox.worktree:devbox_worktreedescription: Give this worktree its own devbox and sync mirror+ devbox:worktree:prune:+ click: hogli_commands.devbox.worktree:devbox_worktree_prune+ description: Stop or delete the devboxes of worktrees that t3code, herdr or git already removed+ devbox:worktree:teardown:+ click: hogli_commands.devbox.worktree:devbox_worktree_teardown+ description: Stop the sync mirror and the devbox of this worktree before a tool removes itdevbox:worktree:auto:click: hogli_commands.devbox.worktree:devbox_worktree_autodescription: Start devbox:worktree in the background for a new worktree, if auto-provisioning is on@@ -1326,3 +1332,7 @@ environment:bin_script: semgrep_ratchet.pydescription: 'Compare semgrep findings per file with a checked-in baseline'hidden: true+ devbox:worktree:hook:+ bin_script: devbox-worktree-hook+ description: 'Start or stop the devbox of this worktree from an app create or remove hook'+ hidden: truediff --git a/orca.yaml b/orca.yamlnew file mode 100644index 000000000000..7231ad8b0951--- /dev/null+++ b/orca.yaml@@ -0,0 +1,5 @@+scripts:+ setup: |+ bin/devbox-worktree-hook created orca+ archive: |+ bin/devbox-worktree-hook removingdiff --git a/t3.json b/t3.jsonnew file mode 100644index 000000000000..19c0348ac240--- /dev/null+++ b/t3.json@@ -0,0 +1,9 @@+{+ "scripts": [+ {+ "name": "Devbox for this worktree",+ "command": "bin/devbox-worktree-hook created t3code",+ "runOnWorktreeCreate": true+ }+ ]+}diff --git a/tools/herdr-devbox-plugin/herdr-plugin.toml b/tools/herdr-devbox-plugin/herdr-plugin.tomlnew file mode 100644index 000000000000..87469e38c535--- /dev/null+++ b/tools/herdr-devbox-plugin/herdr-plugin.toml@@ -0,0 +1,14 @@+id = "posthog.devbox"+name = "PostHog devbox"+version = "0.2.1"+min_herdr_version = "0.7.1"+description = "Give each PostHog worktree that herdr creates its own devbox, and stop the box when herdr removes the worktree"+platforms = ["linux", "macos"]++[[events]]+on = "worktree.created"+command = ["python3", "-I", "on_worktree_event.py"]++[[events]]+on = "worktree.removed"+command = ["python3", "-I", "on_worktree_event.py"]diff --git a/tools/herdr-devbox-plugin/on_worktree_event.py b/tools/herdr-devbox-plugin/on_worktree_event.pynew file mode 100644index 000000000000..744287e81b28--- /dev/null+++ b/tools/herdr-devbox-plugin/on_worktree_event.py@@ -0,0 +1,86 @@+from __future__ import annotations++import os+import sys+import json+import subprocess+from pathlib import Path++REGISTRY_PATH = Path.home() / ".config" / "posthog" / "hogli_devbox_worktrees.json"+PLUGIN_CHECKOUT = Path(__file__).resolve().parents[2]+++def event_worktree_path(event_json: str) -> Path | None:+ try:+ path = json.loads(event_json)["data"]["worktree"]["path"]+ except (ValueError, KeyError, TypeError):+ return None+ return Path(path) if isinstance(path, str) and path else None+++def main_checkout_for(worktree_path: Path, registry: dict[str, dict[str, str]]) -> Path | None:+ for registered_path, record in registry.items():+ if Path(registered_path).resolve() == worktree_path.resolve() and record.get("git_dir"):+ # git_dir is <main checkout>/.git/worktrees/<name>.+ return Path(record["git_dir"]).parent.parent.parent+ return None+++def run(command: list[str], cwd: Path) -> int:+ return subprocess.run(+ command,+ cwd=cwd,+ env={key: value for key, value in os.environ.items() if key not in ("VIRTUAL_ENV", "PYTHONPATH")},+ stdin=subprocess.DEVNULL,+ check=False,+ ).returncode+++def is_worktree_of_plugin_checkout(worktree_path: Path) -> bool:+ try:+ line = (worktree_path / ".git").read_text().strip()+ except OSError:+ return False+ if not line.startswith("gitdir: "):+ return False+ admin_dir = (worktree_path / line[len("gitdir: ") :]).resolve()+ return admin_dir.parent.parent == (PLUGIN_CHECKOUT / ".git").resolve()+++def on_created(worktree_path: Path) -> int:+ # herdr runs linked plugins for every repo, and the new worktree's branch may not be trusted.+ # So only this checkout's worktrees count, and the hook runs from this checkout, not the worktree.+ hook = PLUGIN_CHECKOUT / "bin" / "devbox-worktree-hook"+ if not hook.exists() or not is_worktree_of_plugin_checkout(worktree_path):+ return 0+ return run([str(hook), "created", "herdr"], worktree_path)+++def on_removed(worktree_path: Path) -> int:+ # herdr emits worktree.removed after the directory is gone, so the box is found through hogli's registry.+ try:+ registry = json.loads(REGISTRY_PATH.read_text())+ except (OSError, ValueError):+ return 0+ main_checkout = main_checkout_for(worktree_path, registry) if isinstance(registry, dict) else None+ if main_checkout is None or not (main_checkout / "bin" / "hogli").exists():+ return 0+ return run(+ [str(main_checkout / "bin" / "hogli"), "devbox:worktree:prune", "--path", str(worktree_path)], main_checkout+ )+++def main() -> int:+ worktree_path = event_worktree_path(os.environ.get("HERDR_PLUGIN_EVENT_JSON", ""))+ if worktree_path is None:+ return 0+ event = os.environ.get("HERDR_PLUGIN_EVENT")+ if event == "worktree.created":+ return on_created(worktree_path)+ if event == "worktree.removed":+ return on_removed(worktree_path)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/hogli-commands/hogli_commands/devbox/config.py b/tools/hogli-commands/hogli_commands/devbox/config.pyindex 9debc6a1cd61..1f1f51fca4dc 100644--- a/tools/hogli-commands/hogli_commands/devbox/config.py+++ b/tools/hogli-commands/hogli_commands/devbox/config.py@@ -34,7 +34,20 @@ _PERSISTED_FIELDS = ()WORKTREE_BOX_CLEANUP_ACTIONS = ("stop", "delete")-WORKTREE_AUTO_SOURCES = ("claude", "codex", "posthog-code", "phw", "other")+WORKTREE_AUTO_SOURCES = (+ "claude",+ "codex",+ "posthog-code",+ "phw",+ "t3code",+ "herdr",+ "superset",+ "emdash",+ "orca",+ "conductor",+ "worktrunk",+ "other",+)WORKTREE_PROVIDERS = ("coder", "hogland")DEFAULT_WORKTREE_PROVIDER = "coder"_WORKTREE_ID_FILE = "hogli-devbox-worktree-id"diff --git a/tools/hogli-commands/hogli_commands/devbox/worktree.py b/tools/hogli-commands/hogli_commands/devbox/worktree.pyindex 2486129f3f45..9465207283aa 100644--- a/tools/hogli-commands/hogli_commands/devbox/worktree.py+++ b/tools/hogli-commands/hogli_commands/devbox/worktree.py@@ -2,8 +2,11 @@from __future__ import annotations+import osimport reimport sys+import json+import shutilimport hashlibimport subprocessimport urllib.parse@@ -14,7 +17,13 @@ from typing import Anyimport click-from ..worktrees import worktree_source+from ..worktrees import (+ WorktreeBox,+ clean_registered_box,+ prune_boxes_of_removed_worktrees,+ teardown_worktree_box,+ worktree_source,+)from . import hogland, mutagenfrom .cli import _preferred_region, devbox_clone, devbox_start, resolve_workspace_namefrom .coder import (@@ -39,12 +48,14 @@ from .config import (clear_worktree_auto_sources,clear_worktree_box_cleanup,ensure_worktree_id,+ get_worktree_boxes_path,load_worktree_boxes,record_worktree_box,save_worktree_auto_sources,save_worktree_box_cleanup,save_worktree_provider,saved_worktree_auto_sources,+ saved_worktree_box_cleanup,saved_worktree_provider,worktree_box_claimant,)@@ -52,11 +63,18 @@ from .sync import _REMOTE_REPO_PATH, _detect_local_posthog_checkout, ensure_hoglCODER_NAME_MAX_LENGTH = 32_HASH_LENGTH = 4-_BRANCH_PREFIXES_TO_DROP = ("worktree-",)+_BRANCH_PREFIXES_TO_DROP = ("worktree-", "worktree/")_RESERVED_SUFFIXES = tuple(suffix for suffix in REGION_NAME_SUFFIXES.values() if suffix)_AUTO_OFF = "off"_AUTO_LOG_NAME = "hogli-devbox-worktree.log"+_AUTO_STARTED_NAME = "hogli-devbox-worktree.auto-started"+_TEARDOWN_LOG_NAME = "hogli-devbox-teardown.log"+_HERDR_PLUGIN_ID = "posthog.devbox"+_HERDR_PLUGIN_DIR = Path("tools") / "herdr-devbox-plugin"_SUBAGENT_WORKTREE_PREFIX = "agent-"+_CONDUCTOR_LOCAL_SETTINGS = Path(".conductor") / "settings.local.toml"+_CONDUCTOR_SETUP_SCRIPT = "bin/devbox-worktree-hook created conductor"+_CONDUCTOR_SCRIPTS = f'[scripts]\nsetup = "{_CONDUCTOR_SETUP_SCRIPT}"\narchive = "bin/devbox-worktree-hook archiving"\n'def label_budget(username: str, region: str) -> int:@@ -133,7 +151,101 @@ def _save_auto_sources(value: str) -> None: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."+ "The husky post-checkout hook or the app's own create hook starts `hogli devbox:worktree` in the background."+ )+ if "herdr" in sources:+ _link_herdr_plugin(_detect_local_posthog_checkout())+ if "conductor" in sources:+ _install_conductor_scripts(_detect_local_posthog_checkout())+++def _install_conductor_scripts(root: Path) -> None:+ """Write the hooks to Conductor's uncommitted project settings, because a committed file would replace each user's own scripts."""+ try:+ settings_path = _main_checkout(root) / _CONDUCTOR_LOCAL_SETTINGS+ except (OSError, subprocess.SubprocessError):+ click.echo(+ f"Couldn't find your main checkout. Add these lines to <main checkout>/{_CONDUCTOR_LOCAL_SETTINGS}:\n"+ f"{_CONDUCTOR_SCRIPTS}"+ )+ return+ if settings_path.exists():+ if _CONDUCTOR_SETUP_SCRIPT in settings_path.read_text():+ click.echo(f"Conductor already runs the devbox scripts from {settings_path}.")+ else:+ click.echo(+ f"{settings_path} already exists, so add the devbox scripts to it yourself:\n{_CONDUCTOR_SCRIPTS}"+ )+ return+ settings_path.parent.mkdir(exist_ok=True)+ settings_path.write_text(_CONDUCTOR_SCRIPTS)+ click.echo(f"Added the devbox setup and archive scripts to {settings_path}.")+++def _find_herdr_plugin(listing: Any) -> dict[str, Any] | None:+ if isinstance(listing, dict):+ if listing.get("plugin_id") == _HERDR_PLUGIN_ID:+ return listing+ children: list[Any] = list(listing.values())+ elif isinstance(listing, list):+ children = listing+ else:+ return None+ for child in children:+ found = _find_herdr_plugin(child)+ if found is not None:+ return found+ return None+++def _main_checkout(root: Path) -> Path:+ result = subprocess.run(+ ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"],+ cwd=root,+ capture_output=True,+ text=True,+ check=True,+ )+ return Path(result.stdout.strip()).parent+++def _link_herdr_plugin(root: Path) -> None:+ """Link the plugin from the main checkout, which outlives every worktree, unless herdr already has it."""+ herdr = shutil.which("herdr")+ if herdr is None:+ click.echo(+ f"herdr isn't on your PATH. Once it is, run `herdr plugin link <main checkout>/{_HERDR_PLUGIN_DIR}`."+ )+ return+ try:+ listing = subprocess.run([herdr, "plugin", "list", "--json"], capture_output=True, text=True, timeout=30)+ existing = _find_herdr_plugin(json.loads(listing.stdout)) if listing.returncode == 0 else None+ except (OSError, subprocess.SubprocessError, ValueError):+ existing = None+ if existing is not None:+ state = "enabled" if existing.get("enabled") else "disabled"+ click.echo(+ f"The herdr plugin {_HERDR_PLUGIN_ID} is already linked from {existing.get('plugin_root')} ({state})."+ )+ return+ try:+ plugin_dir = _main_checkout(root) / _HERDR_PLUGIN_DIR+ except (OSError, subprocess.SubprocessError):+ click.echo(f"Couldn't find your main checkout. Run `herdr plugin link <main checkout>/{_HERDR_PLUGIN_DIR}`.")+ return+ if not (plugin_dir / "herdr-plugin.toml").is_file():+ click.echo(f"Your main checkout has no {_HERDR_PLUGIN_DIR} yet. Pull it, then run this command again.")+ return+ try:+ result = subprocess.run([herdr, "plugin", "link", str(plugin_dir)], capture_output=True, text=True, timeout=60)+ except (OSError, subprocess.SubprocessError) as error:+ click.echo(f"Couldn't link the herdr plugin: {error}")+ return+ if result.returncode != 0:+ click.echo(f"Couldn't link the herdr plugin: {(result.stderr or result.stdout).strip()}")+ return+ click.echo(+ f"Linked the herdr plugin from {plugin_dir}. Turn it off with `herdr plugin disable {_HERDR_PLUGIN_ID}`.")@@ -154,6 +266,7 @@ class _WorktreeTarget:workspace_name: strlabel: strabandoned_mirror: str | None = None+ reset_mirror: bool = False@dataclass(frozen=True)@@ -204,6 +317,15 @@ def _fail_if_other_provider_box_exists(record: WorktreeBoxRecord) -> None:)+def _predecessor_box_survives(+ record: WorktreeBoxRecord | None, workspaces: list[dict[str, Any]], provider: str+) -> bool:+ if record is None or record.provider != provider:+ return False+ live = get_workspace(record.workspace, workspaces)+ return live is not None and record.owns(live)++def _resolve_target(root: Path,label: str | None,@@ -215,12 +337,17 @@ def _resolve_target("""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.+ rename, so a re-run never creates a second box. A worktree recreated at the+ same path, as t3code does when it resumes a thread it cleaned up, takes over+ the box of the worktree it replaces while that box still exists. Its mirror+ is recreated, because the old one saw its local root disappear."""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)):+ recreated = (+ registered is not None and registered.worktree_id is not None and not registered.tracks_worktree(_git_dir(root))+ )+ if recreated and not _predecessor_box_survives(registered, workspaces, provider):registered = Noneabandoned_mirror = Noneif registered is not None and registered.provider != provider:@@ -232,7 +359,7 @@ def _resolve_target(registered = registered_box = Noneregistered_label = label_of(registered.workspace) if registered is not None else Noneif 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)+ return _WorktreeTarget(workspace_name=registered.workspace, label=registered_label, reset_mirror=recreated)box_naming = naming()resolved_label = label or derive_label(_current_branch(root), box_naming.label_budget)@@ -271,6 +398,28 @@ def _list_workspaces_or_fail() -> list[dict[str, Any]]:return workspaces+def _prune_box_of_worktree_removed_during_setup(root: Path, git_dir: Path) -> bool:+ if root.exists():+ return False+ click.echo(f"{root} was removed while its devbox started.")+ box_action = saved_worktree_box_cleanup() or "stop"+ prune_boxes_of_removed_worktrees(git_dir.parents[2], box_action, root, dry_run=False)+ return True+++def _has_reusable_mirror(target: _WorktreeTarget) -> bool:+ if target.reset_mirror:+ return False+ return bool(mutagen.sync_list(label_selector=mutagen.workspace_label_selector(target.workspace_name)))+++def _reset_recreated_mirror(target: _WorktreeTarget) -> None:+ # Runs before `_claim_box` saves the new worktree's ID. A failed terminate then+ # leaves the old ID in place, so a retry still sees a recreated worktree and resets.+ if target.reset_mirror:+ mutagen.sync_terminate(mutagen.workspace_label_selector(target.workspace_name))++@click.command(name="devbox:worktree", help="Give this worktree its own devbox and sync mirror")@click.option("--label", default=None, help="Devbox label to use instead of one derived from the branch name")@click.option(@@ -359,7 +508,7 @@ def devbox_worktree(lambda: _coder_naming(cloning, clone_source),)existing = get_workspace(target.workspace_name, workspaces)- has_sync = bool(mutagen.sync_list(label_selector=mutagen.workspace_label_selector(target.workspace_name)))+ has_sync = _has_reusable_mirror(target)if existing is None:box_step = (@@ -377,6 +526,7 @@ def devbox_worktree(if not _print_plan(root, box_step, sync_step, on_clean, dry_run):return+ _reset_recreated_mirror(target)git_dir, worktree_id = _claim_box(root, target, existing, on_clean, "coder")_drop_abandoned_mirror(target)@@ -400,6 +550,8 @@ def devbox_worktree(worktree_id=worktree_id,),)+ if _prune_box_of_worktree_removed_during_setup(root, git_dir):+ returnensure_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)}")@@ -453,7 +605,7 @@ def _hogland_worktree(root: Path, label: str | None, on_clean: str | None, dry_rtarget = _resolve_target(root, label, devboxes, "hogland", hogland.label_of, _hogland_naming)name = target.workspace_nameexisting = get_workspace(name, devboxes)- has_sync = bool(mutagen.sync_list(label_selector=mutagen.workspace_label_selector(name)))+ has_sync = _has_reusable_mirror(target)if existing is None:box_step = f"Create Hogland devbox '{name}'"@@ -468,6 +620,7 @@ def _hogland_worktree(root: Path, label: str | None, on_clean: str | None, dry_r)if not _print_plan(root, box_step, sync_step, on_clean, dry_run):return+ _reset_recreated_mirror(target)git_dir, worktree_id = _claim_box(root, target, existing, on_clean, "hogland")_drop_abandoned_mirror(target)@@ -487,6 +640,8 @@ def _hogland_worktree(root: Path, label: str | None, on_clean: str | None, dry_rprovider="hogland",),)+ if _prune_box_of_worktree_removed_during_setup(root, git_dir):+ returnensure_hogland_sync_session(name, root, verbose=verbose)click.echo()click.echo(f" SSH hogland devbox ssh {name}")@@ -494,28 +649,146 @@ def _hogland_worktree(root: Path, label: str | None, on_clean: str | None, dry_rclick.echo(f" Stop hogland devbox hibernate {name}")+ name="devbox:worktree:prune",+ help="Stop or delete the devboxes of worktrees that another tool, such as t3code or herdr, already removed",+)[email protected]("--stop", "action", flag_value="stop", default=None, help="Stop the boxes")[email protected]("--delete", "action", flag_value="delete", help="Delete the boxes, including their disks")+ "--path",+ "worktree_path",+ type=click.Path(path_type=Path),+ default=None,+ help="Only the box of the worktree that was at this path",+)[email protected]("--dry-run", is_flag=True, help="Print the boxes without changing anything")+def devbox_worktree_prune(action: str | None, worktree_path: Path | None, dry_run: bool) -> None:+ box_action = action or saved_worktree_box_cleanup() or "stop"+ pruned = prune_boxes_of_removed_worktrees(_detect_local_posthog_checkout(), box_action, worktree_path, dry_run)+ if not pruned:+ click.echo("No devboxes belong to removed worktrees.")+++def _act_on_box_in_background(worktree_root: Path, box: WorktreeBox, box_action: str, keep_record: bool) -> None:+ # The worktree and its git directory are about to be deleted, so the process runs+ # from the main checkout and logs next to the box records.+ main_checkout = _main_checkout(worktree_root)+ log_path = get_worktree_boxes_path().with_name(_TEARDOWN_LOG_NAME)+ main_env = {key: value for key, value in os.environ.items() if key not in ("VIRTUAL_ENV", "PYTHONPATH")}+ with log_path.open("ab") as log:+ subprocess.Popen(+ [+ str(main_checkout / "bin" / "hogli"),+ "devbox:worktree:teardown",+ f"--{box_action}",+ "--box-of",+ str(box.worktree_path),+ "--worktree-id",+ str(box.record.worktree_id),+ *(["--keep-record"] if keep_record else []),+ ],+ cwd=main_checkout,+ env={**main_env, "HOGLI_MANIFEST": str(main_checkout / "hogli.yaml")},+ stdin=subprocess.DEVNULL,+ stdout=log,+ stderr=subprocess.STDOUT,+ start_new_session=True,+ )+ click.echo(+ f"hogli: the sync mirror is stopped. The devbox {box_action} continues in the background. Log: {log_path}"+ )+++ name="devbox:worktree:teardown",+ help="Stop the sync mirror and the devbox of this worktree before a tool such as Superset or Emdash removes it",+)[email protected]("--stop", "action", flag_value="stop", default=None, help="Stop the box")[email protected]("--delete", "action", flag_value="delete", help="Delete the box, including its disk")+ "--background",+ is_flag=True,+ help="Stop the mirror now and act on the box in a background process, to stay inside a tool's hook time limit",+)+ "--keep-record",+ is_flag=True,+ help="Keep the record of a stopped box, for a tool that keeps the worktree on disk, such as Emdash on archive",+)[email protected]("--box-of", "box_of", type=click.Path(path_type=Path), default=None, hidden=True)[email protected]("--worktree-id", "worktree_id", default=None, hidden=True)[email protected]("--dry-run", is_flag=True, help="Print the plan without changing anything")+def devbox_worktree_teardown(+ action: str | None,+ background: bool,+ keep_record: bool,+ box_of: Path | None,+ worktree_id: str | None,+ dry_run: bool,+) -> None:+ box_action = action or saved_worktree_box_cleanup() or "stop"+ if box_of is not None:+ if worktree_id is not None:+ clean_registered_box(box_of, worktree_id, box_action, keep_record)+ return+ root = _detect_local_posthog_checkout()+ if not _is_linked_worktree(root):+ return+ git_dir = _git_dir(root)+ act_on_box = (lambda box, chosen: _act_on_box_in_background(root, box, chosen, keep_record)) if background else None+ if teardown_worktree_box(root, git_dir, box_action, dry_run, keep_record, act_on_box) is None:+ click.echo("This worktree has no devbox from `hogli devbox:worktree`.")+ elif not dry_run:+ # A tool that keeps the worktree, such as Emdash on archive, can run its create hook again later.+ (git_dir / _AUTO_STARTED_NAME).unlink(missing_ok=True)+++def _claim_auto_start(git_dir: Path) -> bool:+ # Both the husky post-checkout hook and a tool's own create hook can fire for+ # one new worktree. The first caller creates this file and starts the box.+ try:+ (git_dir / _AUTO_STARTED_NAME).open("x").close()+ except FileExistsError:+ return False+ return True++@click.command(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:+ "--source",+ type=click.Choice(WORKTREE_AUTO_SOURCES),+ default=None,+ help="The tool that created the worktree. Defaults to the tool whose folder holds it.",+)+def devbox_worktree_auto(source: str | None) -> None:enabled = saved_worktree_auto_sources()if not enabled:returnroot = _detect_local_posthog_checkout()- if not _is_linked_worktree(root) or not should_auto_provision(root, worktree_source(root), enabled):+ if not _is_linked_worktree(root) or not should_auto_provision(root, source or worktree_source(root), enabled):+ return+ git_dir = _git_dir(root)+ if not _claim_auto_start(git_dir):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,- )+ log_path = git_dir / _AUTO_LOG_NAME+ try:+ 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,+ )+ except OSError:+ (git_dir / _AUTO_STARTED_NAME).unlink(missing_ok=True)+ raiseclick.echo(f"hogli: creating a devbox for this worktree in the background. Log: {log_path}")diff --git a/tools/hogli-commands/hogli_commands/telemetry_props.py b/tools/hogli-commands/hogli_commands/telemetry_props.pyindex abce06ef83ab..c3c26ab549ac 100644--- a/tools/hogli-commands/hogli_commands/telemetry_props.py+++ b/tools/hogli-commands/hogli_commands/telemetry_props.py@@ -188,6 +188,27 @@ def _repo_commit() -> tuple[str, str] | None:return None+# bin/devbox-worktree-hook writes this file into a worktree's git directory when an app+# such as t3code or Superset creates the worktree. Keep the name in sync with that script.+_WORKTREE_TOOL_FILE = "hogli-worktree-source"+_WORKTREE_TOOL_RE = re.compile(r"^[a-z0-9-]{1,32}$")+++def _worktree_tool(repo_root: Path) -> str | None:+ """The app that created this linked worktree, as its create hook recorded it."""+ try:+ pointer = (repo_root / ".git").read_text().strip()+ if not pointer.startswith("gitdir:"):+ return None+ git_dir = Path(pointer.removeprefix("gitdir:").strip())+ if not git_dir.is_absolute():+ git_dir = repo_root / git_dir+ tool = (git_dir / _WORKTREE_TOOL_FILE).read_text().strip()+ except (OSError, ValueError):+ return None+ return tool if _WORKTREE_TOOL_RE.match(tool) else None++def _repo_commit_properties() -> dict[str, str]:commit = _repo_commit()if commit is None:@@ -531,6 +552,7 @@ def _posthog_telemetry_properties(command: str | None = None) -> dict[str, Any]:"in_flox": os.environ.get("FLOX_ENV") is not None,"is_agent": agent is not None,"is_worktree": (REPO_ROOT / ".git").is_file(),+ "worktree_tool": _worktree_tool(REPO_ROOT),"worktree_count": _worktree_count(),"disk_free_gb": _disk_free_gb(),"is_posthog_dev": _is_posthog_dev(),diff --git a/tools/hogli-commands/hogli_commands/tests/test_commands.py b/tools/hogli-commands/hogli_commands/tests/test_commands.pyindex 845c65c068a9..d5d0fe472c6f 100644--- a/tools/hogli-commands/hogli_commands/tests/test_commands.py+++ b/tools/hogli-commands/hogli_commands/tests/test_commands.py@@ -23,6 +23,7 @@ from hogli_commands.telemetry_props import (_repo_commit,_repo_commit_properties,_session_properties,+ _worktree_tool,classify_command,is_rerun,)@@ -48,6 +49,33 @@ class TestProcessManagerInference:assert _infer_process_manager("start") == expected+class TestWorktreeTool:+ @pytest.mark.parametrize(+ ("pointer", "recorded", "expected"),+ [+ ("gitdir: {admin}", "superset\n", "superset"),+ ("gitdir: admin", "t3code", "t3code"),+ ("gitdir: {admin}", None, None),+ ("gitdir: {admin}", "Not A Tool; rm -rf", None),+ (None, "superset", None),+ ],+ ids=["absolute-gitdir", "relative-gitdir", "no-hook-ran", "unexpected-content", "main-checkout"],+ )+ def test_reads_the_tool_the_create_hook_recorded(+ self, tmp_path, pointer: str | None, recorded: str | None, expected: str | None+ ) -> None:+ admin = tmp_path / "admin"+ admin.mkdir()+ if recorded is not None:+ (admin / "hogli-worktree-source").write_text(recorded)+ if pointer is None:+ (tmp_path / ".git").mkdir()+ else:+ (tmp_path / ".git").write_text(pointer.format(admin=admin))++ assert _worktree_tool(tmp_path) == expected++class TestDetectEnvironment:@pytest.fixture(autouse=True)def _neutral_environment(self, monkeypatch, tmp_path):diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.pyindex 5b384f1970c3..bb9004418bc2 100644--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py@@ -17,6 +17,7 @@ from unittest.mock import MagicMock, patchfrom click.testing import CliRunnerfrom hogli.cli import cli+from hogli_commands import worktreesfrom hogli_commands.devbox import (cli as devbox_cli,coder,@@ -911,8 +912,9 @@ class TestWorktreeLabel:("feat/session-replay", "feat-session-replay"),("Fix_Cohort__Query", "fix-cohort-query"),("worktree-agent-abc", "agent-abc"),+ ("worktree/brave-river-1a2b", "brave-river-1a2b"),],- ids=["slash", "case-and-underscores", "claude-worktree-prefix"],+ ids=["slash", "case-and-underscores", "claude-worktree-prefix", "herdr-worktree-prefix"],)def test_short_branch_becomes_readable_label(self, branch: str, expected: str) -> None:assert devbox_worktree.derive_label(branch, 20) == expected@@ -967,6 +969,139 @@ class TestWorktreeAutoProvision:root = Path("/work") / worktree_nameassert devbox_worktree.should_auto_provision(root, source, frozenset(enabled)) is expected+ @pytest.mark.parametrize(+ "herdr_installed, listed_plugins, expected_link",+ [+ pytest.param(True, [], True, id="links-from-the-main-checkout"),+ pytest.param(+ True,+ [{"plugin_id": "posthog.devbox", "plugin_root": "/elsewhere", "enabled": False}],+ False,+ id="keeps-an-existing-link-and-its-disabled-state",+ ),+ pytest.param(False, [], False, id="herdr-not-installed"),+ ],+ )+ def test_auto_with_herdr_links_the_plugin_once(+ self,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ herdr_installed: bool,+ listed_plugins: list[dict[str, object]],+ expected_link: bool,+ ) -> None:+ main = tmp_path / "main"+ (main / "tools" / "herdr-devbox-plugin").mkdir(parents=True)+ (main / "tools" / "herdr-devbox-plugin" / "herdr-plugin.toml").write_text("")+ monkeypatch.setattr(devbox_config, "get_config_path", lambda: tmp_path / "config.json")+ monkeypatch.setattr(devbox_worktree, "_detect_local_posthog_checkout", lambda: tmp_path / "wt")+ monkeypatch.setattr(+ devbox_worktree.shutil, "which", lambda name: "/bin/herdr" if herdr_installed and name == "herdr" else None+ )+ herdr_calls: list[list[str]] = []++ def fake_run(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:+ if command[0] == "git":+ return subprocess.CompletedProcess(command, 0, stdout=f"{main / '.git'}\n", stderr="")+ herdr_calls.append(command)+ listing = {"id": "cli", "result": {"type": "plugin_list", "plugins": listed_plugins}}+ return subprocess.CompletedProcess(command, 0, stdout=json.dumps(listing), stderr="")++ monkeypatch.setattr(devbox_worktree.subprocess, "run", fake_run)++ result = runner.invoke(cli, ["devbox:worktree", "--auto", "claude,herdr"])++ assert result.exit_code == 0, result.output+ links = [call for call in herdr_calls if call[1:3] == ["plugin", "link"]]+ assert links == (+ [["/bin/herdr", "plugin", "link", str(main / "tools" / "herdr-devbox-plugin")]] if expected_link else []+ )++ @pytest.mark.parametrize(+ "existing_settings, expected_settings",+ [+ pytest.param(None, devbox_worktree._CONDUCTOR_SCRIPTS, id="writes-the-local-settings"),+ pytest.param(+ '[scripts]\nsetup = "./my-setup.sh"\n',+ '[scripts]\nsetup = "./my-setup.sh"\n',+ id="keeps-the-users-own-scripts",+ ),+ ],+ )+ def test_auto_with_conductor_adds_scripts_only_to_uncommitted_settings(+ self,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ existing_settings: str | None,+ expected_settings: str,+ ) -> None:+ main = tmp_path / "main"+ settings_path = main / ".conductor" / "settings.local.toml"+ main.mkdir()+ if existing_settings is not None:+ settings_path.parent.mkdir()+ settings_path.write_text(existing_settings)+ monkeypatch.setattr(devbox_config, "get_config_path", lambda: tmp_path / "config.json")+ monkeypatch.setattr(devbox_worktree, "_detect_local_posthog_checkout", lambda: tmp_path / "wt")+ monkeypatch.setattr(+ devbox_worktree.subprocess,+ "run",+ lambda command, **kwargs: subprocess.CompletedProcess(command, 0, stdout=f"{main / '.git'}\n", stderr=""),+ )++ result = runner.invoke(cli, ["devbox:worktree", "--auto", "conductor"])++ assert result.exit_code == 0, result.output+ assert settings_path.read_text() == expected_settings++ @pytest.mark.parametrize(+ "source_arg, enabled, first_spawn_fails, expected_starts",+ [+ pytest.param("t3code", "t3code", False, 1, id="tool-hook-declares-an-enabled-source"),+ pytest.param(None, "t3code", False, 0, id="husky-hook-sees-only-the-folder"),+ pytest.param("t3code", "claude", False, 0, id="declared-source-not-enabled"),+ pytest.param("t3code", "t3code", True, 1, id="failed-spawn-releases-the-claim"),+ ],+ )+ def test_auto_starts_at_most_one_box_per_worktree(+ self,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ source_arg: str | None,+ enabled: str,+ first_spawn_fails: bool,+ expected_starts: int,+ ) -> None:+ root = tmp_path / "wt"+ (root / "admin").mkdir(parents=True)+ (root / ".git").write_text("gitdir: elsewhere\n")+ monkeypatch.setattr(devbox_config, "get_config_path", lambda: tmp_path / "config.json")+ devbox_config.save_worktree_auto_sources([enabled])+ monkeypatch.setattr(devbox_worktree, "_detect_local_posthog_checkout", lambda: root)+ monkeypatch.setattr(devbox_worktree, "_git_dir", lambda root: root / "admin")+ monkeypatch.setattr(devbox_worktree, "worktree_source", lambda root: "other")+ starts: list[list[str]] = []+ attempts: list[list[str]] = []+ real_popen = subprocess.Popen++ def fake_popen(command: list[str], *args: object, **kwargs: object) -> object:+ if "devbox:worktree" not in command:+ return real_popen(command, *args, **kwargs)+ attempts.append(command)+ if first_spawn_fails and len(attempts) == 1:+ raise OSError("spawn failed")+ starts.append(command)+ return MagicMock()++ monkeypatch.setattr(devbox_worktree.subprocess, "Popen", fake_popen)+ args = ["devbox:worktree:auto", *(["--source", source_arg] if source_arg else [])]++ for attempt in range(2):+ result = runner.invoke(cli, args)+ assert result.exit_code == (1 if first_spawn_fails and attempt == 0 else 0), result.output++ assert len(starts) == expected_starts+class TestDevboxWorktreeCommand:@pytest.fixture@@ -1065,6 +1200,88 @@ class TestDevboxWorktreeCommand:assert (started, synced) == (expected_calls, expected_calls)assert devbox_config.load_worktree_boxes()[str(worktree_root)].workspace == expected_box+ @pytest.mark.parametrize(+ "live_id, expected_exit",+ [+ pytest.param("id-of-the-old-box", 0, id="adopts-the-box-it-replaces-and-resets-its-mirror"),+ pytest.param("id-of-a-recreated-box", 1, id="refuses-a-same-name-box-it-did-not-set-up"),+ ],+ )+ def test_worktree_recreated_at_the_same_path(+ self, monkeypatch: pytest.MonkeyPatch, worktree_root: Path, live_id: str, expected_exit: int+ ) -> None:+ name = "devbox-test-user-wt"+ workspaces = [{"name": name, "id": live_id, "latest_build": {"status": "stopped"}}]+ monkeypatch.setattr(devbox_worktree, "fetch_user_workspaces", lambda: workspaces)+ monkeypatch.setattr(devbox_cli, "list_user_workspaces", lambda: workspaces)+ devbox_config.record_worktree_box(+ worktree_root,+ devbox_config.WorktreeBoxRecord(+ workspace=name,+ git_dir="admin",+ workspace_id="id-of-the-old-box",+ worktree_id="id-of-the-removed-worktree",+ ),+ )+ started: list[str] = []+ terminated: list[str] = []+ monkeypatch.setattr(+ devbox_worktree,+ "devbox_start",+ lambda workspace, region, verbose, start_app=None: started.append(workspace),+ )+ monkeypatch.setattr(devbox_worktree, "ensure_sync_session", lambda *a, **kw: None)+ monkeypatch.setattr(devbox_worktree.mutagen, "sync_terminate", terminated.append)++ result = runner.invoke(cli, ["devbox:worktree"])++ assert result.exit_code == expected_exit, result.output+ adopted = expected_exit == 0+ assert started == (["wt"] if adopted else [])+ assert terminated == ([devbox_worktree.mutagen.workspace_label_selector(name)] if adopted else [])+ record = devbox_config.load_worktree_boxes()[str(worktree_root)]+ assert (record.worktree_id != "id-of-the-removed-worktree") is adopted++ def test_box_of_a_worktree_removed_during_setup_is_stopped_instead_of_synced(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, devbox_config_path: Path+ ) -> None:+ main = tmp_path / "main"+ main.mkdir()+ _git(main, "init", "-q", "-b", "master")+ _git(main, "commit", "-q", "--allow-empty", "-m", "init")+ root = tmp_path / "wt"+ _git(main, "worktree", "add", "-q", "-b", "feat", str(root))+ name = "devbox-test-user-feat"+ workspaces: list[dict[str, Any]] = []+ 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, "_preferred_region", lambda: "us-east-1")+ monkeypatch.setattr(devbox_mutagen, "sync_list", lambda label_selector=None: [])+ monkeypatch.setattr(devbox_mutagen, "sync_terminate", lambda selector: None)+ for module in (devbox_worktree, worktrees):+ monkeypatch.setattr(module, "ensure_runtime_ready", lambda: None)+ monkeypatch.setattr(module, "fetch_user_workspaces", lambda: workspaces)+ stopped: list[str] = []+ synced: list[str] = []+ monkeypatch.setattr(worktrees, "stop_workspace", stopped.append)+ monkeypatch.setattr(devbox_worktree, "ensure_sync_session", lambda name, *a, **kw: synced.append(name))++ def start_while_the_app_removes_the_worktree(+ workspace: str, region: str, verbose: bool, start_app: bool | None = None+ ) -> None:+ workspaces.append({"name": name, "id": "id-new-box", "latest_build": {"status": "running"}})+ _git(main, "worktree", "remove", "--force", str(root))++ monkeypatch.setattr(devbox_worktree, "devbox_start", start_while_the_app_removes_the_worktree)++ result = runner.invoke(cli, ["devbox:worktree"])++ assert result.exit_code == 0, result.output+ assert (stopped, synced) == ([name], [])+@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: booldiff --git a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py b/tools/hogli-commands/hogli_commands/tests/test_worktrees.pyindex 130cbab1be1c..5341c13c6446 100644--- a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py+++ b/tools/hogli-commands/hogli_commands/tests/test_worktrees.py@@ -582,15 +582,126 @@ class TestWorktreeBoxes:assert boxes == (expected if pending else [])@pytest.mark.parametrize(- ("action", "status", "live_id", "last_used_at", "expected_calls"),+ ("path_arg", "expected_workspaces"),[- ("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", "", []),+ (None, ["devbox-test-user-feature", "devbox-test-user-other"]),+ ("link/.herdr-wt/feature", ["devbox-test-user-feature"]),+ ],+ ids=["every-removed-worktree", "only-the-path-herdr-reports-through-a-symlink"],+ )+ def test_prune_acts_on_removed_worktrees_or_only_the_given_path(+ self, tmp_path, monkeypatch, path_arg: str | None, expected_workspaces: list[str]+ ) -> None:+ repo = tmp_path / "repo"+ common = repo / ".git"+ (common / "worktrees").mkdir(parents=True)+ (tmp_path / "link").symlink_to(repo, target_is_directory=True)+ monkeypatch.setattr(devbox_config, "get_worktree_boxes_path", lambda: tmp_path / "boxes.json")+ monkeypatch.setattr(worktrees, "_git_common_dir", lambda start: common)+ for name in ("feature", "other"):+ devbox_config.record_worktree_box(+ repo / ".herdr-wt" / name,+ _box(f"devbox-test-user-{name}", git_dir=common / "worktrees" / name, worktree_id=f"id-{name}"),+ )+ cleaned: list[tuple[list[str], str, bool]] = []+ monkeypatch.setattr(+ worktrees,+ "_clean_worktree_boxes",+ lambda boxes, action, keep_stopped_records=False: cleaned.append(+ ([b.workspace for b in boxes], action, keep_stopped_records)+ ),+ )++ worktrees.prune_boxes_of_removed_worktrees(+ repo, "stop", None if path_arg is None else tmp_path / path_arg, dry_run=False+ )++ assert cleaned == [(expected_workspaces, "stop", False)]++ @pytest.mark.parametrize(+ ("same_worktree", "background", "keep_record", "expected_calls"),+ [+ (True, False, False, ["mirror", "stop"]),+ (True, False, True, ["mirror", "stop:keeps-record"]),+ (True, True, False, ["mirror", "background:stop"]),+ (False, False, False, []),+ ],+ ids=[+ "own-box",+ "own-box-of-an-archived-worktree",+ "own-box-in-the-background",+ "box-of-an-earlier-worktree-at-the-path",+ ],+ )+ def test_teardown_stops_the_mirror_before_acting_on_its_own_box(+ self, tmp_path, monkeypatch, same_worktree: bool, background: bool, keep_record: bool, expected_calls: list[str]+ ) -> None:+ worktree = tmp_path / "wt"+ admin = tmp_path / "admin"+ admin.mkdir()+ worktree_id = devbox_config.ensure_worktree_id(admin)+ monkeypatch.setattr(devbox_config, "get_worktree_boxes_path", lambda: tmp_path / "boxes.json")+ devbox_config.record_worktree_box(+ worktree,+ _box(+ "devbox-test-user-wt",+ git_dir=admin,+ worktree_id=worktree_id if same_worktree else "id-of-an-earlier-worktree",+ ),+ )+ calls: list[str] = []+ monkeypatch.setattr(worktrees.mutagen, "sync_terminate", lambda selector: calls.append("mirror"))+ monkeypatch.setattr(+ worktrees,+ "_clean_worktree_boxes",+ lambda boxes, action, keep_stopped_records=False: calls.append(+ f"{action}:keeps-record" if keep_stopped_records else action+ ),+ )++ act_on_box = (lambda box, action: calls.append(f"background:{action}")) if background else None++ box = worktrees.teardown_worktree_box(+ worktree, admin, "stop", dry_run=False, keep_record=keep_record, act_on_box=act_on_box+ )++ assert (box is not None) is same_worktree+ assert calls == expected_calls++ @pytest.mark.parametrize(+ ("registered_worktree_id", "expected_cleaned"),+ [("id-checked-by-teardown", ["devbox-test-user-wt"]), ("id-of-a-worktree-recreated-since", [])],+ ids=["box-still-held", "box-taken-over-by-a-recreated-worktree"],+ )+ def test_background_box_action_skips_a_box_taken_over_since_the_teardown(+ self, tmp_path, monkeypatch, registered_worktree_id: str, expected_cleaned: list[str]+ ) -> None:+ worktree = tmp_path / "wt"+ monkeypatch.setattr(devbox_config, "get_worktree_boxes_path", lambda: tmp_path / "boxes.json")+ devbox_config.record_worktree_box(worktree, _box("devbox-test-user-wt", worktree_id=registered_worktree_id))+ cleaned: list[str] = []+ monkeypatch.setattr(+ worktrees,+ "_clean_worktree_boxes",+ lambda boxes, action, keep_stopped_records=False: cleaned.extend(box.workspace for box in boxes),+ )++ worktrees.clean_registered_box(worktree, "id-checked-by-teardown", "stop", keep_record=False)++ assert cleaned == expected_cleaned++ @pytest.mark.parametrize(+ ("action", "status", "live_id", "last_used_at", "keep_stopped", "expected_calls"),+ [+ ("delete", "running", "id-a", None, False, [("delete", "devbox-test-user-a")]),+ ("stop", "running", "id-a", None, False, [("stop", "devbox-test-user-a")]),+ ("stop", "stopped", "id-a", None, False, []),+ ("delete", "running", "id-recreated", None, False, []),+ ("delete", "running", "id-a", "2026-01-01T00:00:00.123456789Z", False, [("delete", "devbox-test-user-a")]),+ ("delete", "running", "id-a", "2026-03-01T00:00:00Z", False, []),+ ("delete", "running", "id-a", "", False, []),+ ("stop", "running", "id-a", None, True, [("stop", "devbox-test-user-a")]),+ ("delete", "running", "id-a", None, True, [("delete", "devbox-test-user-a")]),],ids=["delete",@@ -600,10 +711,12 @@ class TestWorktreeBoxes:"idle-past-cutoff","used-after-cutoff-kept","unknown-last-use-kept",+ "stopped-box-keeps-its-record-for-a-recreated-worktree",+ "deleted-box-forgotten-even-when-keeping-stopped",],)def test_acts_on_existing_box_and_forgets_it(- self, tmp_path, monkeypatch, registry_path, action, status, live_id, last_used_at, expected_calls+ self, tmp_path, monkeypatch, registry_path, action, status, live_id, last_used_at, keep_stopped, expected_calls) -> None:calls: list[tuple[str, str]] = []terminated: list[str] = []@@ -627,13 +740,14 @@ class TestWorktreeBoxes:WorktreeBox(worktree_path=tmp_path / "b", record=box_b),],action,+ keep_stopped_records=keep_stopped,**({} if last_used_at is None else {"idle_before": datetime(2026, 2, 1, tzinfo=UTC).timestamp()}),)assert calls == expected_callsacted = 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+ kept = live_id == box_a.workspace_id and (not acted or (keep_stopped and action == "stop"))assert devbox_config.load_worktree_boxes() == ({str(tmp_path / "a"): box_a} if kept else {})@pytest.mark.parametrize(diff --git a/tools/hogli-commands/hogli_commands/worktrees.py b/tools/hogli-commands/hogli_commands/worktrees.pyindex a73fde89392f..238faec20ea0 100644--- a/tools/hogli-commands/hogli_commands/worktrees.py+++ b/tools/hogli-commands/hogli_commands/worktrees.py@@ -541,6 +541,83 @@ def _boxes_of_removed_worktrees(return boxes+def prune_boxes_of_removed_worktrees(+ repo_root: Path, box_action: str, worktree_path: Path | None, dry_run: bool+) -> list[WorktreeBox]:+ """Act on the boxes of this repo's worktrees that another tool already removed, or only the one at *worktree_path*.++ `worktrees:clean` covers worktrees it removes itself. t3code and herdr remove+ their own, so their boxes are found here by the same rule.+ """+ boxes = _boxes_of_removed_worktrees(load_worktree_boxes(), repo_root, _git_common_dir(repo_root), None)+ if worktree_path is not None:+ boxes = [box for box in boxes if _resolve(box.worktree_path) == _resolve(worktree_path)]+ 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:+ click.echo(f"[DRY-RUN] Would {box_action} them.")+ else:+ _clean_worktree_boxes(boxes, box_action)+ return boxes+++def teardown_worktree_box(+ worktree_path: Path,+ git_dir: Path,+ box_action: str,+ dry_run: bool,+ keep_record: bool = False,+ act_on_box: Callable[[WorktreeBox, str], None] | None = None,+) -> WorktreeBox | None:+ """Stop the mirror and act on the box of the worktree at *worktree_path*, which a tool is about to remove.++ The mirror stops first, while the files still exist, for the reason in+ `_stop_worktree_mirrors`. The record is found by the ID in *git_dir*, so a+ moved worktree still finds its box, and a record saved for an earlier+ worktree at the same path does not match. *keep_record* keeps the record+ of a stopped box, for a tool that keeps the worktree and can restore it.+ *act_on_box* replaces the box action, so a caller can move it out of a+ tool's hook time limit.+ """+ worktree_id = read_worktree_id(git_dir)+ match = next(+ (+ (Path(path), record)+ for path, record in load_worktree_boxes().items()+ if worktree_id is not None and record.worktree_id == worktree_id+ ),+ None,+ )+ if match is None:+ return None+ box = WorktreeBox(worktree_path=match[0], record=match[1], current_path=worktree_path)+ if dry_run:+ click.echo(f"[DRY-RUN] Would stop the sync mirror and {box_action} {box.workspace}.")+ return box+ _stop_worktree_mirrors([box])+ if act_on_box is None:+ _clean_worktree_boxes([box], box_action, keep_stopped_records=keep_record)+ else:+ act_on_box(box, box_action)+ return box+++def clean_registered_box(worktree_path: Path, worktree_id: str, box_action: str, keep_record: bool) -> None:+ """Act on the box registered for *worktree_path*, if the worktree with *worktree_id* still holds it.++ A worktree recreated at the same path can take the box over before this+ runs, and its record then carries its own ID.+ """+ record = load_worktree_boxes().get(str(worktree_path))+ if record is not None and record.worktree_id == worktree_id:+ _clean_worktree_boxes(+ [WorktreeBox(worktree_path=worktree_path, record=record)], box_action, keep_stopped_records=keep_record+ )++def _clean_boxes_of_removed_worktrees(boxes: list[WorktreeBox], box_action: str, cutoff: float, dry_run: bool, yes: bool) -> None:@@ -607,16 +684,28 @@ def _box_last_used(workspace: Mapping[str, object]) -> float | None:return None-def _clean_worktree_boxes(boxes: list[WorktreeBox], box_action: str, idle_before: float = float("inf")) -> None:+def _clean_worktree_boxes(+ boxes: list[WorktreeBox],+ box_action: str,+ idle_before: float = float("inf"),+ keep_stopped_records: bool = False,+) -> None:+ """Stop or delete *boxes* and forget their records.++ With *keep_stopped_records*, a box that ends up stopped keeps its record, so+ the worktree can start it again when a tool restores it.+ """hogland_boxes = [box for box in boxes if box.record.provider == "hogland"]coder_boxes = [box for box in boxes if box.record.provider != "hogland"]if hogland_boxes:- _clean_hogland_boxes(hogland_boxes, box_action, idle_before)+ _clean_hogland_boxes(hogland_boxes, box_action, idle_before, keep_stopped_records)if coder_boxes:- _clean_coder_boxes(coder_boxes, box_action, idle_before)+ _clean_coder_boxes(coder_boxes, box_action, idle_before, keep_stopped_records)-def _clean_hogland_boxes(boxes: list[WorktreeBox], box_action: str, idle_before: float) -> None:+def _clean_hogland_boxes(+ boxes: list[WorktreeBox], box_action: str, idle_before: float, keep_stopped_records: bool+) -> None:try:hogland.ensure_cli()devboxes = hogland.fetch_devboxes()@@ -660,11 +749,14 @@ def _clean_hogland_boxes(boxes: list[WorktreeBox], box_action: str, idle_before:command = "delete" if box_action == "delete" else "hibernate"click.echo(f" ⚠️ could not {box_action} {box.workspace}. Run `hogland devbox {command} {box.workspace}`.")continue- handled.append(box.worktree_path)+ if box_action == "delete" or not keep_stopped_records:+ handled.append(box.worktree_path)forget_worktree_boxes(handled)-def _clean_coder_boxes(boxes: list[WorktreeBox], box_action: str, idle_before: float) -> None:+def _clean_coder_boxes(+ boxes: list[WorktreeBox], box_action: str, idle_before: float, keep_stopped_records: bool+) -> None:try:ensure_runtime_ready()except SystemExit:@@ -712,7 +804,8 @@ def _clean_coder_boxes(boxes: list[WorktreeBox], box_action: str, idle_before: flabel = 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)+ if box_action == "delete" or not keep_stopped_records:+ handled.append(box.worktree_path)forget_worktree_boxes(handled)