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(hogli): point at worktrees:clean when disk runs low (#122355)

Georges-Antoine Assif894b3f1e28e
diff --git a/bin/posthog-worktree b/bin/posthog-worktree
index 4a5578cd8589..f9650a044539 100755
--- a/bin/posthog-worktree
+++ b/bin/posthog-worktree
@@ -300,6 +300,7 @@ setup_worktree_environment() {
print_color blue " bin/start"
echo ""
print_color yellow "Tip: only running the app needs this full setup — for edit+commit work, plain 'git worktree add' is enough (hooks borrow the main clone's toolchain)."
+ print_color yellow "Each worktree takes several GB. To see which old worktrees you can clear, run 'hogli worktrees:clean --before 7d --mode deps --dry-run'."
}
# Function to list all worktrees
diff --git a/docs/published/handbook/engineering/flox-multi-instance-workflow.md b/docs/published/handbook/engineering/flox-multi-instance-workflow.md
index b337c446beab..c43e70880c16 100644
--- a/docs/published/handbook/engineering/flox-multi-instance-workflow.md
+++ b/docs/published/handbook/engineering/flox-multi-instance-workflow.md
@@ -402,6 +402,8 @@ phw remove haacked/old-feature
git worktree prune
```
+To clear old `phw`, Claude Code, Codex, and PostHog Code worktrees in bulk, run `hogli worktrees:clean --before 7d --mode deps --dry-run` to preview, then drop `--dry-run`, or use `--mode full` to remove whole worktrees.
+
## Quick Setup Script
For a complete one-time setup, run:
diff --git a/hogli.yaml b/hogli.yaml
index b49672a05ec6..83eb87dcdc19 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -351,6 +351,10 @@ start:
- kafka
- clickhouse
- temporal
+ prechecks:
+ - type: worktree_disk
+ min_free_gib: 20
+ max_worktrees: 3
up:
extends: start
description: Alias for `hogli start`; use `-d` for optional detached mode
@@ -1147,7 +1151,7 @@ utilities:
prompt: true
worktrees:clean:
click: hogli_commands.worktrees:worktrees_clean
- description: Clear out unused Claude Code / Codex / PostHog Desktop worktrees by age
+ description: Clear out unused Claude Code / Codex / PostHog Desktop / phw worktrees by age
pr:upload-image:
click: hogli_commands.upload_image:upload_image
description: Upload screenshot(s) to the public PostHog/pr-assets repo and print embeddable PR markdown
diff --git a/tools/hogli-commands/hogli_commands/prechecks.py b/tools/hogli-commands/hogli_commands/prechecks.py
index 782d3009dd41..569b2711ec63 100644
--- a/tools/hogli-commands/hogli_commands/prechecks.py
+++ b/tools/hogli-commands/hogli_commands/prechecks.py
@@ -8,8 +8,23 @@ inside the handler — keep this module light to import.
from __future__ import annotations
+import os
+import shutil
+import subprocess
+from typing import Any
+
import click
from hogli.hooks import register_precheck
+from hogli.manifest import REPO_ROOT
+
+from hogli_commands.telemetry_props import _detect_environment
+
+_GIB = 1024**3
+_DEFAULT_MIN_FREE_GIB = 20.0
+_DEFAULT_MAX_WORKTREES = 3
+_MIN_FREE_GIB_ENV = "HOGLI_WORKTREE_DISK_MIN_FREE_GIB"
+_MAX_WORKTREES_ENV = "HOGLI_WORKTREE_DISK_MAX_WORKTREES"
+_CLEAN_PREVIEW_COMMAND = "hogli worktrees:clean --before 7d --mode deps --dry-run"
def _migrations_precheck(check: dict, yes: bool) -> bool | None:
@@ -47,4 +62,63 @@ def _migrations_precheck(check: dict, yes: bool) -> bool | None:
return None
+def should_warn_about_worktree_disk(
+ free_bytes: int, linked_worktrees: int, min_free_gib: float, max_worktrees: int
+) -> bool:
+ return free_bytes < min_free_gib * _GIB and linked_worktrees > max_worktrees
+
+
+def _threshold(env_var: str, configured: Any, default: float) -> float:
+ for candidate in (os.environ.get(env_var), configured):
+ if candidate is None or candidate == "":
+ continue
+ try:
+ return float(candidate)
+ except (TypeError, ValueError):
+ continue
+ return default
+
+
+def _count_linked_worktrees() -> int | None:
+ try:
+ porcelain = subprocess.run(
+ ["git", "worktree", "list", "--porcelain"],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ timeout=5,
+ check=True,
+ ).stdout
+ except (subprocess.SubprocessError, OSError):
+ return None
+ all_worktrees = sum(1 for line in porcelain.splitlines() if line.startswith("worktree "))
+ return max(0, all_worktrees - 1)
+
+
+def _worktree_disk_precheck(check: dict, yes: bool) -> None:
+ """Point at `hogli worktrees:clean` when free disk is low and many worktrees exist. Never blocks."""
+ try:
+ if _detect_environment() == "ci" or os.environ.get("POSTHOG_TASK_RUN_ID"):
+ return None
+ min_free_gib = _threshold(_MIN_FREE_GIB_ENV, check.get("min_free_gib"), _DEFAULT_MIN_FREE_GIB)
+ max_worktrees = int(_threshold(_MAX_WORKTREES_ENV, check.get("max_worktrees"), _DEFAULT_MAX_WORKTREES))
+ free_bytes = shutil.disk_usage(REPO_ROOT).free
+ if free_bytes >= min_free_gib * _GIB:
+ return None
+ linked_worktrees = _count_linked_worktrees()
+ if linked_worktrees is None:
+ return None
+ if should_warn_about_worktree_disk(free_bytes, linked_worktrees, min_free_gib, max_worktrees):
+ click.secho(
+ f"⚠️ {free_bytes / _GIB:.1f} GiB free on this disk and {linked_worktrees} git worktrees exist. "
+ f"See what you can reclaim with `{_CLEAN_PREVIEW_COMMAND}`.",
+ fg="yellow",
+ err=True,
+ )
+ except Exception:
+ pass
+ return None
+
+
register_precheck("migrations", _migrations_precheck)
+register_precheck("worktree_disk", _worktree_disk_precheck)
diff --git a/tools/hogli-commands/hogli_commands/tests/test_prechecks.py b/tools/hogli-commands/hogli_commands/tests/test_prechecks.py
new file mode 100644
index 000000000000..c5591c9d002a
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/tests/test_prechecks.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+import pytest
+
+from hogli_commands.prechecks import should_warn_about_worktree_disk
+
+_GIB = 1024**3
+
+
+ ("free_bytes", "linked_worktrees", "expected"),
+ [
+ pytest.param(5 * _GIB, 8, True, id="low_disk_many_worktrees"),
+ pytest.param(20 * _GIB - 1, 4, True, id="just_under_threshold"),
+ pytest.param(20 * _GIB, 8, False, id="exactly_at_threshold"),
+ pytest.param(20 * 10**9, 8, True, id="decimal_gb_is_below_gib_threshold"),
+ pytest.param(100 * _GIB, 8, False, id="plenty_of_disk"),
+ pytest.param(5 * _GIB, 3, False, id="worktrees_at_limit"),
+ pytest.param(5 * _GIB, 0, False, id="no_worktrees"),
+ ],
+)
+def test_should_warn_about_worktree_disk(free_bytes: int, linked_worktrees: int, expected: bool) -> None:
+ assert should_warn_about_worktree_disk(free_bytes, linked_worktrees, min_free_gib=20, max_worktrees=3) is expected
diff --git a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py b/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
index 94bfe8ab6e04..6d6e58d39e8a 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
@@ -12,6 +12,7 @@ from hogli_commands.worktrees import (
_belongs_to_repo,
_collect_deps_items,
_compute_git_state,
+ _discover_root_worktrees,
_du_sizes,
_execute,
_include_orphans,
@@ -20,6 +21,7 @@ from hogli_commands.worktrees import (
_reclaimed_bytes,
_registered_worktrees,
_resolve_orphan_policy,
+ _worktree_roots,
)
@@ -121,6 +123,36 @@ class TestBelongsToRepo:
assert not _belongs_to_repo(wt.resolve(), (tmp_path / "main").resolve(), (tmp_path / "main" / ".git").resolve())
+class TestWorktreeRoots:
+ @pytest.mark.parametrize(
+ "override_base,branch,registered",
+ [
+ (True, "haacked/new-feature", False),
+ (False, "haacked/new-feature", False),
+ (False, "alice/feature/disk", True),
+ ],
+ ids=["posthog_worktree_base", "default_home_base", "registered_three_segment_branch"],
+ )
+ def test_phw_branch_worktree_is_discovered(
+ self, tmp_path, monkeypatch, override_base: bool, branch: str, registered: bool
+ ) -> None:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path / "home")
+ if override_base:
+ base = tmp_path / "custom"
+ monkeypatch.setenv("POSTHOG_WORKTREE_BASE", str(base))
+ else:
+ base = tmp_path / "home" / ".worktrees" / "posthog"
+ monkeypatch.delenv("POSTHOG_WORKTREE_BASE", raising=False)
+ wt = base / branch
+ wt.mkdir(parents=True)
+ (wt / ".git").write_text("gitdir: /nowhere\n")
+ registry = {wt.resolve(): {"locked": False, "branch": branch}} if registered else {}
+
+ roots = dict(_worktree_roots(tmp_path / "repo"))
+
+ assert [p.resolve() for p in _discover_root_worktrees(roots["phw"], registry)] == [wt.resolve()]
+
+
class TestCollectDepsItems:
def test_never_escapes_worktree_via_symlinked_parent(self, tmp_path) -> None:
worktree = tmp_path / "wt"
diff --git a/tools/hogli-commands/hogli_commands/worktrees.py b/tools/hogli-commands/hogli_commands/worktrees.py
index 6569957c2a94..ae998da3ca0d 100644
--- a/tools/hogli-commands/hogli_commands/worktrees.py
+++ b/tools/hogli-commands/hogli_commands/worktrees.py
@@ -1,4 +1,4 @@
-"""Clean up unused agent worktrees (Claude Code, Codex, PostHog Desktop).
+"""Clean up unused agent and phw worktrees (Claude Code, Codex, PostHog Desktop, phw).
These tools each create throwaway git worktrees that accumulate over time. A
single PostHog worktree carries multi-GB `node_modules`, Python venvs, and Rust
@@ -43,11 +43,15 @@ from .doctor import _format_size
# Roots that hold agent-created worktrees, keyed by the tool that owns them.
# Claude Code and Codex nest worktrees directly under the repo; PostHog Desktop
# keeps them in the home directory as <id>/posthog. Returned as (source, root).
+# The phw root must match WORKTREE_BASE in bin/posthog-worktree, including its
+# POSTHOG_WORKTREE_BASE override.
def _worktree_roots(repo_root: Path) -> list[tuple[str, Path]]:
+ phw_base = os.environ.get("POSTHOG_WORKTREE_BASE") or str(Path.home() / ".worktrees" / "posthog")
return [
("claude", repo_root / ".claude" / "worktrees"),
("codex", repo_root / ".codex" / "worktrees"),
("posthog-code", Path.home() / ".posthog-code" / "worktrees"),
+ ("phw", Path(phw_base).expanduser()),
]
@@ -131,7 +135,7 @@ class Worktree:
@click.command(
name="worktrees:clean",
- help="Clear out unused Claude Code / Codex / PostHog Desktop worktrees by age",
+ help="Clear out unused Claude Code / Codex / PostHog Desktop / phw worktrees by age",
)
@click.option(
"--before",
@@ -150,8 +154,8 @@ class Worktree:
"--source",
"sources",
multiple=True,
- type=click.Choice(["claude", "codex", "posthog-code"], case_sensitive=False),
- help="Restrict to specific tool(s). Repeatable. Default: all three.",
+ type=click.Choice(["claude", "codex", "posthog-code", "phw"], case_sensitive=False),
+ help="Restrict to specific tool(s). Repeatable. Default: all of them.",
)
@click.option(
"--repo",
@@ -221,7 +225,7 @@ def worktrees_clean(
for source, root in _worktree_roots(repo_root):
if selected_sources is not None and source not in selected_sources:
continue
- for path in _discover_worktrees(root):
+ for path in _discover_root_worktrees(root, registry):
resolved = _resolve(path)
if resolved in protected:
continue
@@ -457,6 +461,16 @@ def _discover_worktrees(root: Path, max_depth: int = 2) -> list[Path]:
return found
+def _discover_root_worktrees(root: Path, registry: dict[Path, dict]) -> list[Path]:
+ found = _discover_worktrees(root)
+ seen = {_resolve(path) for path in found}
+ resolved_root = _resolve(root)
+ for path in registry:
+ if path not in seen and path != resolved_root and _is_under(path, resolved_root) and path.is_dir():
+ found.append(path)
+ return found
+
+
def _registered_worktrees(repo_root: Path) -> dict[Path, dict] | None:
"""Map resolved worktree path -> {locked, branch} from `git worktree list`.