: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
refactor(hogli): lazy-load Click commands via manifest (#57315)
Raúl Negrón-Otero117db5c019af
diff --git a/.agents/skills/hogli/SKILL.md b/.agents/skills/hogli/SKILL.mdindex ad2ff7ebee2f..cacb94400ccf 100644--- a/.agents/skills/hogli/SKILL.md+++ b/.agents/skills/hogli/SKILL.md@@ -19,6 +19,6 @@ Run `hogli --help` to get the full, current command list. Run `hogli <command> -## Key references- `hogli.yaml` — command definitions (source of truth)-- `tools/hogli-commands/hogli_commands/commands.py` — extension point for custom Click commands+- `tools/hogli-commands/hogli_commands/` — PostHog-specific lazy Click command modules- `tools/hogli/README.md` — framework documentation- `tools/hogli-commands/README.md` — PostHog commands documentationdiff --git a/hogli.yaml b/hogli.yamlindex 687af8977e89..8664758e4196 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -1,6 +1,13 @@config:description: Unified developer experience for the PostHog monorepo.commands_dir: tools/hogli-commands/hogli_commands+ # Imported once at startup to register precheck handlers, telemetry property+ # hooks, and post-command hooks. Keep these modules cheap to import — heavy+ # dependencies must live behind lazy imports inside handler bodies.+ boot_modules:+ - hogli_commands.prechecks+ - hogli_commands.telemetry_props+ - hogli_commands.hint_hookscripts_exclude:- mprocs.yaml- mprocs-test.yaml@@ -113,29 +120,85 @@ metadata:name: phrocsabout: PostHog's custom process runner (replaces mprocs).devbox:- devbox: null- devbox:setup: null- devbox:start: null- devbox:stop: null- devbox:restart: null- devbox:update: null- devbox:list: null- devbox:ssh: null- devbox:open: null- devbox:logs: null- devbox:destroy: null- devbox:status: null- devbox:forward: null- devbox:users: null- devbox:share: null- devbox:cleanup:disk: null- devbox:task: null+ devbox:+ click: hogli_commands.devbox.cli:devbox_help+ description: Show available devbox commands+ devbox:setup:+ click: hogli_commands.devbox.cli:devbox_setup+ description: Install and configure local access to Coder devboxes+ devbox:start:+ click: hogli_commands.devbox.cli:devbox_start+ description: Start or create your remote devbox+ devbox:stop:+ click: hogli_commands.devbox.cli:devbox_stop+ description: Stop your devbox (preserves disk, stops billing)+ devbox:restart:+ click: hogli_commands.devbox.cli:devbox_restart+ description: Restart your devbox+ devbox:update:+ click: hogli_commands.devbox.cli:devbox_update+ description: Update devbox to the latest template+ devbox:list:+ click: hogli_commands.devbox.cli:devbox_list+ description: List your devboxes+ devbox:ssh:+ click: hogli_commands.devbox.cli:devbox_ssh+ description: SSH into your devbox+ devbox:open:+ click: hogli_commands.devbox.cli:devbox_open+ description: Open devbox in browser, VS Code, or Cursor+ devbox:logs:+ click: hogli_commands.devbox.cli:devbox_logs+ description: Tail devbox build and agent logs+ devbox:destroy:+ click: hogli_commands.devbox.cli:devbox_destroy+ description: Destroy your devbox and its data+ devbox:status:+ click: hogli_commands.devbox.cli:devbox_status+ description: Show devbox status+ devbox:forward:+ click: hogli_commands.devbox.cli:devbox_forward+ description: Forward PostHog UI to localhost+ devbox:users:+ click: hogli_commands.devbox.cli:devbox_users+ description: List Coder users (for devbox sharing)+ devbox:share:+ click: hogli_commands.devbox.cli:devbox_share+ description: Share your devbox with other users+ devbox:unshare:+ click: hogli_commands.devbox.cli:devbox_unshare+ description: Revoke access to your devbox from other users+ devbox:cleanup:disk:+ click: hogli_commands.devbox.cli:devbox_cleanup_disk+ description: Free disk space by cleaning caches and build artifacts+ devbox:task:+ click: hogli_commands.devbox.cli:devbox_task+ description: Run a background agent task on a fresh devboxdevenv:- dev:setup: null- dev:generate: null- dev:explain: null- dev:intents: null+ dev:setup:+ click: hogli_commands.devenv.cli:dev_setup+ description: Interactive wizard to configure your dev environment+ dev:generate:+ click: hogli_commands.devenv.cli:dev_generate+ description: Regenerate mprocs config from saved settings+ dev:explain:+ click: hogli_commands.devenv.cli:dev_explain+ description: Show what services would be started for intents+ dev:intents:+ click: hogli_commands.devenv.cli:dev_intents+ description: List available intents+ dev:list-units:+ click: hogli_commands.devenv.cli:dev_list_units+ description: List autostart units for given intents (used by phrocs)+ hidden: true+ dev:apply:+ click: hogli_commands.devenv.cli:dev_apply+ description: Apply intent config non-interactively (used by phrocs)+ hidden: truecore:+ quickstart:+ click: hogli_commands.quickstart:quickstart+ description: Show getting started with PostHog developmentcategories:description: Show all available commands grouped by categorydev:up:@@ -317,7 +380,9 @@ deploy:\ exports -n # Dry run exports only"prompt: truebuild:- build: null # Click-defined command; placed here for help categorization+ build:+ click: hogli_commands.build:build+ description: Run code generation pipelines (smart change detection by default)build:frontend:cmd: pnpm --filter=@posthog/frontend builddescription: Build frontend packages and run TypeScript compilation@@ -405,6 +470,9 @@ build:cmd: python products/posthog_ai/scripts/build_skills.py --sync --cleandescription: Remove a previously synced skill from .agents/skills/docker:+ docker:services:up:+ click: hogli_commands.devenv.cli:docker_services_up+ description: Start Docker services based on your intent configdocker:services:down:cmd: docker compose -f docker-compose.dev.yml downdescription: Stop Docker infrastructure services@@ -481,6 +549,21 @@ migrations:services:- postgresql- clickhouse+ migrations:status:+ click: hogli_commands.migrations:migrations_status+ description: Show migration diff between database and code+ migrations:down:+ click: hogli_commands.migrations:migrations_down+ description: Roll back orphaned migrations+ migrations:up:+ click: hogli_commands.migrations:migrations_up+ description: Apply pending migrations+ migrations:sync:+ click: hogli_commands.migrations:migrations_sync+ description: 'Sync migrations: roll back orphaned, apply pending'+ migrations:cache-sync:+ click: hogli_commands.migrations:migrations_cache_sync+ description: Populate cache from currently applied migrationsdb:db:pg:cmd: psql postgres://posthog:posthog@localhost:5432/posthog@@ -611,6 +694,9 @@ db:- postgresql- dockertests:+ test:+ click: hogli_commands.test_runner:test_command+ description: Auto-detect test type (Python, Jest, Playwright, Rust, Go) and run ittest:python:cmd: pytestdescription: Run Python test suite@@ -668,12 +754,37 @@ quality:cmd: pnpm run --filter @posthog/mcp formatdescription: Format MCP filesauth:- metabase:login: null # Click-defined, placed here for categorization- metabase:cookie: null # Click-defined, placed here for categorization- metabase:databases: null # Click-defined, placed here for categorization- metabase:query: null # Click-defined, placed here for categorization+ metabase:login:+ click: hogli_commands.metabase:metabase_login+ description: Log in to Metabase via SSO and cache the session cookie+ metabase:cookie:+ click: hogli_commands.metabase:metabase_cookie+ description: Print the cached Metabase cookie header+ metabase:databases:+ click: hogli_commands.metabase:metabase_databases+ description: List Metabase databases (id, name, engine) for a region+ metabase:query:+ click: hogli_commands.metabase:metabase_query+ description: Run a SQL query against Metabase /api/dataset; results to stdouttools:- doctor: null # Click-defined, placed here for categorization+ doctor:+ click: hogli_commands.doctor:doctor+ description: Quick health check for your dev environment+ doctor:disk:+ click: hogli_commands.doctor:doctor_disk+ description: Interactive disk space cleanup for common PostHog dev bloat+ doctor:zombies:+ click: hogli_commands.doctor:doctor_zombies+ description: Find and kill orphaned PostHog dev processes+ product:bootstrap:+ click: hogli_commands.product.cli:cmd_bootstrap+ description: Scaffold a new product with canonical structure+ product:lint:+ click: hogli_commands.product.cli:cmd_lint+ description: Check product structure for misplaced files+ product:maturity:+ click: hogli_commands.product.cli:cmd_maturity+ description: Score product maturity across isolation dimensionstool:temporal-codec-server:bin_script: temporal-codec-serverdescription: Run a local Temporal codec server to decode Fernet payloads for debugging@@ -850,10 +961,13 @@ environment:cmd: uv sync --activedescription: Install Python dependencies to active virtual environmenttelemetry:on:+ click: hogli_commands.telemetry_commands:telemetry_ondescription: Enable anonymous usage telemetrytelemetry:off:+ click: hogli_commands.telemetry_commands:telemetry_offdescription: Disable anonymous usage telemetrytelemetry:status:+ click: hogli_commands.telemetry_commands:telemetry_statusdescription: Show current telemetry settingssandbox:bin_script: sandboxdiff --git a/tools/hogli-commands/README.md b/tools/hogli-commands/README.mdindex f17b4d584c81..bd6636749b17 100644--- a/tools/hogli-commands/README.md+++ b/tools/hogli-commands/README.md@@ -1,33 +1,41 @@# PostHog Custom Commands-Custom Python commands for the PostHog monorepo. These extend hogli with PostHog-specific functionality that's too complex for YAML definitions.+Custom Python commands for the PostHog monorepo. They extend hogli with PostHog-specific functionality that's too complex for YAML definitions.## How It Works-This directory is loaded automatically via `config.commands_dir` in `/hogli.yaml`. Any command decorated with `@cli.command()` is registered and available via `hogli <command>`.+Each command module is imported **on first use**, not at hogli startup. The hogli framework reads `config.commands_dir` from `/hogli.yaml`; manifest entries with a `click:` field are resolved by Click when the user invokes the command or runs per-command `--help`.++Boot-time registrations (precheck handlers, telemetry hooks, post-command hooks) live in their own modules listed under `config.boot_modules:` in `hogli.yaml`. Those modules **must** be cheap to import — keep heavy dependencies behind deferred imports inside handler bodies.## Adding a Command-1. Create a new file or add to an existing one:+1. Create or edit a module with a plain `@click.command(...)` decorator (no need to import or reference hogli's `cli` group):```python# myfeature.pyimport click-from hogli.cli import cli[email protected](name="my:command")[email protected](name="my:command")@click.option("--verbose", "-v", is_flag=True)def my_command(verbose: bool) -> None:"""One-line description shown in hogli --help."""click.echo("Done!")```-2. Import it in `commands.py`:+2. Add an entry to `hogli.yaml` in the appropriate category section:-```python-from . import myfeature # noqa: F401+```yaml+tools:+ my:command:+ click: hogli_commands.myfeature:my_command+ description: One-line summary shown in `hogli --help`.```+The Click command name must match the manifest key — drift surfaces as a `ClickException` on resolution. The hogli test suite parametrizes a `--help` invocation over every `click:` entry, which is Click's recommended sanity check.++Mark a command hidden by setting `hidden: true` on the manifest entry. Don't use `@click.command(hidden=True)`; the manifest is the only source of truth.+3. Test it:```bash@@ -35,15 +43,17 @@ hogli my:command --helphogli my:command -v```-## Framework Hooks This Package Registers+That's it. No side-effect imports, no central registration list to maintain.++## Boot Modules-On top of `@cli.command` definitions, `commands.py` also registers into hogli's extension hook API (`hogli.hooks`):+`config.boot_modules` in `hogli.yaml` lists modules imported once at startup. They register hooks via `hogli.hooks`:-- **Precheck** `migrations` — detects orphaned migrations before `dev:start` and prompts to sync.-- **Telemetry properties** — adds PostHog-specific environment props (`in_flox`, `is_worktree`, `is_posthog_dev`, `process_manager`, `has_devenv_config`) to every `command_completed` event.-- **Post-command hook** — shows a contextual hint (`hogli.hints`) after successful commands.+- `hogli_commands.prechecks` — declares the `migrations` precheck (used by `dev:start`).+- `hogli_commands.telemetry_props` — adds PostHog environment props (`in_flox`, `is_worktree`, `is_posthog_dev`, `process_manager`, `has_devenv_config`) to every `command_completed` event.+- `hogli_commands.hint_hook` — shows a contextual hint after successful commands.-That's why `commands.py` has top-level `register_*` calls alongside the command imports. See `tools/hogli/README.md` for the hook API.+Add a new boot module by creating a file that calls one of the `register_*` helpers from `hogli.hooks` at import time, then list it under `config.boot_modules:`. Keep these modules import-light: the precheck handler in `prechecks.py` is the canonical example of deferring its heavy import until the handler actually fires.## When to Use Python vs YAML@@ -57,22 +67,31 @@ That's why `commands.py` has top-level `register_*` calls alongside the command## File Structure```text-tools/hogli-commands/hogli_commands/-├── __init__.py # Package init (imports commands.py)-├── commands.py # Imports all command modules-├── doctor.py # Health/cleanup commands-└── README.md # This file+tools/hogli-commands/+└── hogli_commands/+ ├── __init__.py # Only the common/ sys.path workaround+ ├── prechecks.py # Boot module — registers the migrations precheck+ ├── telemetry_props.py# Boot module — registers PostHog telemetry props+ ├── hint_hook.py # Boot module — registers the post-command hint hook+ ├── build.py # Lazy: hogli build+ ├── doctor.py # Lazy: hogli doctor / doctor:disk / doctor:zombies+ ├── ... # Other lazy command modules+ ├── devbox/ # Devbox subpackage (lazy)+ ├── devenv/ # Intent-based dev environment subpackage (lazy)+ └── product/ # Product scaffolding subpackage (lazy)```+This directory is not packaged or installed — the hogli framework loads `hogli_commands` from disk at runtime via `config.commands_dir` in `/hogli.yaml`. Runtime dependencies (`click`, `pyyaml`, `pydantic`, `requests`) are declared in the root `/pyproject.toml` alongside the rest of the monorepo.+## Tips- Use `click.echo()` for output, not `print()`- Use `click.secho(msg, fg="green")` for colored output- Add `@click.option("--yes", "-y", is_flag=True)` for destructive commands-- Keep commands focused - compose via YAML `steps:` if needed+- Keep commands focused — compose via YAML `steps:` if needed## See Also-- `/hogli.yaml` - YAML command definitions-- `/tools/hogli/README.md` - Framework documentation-- `/bin/` - Shell scripts (used via `bin_script:` in YAML)+- `/hogli.yaml` — manifest with category placement, lazy `click:` import paths, and `boot_modules:` list+- `/tools/hogli/README.md` — framework documentation (command registry, hooks API)+- `/bin/` — shell scripts (referenced via `bin_script:` in YAML)diff --git a/tools/hogli-commands/hogli_commands/__init__.py b/tools/hogli-commands/hogli_commands/__init__.pyindex afe573dcc604..5024a4e16586 100644--- a/tools/hogli-commands/hogli_commands/__init__.py+++ b/tools/hogli-commands/hogli_commands/__init__.py@@ -1,20 +1,9 @@-"""PostHog-specific hogli commands, loaded by the hogli framework.+"""PostHog-specific hogli commands, loaded lazily by the hogli framework.-The hogli framework itself lives in tools/hogli/. This package is discovered-via `config.commands_dir` in hogli.yaml.-"""--from __future__ import annotations--import sys+Each command module is imported on first invoke via the ``click:`` import+strings in ``hogli.yaml``. Boot-time registrations (prechecks, telemetry+property hooks, post-command hooks) are listed in ``config.boot_modules``.-from hogli.manifest import REPO_ROOT--# `hogli_commands.migrations` imports from `migration_utils`, a shared module at-# `common/migration_utils/`. Put `common/` on sys.path regardless of entry point-# (bin/hogli, pytest, direct import) so that transitive import resolves.-_COMMON = REPO_ROOT / "common"-if _COMMON.is_dir() and str(_COMMON) not in sys.path:- sys.path.insert(0, str(_COMMON))--from . import commands # noqa: E402, F401+The framework itself lives in ``tools/hogli/``; this package is discovered+via ``config.commands_dir`` in ``hogli.yaml``.+"""diff --git a/tools/hogli-commands/hogli_commands/build.py b/tools/hogli-commands/hogli_commands/build.pyindex 16ba631d38c4..ff0acdaa94df 100644--- a/tools/hogli-commands/hogli_commands/build.py+++ b/tools/hogli-commands/hogli_commands/build.py@@ -6,7 +6,6 @@ import fnmatchimport subprocessimport click-from hogli.cli import clifrom hogli.manifest import REPO_ROOT# command -> file globs that should trigger it@@ -82,7 +81,7 @@ def _match_commands(changed_files: set[str]) -> list[str]:][email protected](name="build", help="Run code generation pipelines (smart change detection by default)")[email protected](name="build", help="Run code generation pipelines (smart change detection by default)")@click.option("--force", is_flag=True, help="Rebuild all pipelines unconditionally")@click.option("--dry-run", is_flag=True, help="Show what would be rebuilt without running")@click.option("--list", "list_all", is_flag=True, help="List all available pipelines")diff --git a/tools/hogli-commands/hogli_commands/commands.py b/tools/hogli-commands/hogli_commands/commands.pydeleted file mode 100644index a6b6cdd9e185..000000000000--- a/tools/hogli-commands/hogli_commands/commands.py+++ /dev/null@@ -1,191 +0,0 @@-"""Developer Click commands for PostHog workflows.--This is the extension point for adding new Click commands to hogli.-Add your @cli.command() decorated functions here as an alternative to shell scripts.--They auto-register with hogli and appear in `hogli --help` automatically.--Example:- ```python- import click- from hogli.cli import cli-- @cli.command(name="my:command", help="Does something useful")- @click.argument('path', type=click.Path())- @click.option('--flag', is_flag=True, help='Enable feature')- def my_command(path, flag):- '''Command implementation.'''- # Your Python logic here- click.echo(f"Processing {path}")- ```--Guidelines:-- Use Click decorators for arguments and options-- Import cli group from hogli.cli (the framework in tools/hogli/)-- Name commands with colons for grouping (e.g., 'test:python', 'db:migrate')-- Add helpful docstrings - they become the command help text-- Prefer Python Click commands over shell scripts for better type safety--For simple shell commands or bin script delegation, use hogli.yaml instead.-"""--from __future__ import annotations--import os-import sys-import time as _time-import subprocess-import configparser-from pathlib import Path-from typing import Any--import click-from hogli.hooks import register_post_command_hook, register_precheck, register_telemetry_properties-from hogli.manifest import REPO_ROOT-from hogli.telemetry import _load_config, _save_config--# Side-effect imports: these modules use @cli.command() decorators that register-# commands with the CLI group when imported. The imports appear unused but are required.-from . import ( # noqa: F401- build,- devbox,- doctor,- hints,- metabase,- migrations,- product,- quickstart,- telemetry_commands,- test_runner,-)-from .devenv import cli as devenv_cli # noqa: F401-from .migrations import _compute_migration_diff, _get_cached_migration--# ----------------------------------------------------------------------------# Precheck handlers -- registered with the hogli framework-# ------------------------------------------------------------------------------def _migrations_precheck(check: dict, yes: bool) -> bool | None:- """Check for orphaned migrations before starting services."""- try:- diff = _compute_migration_diff()-- if diff.orphaned:- click.echo()- click.secho("\u26a0\ufe0f Orphaned migrations detected!", fg="yellow", bold=True)- click.echo("These migrations are applied in the DB but don't exist in code.")- click.echo("They were likely applied on another branch.\n")-- for m in diff.orphaned:- cached = "cached" if _get_cached_migration(m.app, m.name) else "not cached"- click.echo(f" {m.app}: {m.name} ({cached})")- click.echo()-- click.echo("Run 'hogli migrations:sync' to roll them back.\n")-- if not yes:- if not click.confirm("Continue anyway?", default=False):- click.echo("Aborted. Run 'hogli migrations:sync' first.")- return False-- except Exception as e:- # Don't block start if migration check fails (e.g., DB not running)- click.secho(f"\u26a0\ufe0f Could not check migrations: {e}", fg="yellow", err=True)-- return None---register_precheck("migrations", _migrations_precheck)---# ----------------------------------------------------------------------------# Telemetry property hooks -- PostHog-specific environment properties-# ------------------------------------------------------------------------------def _infer_process_manager(command: str | None) -> str | None:- pm = os.environ.get("HOGLI_PROCESS_MANAGER")- if pm:- return os.path.basename(pm)- if command == "start":- return "mprocs" if "--mprocs" in sys.argv[2:] else "phrocs"- return None---_POSTHOG_DEV_CACHE_TTL_SECONDS = 30 * 86400 # 30 days---def _check_email_domain() -> bool:- """Fallback: check if git user.email ends with @posthog.com."""- parser = configparser.RawConfigParser()- try:- parser.read([Path.home() / ".gitconfig", REPO_ROOT / ".git" / "config"])- email = parser.get("user", "email", fallback="")- return email.endswith("@posthog.com")- except Exception:- return False---def _check_github_org_membership() -> bool | None:- """Use ``gh api`` to check PostHog org membership. Returns None if gh is unavailable."""- try:- result = subprocess.run(- ["gh", "api", "/user/memberships/orgs/PostHog", "--silent"],- capture_output=True,- timeout=5,- )- return result.returncode == 0- except Exception:- return None---def _is_posthog_dev() -> bool:- """Check if the user is a PostHog GitHub org member.-- Uses ``gh api`` to check org membership, caching the boolean result in- the telemetry config for 30 days. Falls back to a git email domain- check when ``gh`` is unavailable or unauthenticated.- """- config = _load_config()- cached = config.get("is_posthog_org_member")- checked_at = config.get("org_check_timestamp", 0.0)-- if cached is not None and (_time.time() - checked_at) < _POSTHOG_DEV_CACHE_TTL_SECONDS:- return cached-- is_member = _check_github_org_membership()- if is_member is None:- is_member = _check_email_domain()-- config["is_posthog_org_member"] = is_member- config["org_check_timestamp"] = _time.time()- _save_config(config)- return is_member---def _posthog_telemetry_properties(command: str | None = None) -> dict[str, Any]:- return {- "has_devenv_config": (REPO_ROOT / ".posthog" / ".generated" / "mprocs.yaml").exists(),- "in_flox": os.environ.get("FLOX_ENV") is not None,- "is_worktree": (REPO_ROOT / ".git").is_file(),- "is_posthog_dev": _is_posthog_dev(),- "process_manager": _infer_process_manager(command),- }---register_telemetry_properties(_posthog_telemetry_properties)---# ----------------------------------------------------------------------------# Post-command hooks -- run after telemetry flush on every invocation-# ------------------------------------------------------------------------------def _show_hints_post_command(command: str | None, exit_code: int) -> None:- """Print a contextual hint on successful commands."""- if exit_code == 0:- hints.maybe_show_hint(command)---register_post_command_hook(_show_hints_post_command)diff --git a/tools/hogli-commands/hogli_commands/devbox/__init__.py b/tools/hogli-commands/hogli_commands/devbox/__init__.pyindex b26d92d582ad..fb9c826e116e 100644--- a/tools/hogli-commands/hogli_commands/devbox/__init__.py+++ b/tools/hogli-commands/hogli_commands/devbox/__init__.py@@ -1,3 +1 @@"""Remote development environment (Coder devbox) management."""--from . import cli as _cli # noqa: F401diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.pyindex df17aef1635f..eba216bfe30d 100644--- a/tools/hogli-commands/hogli_commands/devbox/cli.py+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py@@ -16,7 +16,7 @@ from pathlib import Pathfrom typing import Anyimport click-from hogli.cli import cli+from hogli.manifest import get_manifestfrom . import keychainfrom .coder import (@@ -370,13 +370,14 @@ def maybe_configure_dotfiles(configure_dotfiles: bool | None) -> None:click.echo("No dotfiles repo configured.")[email protected](name="devbox", help="Show available devbox commands")[email protected](name="devbox", help="Show available devbox commands")def devbox_help() -> None:"""Show the available `hogli devbox:*` commands."""+ manifest_obj = get_manifest()commands = sorted(- (name, cmd.get_short_help_str() or "")- for name, cmd in cli.commands.items()- if name.startswith("devbox:") and not getattr(cmd, "hidden", False)+ (name, (manifest_obj.get_command_config(name) or {}).get("description", ""))+ for name in manifest_obj.get_all_commands()+ if name.startswith("devbox:") and not manifest_obj.is_command_hidden(name))click.echo("Available devbox commands:")click.echo()@@ -413,7 +414,7 @@ def maybe_configure_claude_token(configure_claude: bool | None) -> None:click.echo("No token provided. Skipping.")[email protected](name="devbox:setup", help="Install and configure local access to Coder devboxes")[email protected](name="devbox:setup", help="Install and configure local access to Coder devboxes")@click.option("--configure-ssh/--skip-configure-ssh",default=None,@@ -456,7 +457,7 @@ def devbox_setup(print_setup_summary()[email protected](name="devbox:list", help="List your devboxes")[email protected](name="devbox:list", help="List your devboxes")def devbox_list() -> None:"""List all workspaces belonging to the current user, plus shared workspaces."""ensure_runtime_ready()@@ -496,7 +497,7 @@ def devbox_list() -> None:click.echo(f" {label:<16} {', '.join(users)}")[email protected](name="devbox:users", help="List Coder users (for devbox sharing)")[email protected](name="devbox:users", help="List Coder users (for devbox sharing)")def devbox_users() -> None:"""List all active Coder users so you know who to share with."""ensure_runtime_ready()@@ -538,7 +539,7 @@ def _hint_if_positional_looks_like_username()[email protected](name="devbox:share", help="Share your devbox with other users")[email protected](name="devbox:share", help="Share your devbox with other users")@workspace_argument@click.option("--user", "users", multiple=True, help="Coder username(s) to share with")@click.option("--role", type=click.Choice(["use", "admin"]), default="use", help="Access role to grant")@@ -570,7 +571,7 @@ def devbox_share(click.echo(f"Shared '{name}' with {', '.join(users)} (role: {role}).")[email protected](name="devbox:unshare", help="Revoke access to your devbox from other users")[email protected](name="devbox:unshare", help="Revoke access to your devbox from other users")@workspace_argument@click.option("--user", "users", multiple=True, help="Coder username(s) to revoke access from")def devbox_unshare(workspace: str | None, users: tuple[str, ...]) -> None:@@ -590,7 +591,7 @@ def devbox_unshare(workspace: str | None, users: tuple[str, ...]) -> None:click.echo(click.style("Restart your devbox for this to take effect.", fg="yellow"))[email protected](name="devbox:start", help="Start or create your remote devbox")[email protected](name="devbox:start", help="Start or create your remote devbox")@workspace_argument@click.option("--disk",@@ -642,7 +643,7 @@ def devbox_start(_print_connection_info(name)[email protected](name="devbox:stop", help="Stop your devbox (preserves disk, stops billing)")[email protected](name="devbox:stop", help="Stop your devbox (preserves disk, stops billing)")@workspace_argument@click.option("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")def devbox_stop(workspace: str | None, verbose: bool) -> None:@@ -661,7 +662,7 @@ def devbox_stop(workspace: str | None, verbose: bool) -> None:click.echo("Stopped. Disk preserved. Run 'hogli devbox:start' to resume.")[email protected](name="devbox:restart", help="Restart your devbox")[email protected](name="devbox:restart", help="Restart your devbox")@workspace_argument@click.option("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")def devbox_restart(workspace: str | None, verbose: bool) -> None:@@ -675,7 +676,7 @@ def devbox_restart(workspace: str | None, verbose: bool) -> None:_print_connection_info(name)[email protected](name="devbox:update", help="Update devbox to the latest template")[email protected](name="devbox:update", help="Update devbox to the latest template")@workspace_argument@click.option("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")def devbox_update(workspace: str | None, verbose: bool) -> None:@@ -696,7 +697,7 @@ def devbox_update(workspace: str | None, verbose: bool) -> None:_print_connection_info(name)[email protected](name="devbox:ssh", help="SSH into your devbox")[email protected](name="devbox:ssh", help="SSH into your devbox")@workspace_argumentdef devbox_ssh(workspace: str | None) -> None:"""Open an SSH session to the devbox."""@@ -705,7 +706,7 @@ def devbox_ssh(workspace: str | None) -> None:ssh_replace(name)[email protected](name="devbox:open", help="Open devbox in browser, VS Code, or Cursor")[email protected](name="devbox:open", help="Open devbox in browser, VS Code, or Cursor")@workspace_argument@click.option("--vscode", is_flag=True, help="Open in VS Code Desktop via SSH")@click.option("--cursor", is_flag=True, help="Open in Cursor via SSH")@@ -733,7 +734,7 @@ def devbox_open(workspace: str | None, vscode: bool, cursor: bool, web: bool) ->open_in_browser(name)[email protected](name="devbox:logs", help="Tail devbox build and agent logs")[email protected](name="devbox:logs", help="Tail devbox build and agent logs")@workspace_argument@click.option("-f", "--follow", is_flag=True, help="Follow log output")def devbox_logs(workspace: str | None, follow: bool) -> None:@@ -743,7 +744,7 @@ def devbox_logs(workspace: str | None, follow: bool) -> None:logs_replace(name, follow)[email protected](name="devbox:task", short_help="Run a background agent task on a fresh devbox")[email protected](name="devbox:task", short_help="Run a background agent task on a fresh devbox")@click.argument("prompt", required=False)@click.option("--name", "task_name", default=None, help="Task name (auto-generated if omitted)")@click.option("-q", "--quiet", is_flag=True, help="Only print the created task's ID")@@ -768,7 +769,7 @@ def devbox_task(prompt: str | None, task_name: str | None, quiet: bool) -> None:create_task(prompt, task_name=task_name, quiet=quiet)[email protected](name="devbox:destroy", help="Destroy your devbox and its data")[email protected](name="devbox:destroy", help="Destroy your devbox and its data")@workspace_argument@click.option("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")def devbox_destroy(workspace: str | None, verbose: bool) -> None:@@ -789,7 +790,7 @@ def devbox_destroy(workspace: str | None, verbose: bool) -> None:click.echo("Destroyed.")[email protected](name="devbox:status", help="Show devbox status")[email protected](name="devbox:status", help="Show devbox status")@workspace_argumentdef devbox_status(workspace: str | None) -> None:"""Show the current state of the devbox."""@@ -821,7 +822,7 @@ def devbox_status(workspace: str | None) -> None:_print_connection_info(name)[email protected](name="devbox:forward", help="Forward PostHog UI to localhost")[email protected](name="devbox:forward", help="Forward PostHog UI to localhost")@workspace_argument@click.option("--port", default=8010, type=int, help="Local port to forward to")def devbox_forward(workspace: str | None, port: int) -> None:@@ -888,7 +889,7 @@ def _rm_dir(label: str, path: Path) -> None:click.echo(f" warning: partial deletion ({e})")[email protected](name="devbox:cleanup:disk", help="Free disk space by cleaning caches and build artifacts")[email protected](name="devbox:cleanup:disk", help="Free disk space by cleaning caches and build artifacts")@click.option("--docker", "prune_docker", is_flag=True, help="Also prune stopped Docker containers")@click.option("--cargo",diff --git a/tools/hogli-commands/hogli_commands/devenv/cli.py b/tools/hogli-commands/hogli_commands/devenv/cli.pyindex 0c9c40936d0e..9beddba51bda 100644--- a/tools/hogli-commands/hogli_commands/devenv/cli.py+++ b/tools/hogli-commands/hogli_commands/devenv/cli.py@@ -6,7 +6,6 @@ Provides hogli dev:* commands for managing the development environment.from __future__ import annotationsimport click-from hogli.cli import clifrom .generator import (DevenvConfig,@@ -26,7 +25,7 @@ def _create_resolver() -> IntentResolver:return IntentResolver(intent_map, registry)[email protected](name="dev:generate", help="Regenerate mprocs config from saved settings")[email protected](name="dev:generate", help="Regenerate mprocs config from saved settings")@click.option("--with","with_intents",@@ -111,7 +110,7 @@ def dev_generate(click.echo("Run 'hogli dev:setup' to change your environment.")[email protected](name="dev:explain", help="Show what services would be started for intents")[email protected](name="dev:explain", help="Show what services would be started for intents")@click.argument("intents", nargs=-1)def dev_explain(intents: tuple[str, ...]) -> None:"""Show resolution of intents to services.@@ -158,7 +157,7 @@ def dev_explain(intents: tuple[str, ...]) -> None:click.echo(resolver.explain_resolution(resolved))[email protected](name="dev:intents", help="List available intents")[email protected](name="dev:intents", help="List available intents")def dev_intents() -> None:"""List all available intents with descriptions."""try:@@ -178,7 +177,7 @@ def dev_intents() -> None:click.echo("")[email protected](name="dev:list-units", help="List autostart units for given intents (used by phrocs)")[email protected](name="dev:list-units", help="List autostart units for given intents (used by phrocs)")@click.argument("intents", nargs=-1, required=True)def dev_list_units(intents: tuple[str, ...]) -> None:"""Resolve intents and print autostart unit names, one per line."""@@ -202,7 +201,7 @@ def dev_list_units(intents: tuple[str, ...]) -> None:click.echo(unit)[email protected](name="dev:apply", help="Apply intent config non-interactively (used by phrocs)")[email protected](name="dev:apply", help="Apply intent config non-interactively (used by phrocs)")@click.argument("intents", nargs=-1, required=True)@click.option("--include",@@ -287,7 +286,7 @@ def dev_apply(click.echo(str(output_path))[email protected](name="dev:setup", help="Interactive wizard to configure your dev environment")[email protected](name="dev:setup", help="Interactive wizard to configure your dev environment")@click.option("--log", "log_to_files", is_flag=True, help="Log process output to /tmp/posthog-*.log files")def dev_setup(log_to_files: bool) -> None:"""Run the interactive setup wizard to configure your development environment."""@@ -327,7 +326,7 @@ def _get_docker_profiles_from_config() -> list[str]:return []name="docker:services:up",help="Start Docker services based on your intent config",context_settings={"ignore_unknown_options": True, "allow_extra_args": True},diff --git a/tools/hogli-commands/hogli_commands/doctor.py b/tools/hogli-commands/hogli_commands/doctor.pyindex 1cc572c4edb5..e5b2e67f917f 100644--- a/tools/hogli-commands/hogli_commands/doctor.py+++ b/tools/hogli-commands/hogli_commands/doctor.py@@ -13,7 +13,6 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathimport click-from hogli.cli import clifrom . import hints@@ -103,7 +102,7 @@ class CleanupResult:deleted_anything: bool = Falsename="doctor:disk",help="Interactive disk space cleanup for common PostHog dev bloat",)@@ -982,7 +981,7 @@ class DevProcess:manager: str = "" # e.g. "phrocs (PID 1234)" for managed processesname="doctor:zombies",help="Find and kill orphaned PostHog dev processes",)@@ -1718,7 +1717,7 @@ def _print_check_result(result: CheckResult) -> None:click.echo(f"{'':>30}{result.remediation}")[email protected](name="doctor", help="Quick health check for your dev environment")[email protected](name="doctor", help="Quick health check for your dev environment")def doctor() -> None:"""Run non-destructive checks and print a status summary."""from hogli.manifest import REPO_ROOTdiff --git a/tools/hogli-commands/hogli_commands/hint_hook.py b/tools/hogli-commands/hogli_commands/hint_hook.pynew file mode 100644index 000000000000..4e9e300d583c--- /dev/null+++ b/tools/hogli-commands/hogli_commands/hint_hook.py@@ -0,0 +1,19 @@+"""Post-command hint hook.++Prints a contextual tip after successful commands.+"""++from __future__ import annotations++from hogli.hooks import register_post_command_hook++from hogli_commands import hints+++def _show_hints_post_command(command: str | None, exit_code: int) -> None:+ if exit_code != 0:+ return+ hints.maybe_show_hint(command)+++register_post_command_hook(_show_hints_post_command)diff --git a/tools/hogli-commands/hogli_commands/metabase.py b/tools/hogli-commands/hogli_commands/metabase.pyindex ae1e8f472301..fb46a04c54cc 100644--- a/tools/hogli-commands/hogli_commands/metabase.py+++ b/tools/hogli-commands/hogli_commands/metabase.py@@ -28,7 +28,6 @@ from pathlib import Pathfrom typing import Anyimport click-from hogli.cli import cliLOGIN_TIMEOUT_SECONDS: float = 180.0LOGIN_POLL_INTERVAL_SECONDS: float = 1.0@@ -238,7 +237,7 @@ def _login_region(region: str, browser: str | None, no_open: bool, timeout: floaclick.echo(f"[{region}] saved cookie to {path}")[email protected](name="metabase:login", help="Log in to Metabase via SSO and cache the session cookie")[email protected](name="metabase:login", help="Log in to Metabase via SSO and cache the session cookie")@click.option("--region",type=click.Choice(sorted(REGIONS.keys())),@@ -268,7 +267,7 @@ def metabase_login(region: str, browser: str | None, no_open: bool, timeout: flo_login_region(region, browser, no_open, timeout)[email protected](name="metabase:cookie", help="Print the cached Metabase cookie header")[email protected](name="metabase:cookie", help="Print the cached Metabase cookie header")@click.option("--region",type=click.Choice(sorted(REGIONS.keys())),@@ -388,7 +387,7 @@ def _render_rows_tsv(body: dict[str, Any]) -> str:return "\n".join(out) + "\n"name="metabase:databases",help="List Metabase databases (id, name, engine) for a region",)@@ -422,7 +421,7 @@ def metabase_databases(region: str, output_format: str) -> None:click.echo(f"{e['id']:>4} {e['name']:<40} {e['engine']}")name="metabase:query",help="Run a SQL query against Metabase /api/dataset; results to stdout",)diff --git a/tools/hogli-commands/hogli_commands/migrations.py b/tools/hogli-commands/hogli_commands/migrations.pyindex 32316072d230..52a89c5f61d7 100644--- a/tools/hogli-commands/hogli_commands/migrations.py+++ b/tools/hogli-commands/hogli_commands/migrations.py@@ -33,10 +33,11 @@ from pathlib import Pathfrom urllib.parse import quoteimport click-from hogli.cli import clifrom hogli.manifest import REPO_ROOT-from migration_utils import (++from common.migration_utils import (MIGRATION_CACHE_DIR,+ cache_migration_file,get_cache_path as _get_cache_path,get_cached_migration as _get_cached_migration,get_managed_app_paths,@@ -83,8 +84,6 @@ class MigrationDiff:def _cache_migration(app: str, name: str, source_path: Path) -> bool:"""Cache a migration file for later rollback with CLI feedback."""- from migration_utils import cache_migration_file-try:if not cache_migration_file(app, name, source_path):click.secho(f" ⚠ Could not cache {app}.{name}", fg="yellow", err=True)@@ -209,11 +208,11 @@ def _get_subprocess_env() -> dict[str, str]:"""Get environment for subprocess calls that need hogli module access."""env = dict(os.environ)env["DJANGO_SETTINGS_MODULE"] = "posthog.settings"- # Ensure common/ is in PYTHONPATH so hogli module is importable- common_path = str(REPO_ROOT / "common")+ # Put repo root on the child's PYTHONPATH so `from common.migration_utils import ...`+ # resolves the same way as in-process imports.+ repo_root = str(REPO_ROOT)existing_path = env.get("PYTHONPATH", "")- # Use os.pathsep for cross-platform compatibility (: on Unix, ; on Windows)- env["PYTHONPATH"] = f"{common_path}{os.pathsep}{existing_path}" if existing_path else common_path+ env["PYTHONPATH"] = f"{repo_root}{os.pathsep}{existing_path}" if existing_path else repo_rootreturn env@@ -577,7 +576,7 @@ def _apply_migrations(pending: list[MigrationInfo] | None = None, dry_run: boolreturn MigrationResult(success=True)[email protected](name="migrations:status", help="Show migration diff between database and code")[email protected](name="migrations:status", help="Show migration diff between database and code")def migrations_status() -> None:"""Show which migrations are orphaned, pending, or synced."""click.echo("\nAnalyzing migrations…\n")@@ -605,7 +604,7 @@ def migrations_status() -> None:click.echo("Run 'hogli migrations:sync' to fix, or use 'down'/'up' individually.")[email protected](name="migrations:down", help="Roll back orphaned migrations")[email protected](name="migrations:down", help="Roll back orphaned migrations")@click.option("--dry-run", "-n", is_flag=True, help="Show what would be done without executing")@click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompts")@click.option("--force", "-f", is_flag=True, help="Force removal without schema rollback (just deletes DB records)")@@ -733,7 +732,7 @@ def _handle_duplicate_error(result: MigrationResult, pending: list[MigrationInforeturn False[email protected](name="migrations:up", help="Apply pending migrations")[email protected](name="migrations:up", help="Apply pending migrations")@click.option("--dry-run", "-n", is_flag=True, help="Show what would be done without executing")@click.option("--yes", "-y", is_flag=True, help="Auto-confirm faking migrations with duplicate schema")def migrations_up(dry_run: bool, yes: bool) -> None:@@ -781,7 +780,7 @@ def migrations_up(dry_run: bool, yes: bool) -> None:click.secho("✓ Migrations applied and cached", fg="green", bold=True)[email protected](name="migrations:sync", help="Sync migrations: roll back orphaned, apply pending")[email protected](name="migrations:sync", help="Sync migrations: roll back orphaned, apply pending")@click.option("--dry-run", "-n", is_flag=True, help="Show what would be done without executing")@click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompts")@click.option("--force", "-f", is_flag=True, help="Force sync even if some migrations can't be properly rolled back")@@ -910,7 +909,7 @@ def migrations_sync(dry_run: bool, yes: bool, force: bool) -> None:click.secho("✓ Sync complete", fg="green", bold=True)[email protected](name="migrations:cache-sync", help="Populate cache from currently applied migrations")[email protected](name="migrations:cache-sync", help="Populate cache from currently applied migrations")def migrations_cache_sync() -> None:"""Cache all currently applied migrations that exist in code.diff --git a/tools/hogli-commands/hogli_commands/prechecks.py b/tools/hogli-commands/hogli_commands/prechecks.pynew file mode 100644index 000000000000..782d3009dd41--- /dev/null+++ b/tools/hogli-commands/hogli_commands/prechecks.py@@ -0,0 +1,50 @@+"""Precheck handlers for hogli command lifecycle.++Precheck handlers run before composite commands execute (see ``steps:`` /+``prechecks:`` entries in hogli.yaml). They register against+``hogli.hooks.register_precheck`` at boot, and the heavy work happens lazily+inside the handler — keep this module light to import.+"""++from __future__ import annotations++import click+from hogli.hooks import register_precheck+++def _migrations_precheck(check: dict, yes: bool) -> bool | None:+ """Warn (and optionally block) when applied migrations don't exist in code."""+ # Lazy import: pulls the migrations command module only when this precheck+ # actually fires (i.e. when a `prechecks: [{type: migrations}]` step runs),+ # not at boot.+ from hogli_commands.migrations import _compute_migration_diff, _get_cached_migration++ try:+ diff = _compute_migration_diff()++ if diff.orphaned:+ click.echo()+ click.secho("⚠️ Orphaned migrations detected!", fg="yellow", bold=True)+ click.echo("These migrations are applied in the DB but don't exist in code.")+ click.echo("They were likely applied on another branch.\n")++ for m in diff.orphaned:+ cached = "cached" if _get_cached_migration(m.app, m.name) else "not cached"+ click.echo(f" {m.app}: {m.name} ({cached})")+ click.echo()++ click.echo("Run 'hogli migrations:sync' to roll them back.\n")++ if not yes:+ if not click.confirm("Continue anyway?", default=False):+ click.echo("Aborted. Run 'hogli migrations:sync' first.")+ return False++ except Exception as e:+ # Don't block start if migration check fails (e.g., DB not running)+ click.secho(f"⚠️ Could not check migrations: {e}", fg="yellow", err=True)++ return None+++register_precheck("migrations", _migrations_precheck)diff --git a/tools/hogli-commands/hogli_commands/product/__init__.py b/tools/hogli-commands/hogli_commands/product/__init__.pyindex 534e245f2e54..0fa87659981e 100644--- a/tools/hogli-commands/hogli_commands/product/__init__.py+++ b/tools/hogli-commands/hogli_commands/product/__init__.py@@ -1,9 +1,5 @@"""Product scaffolding and linting."""-# Import _cli to trigger @cli.command registration with hogli's CLI group.-from . import cli as _cli # noqa: F401--# Public APIfrom .checks import CHECKS, CheckContext, CheckResult, ProductCheckfrom .lint import lint_productfrom .scaffold import bootstrap_productdiff --git a/tools/hogli-commands/hogli_commands/product/cli.py b/tools/hogli-commands/hogli_commands/product/cli.pyindex fa1336c5a1cc..925230a33db8 100644--- a/tools/hogli-commands/hogli_commands/product/cli.py+++ b/tools/hogli-commands/hogli_commands/product/cli.py@@ -3,14 +3,13 @@from __future__ import annotationsimport click-from hogli.cli import clifrom .lint import lint_all_products, lint_productfrom .maturity import generate_codegen_report, generate_detail, generate_report, score_all_products, score_productfrom .scaffold import bootstrap_product[email protected](name="product:bootstrap", help="Scaffold a new product with canonical structure")[email protected](name="product:bootstrap", help="Scaffold a new product with canonical structure")@click.argument("name")@click.option("--dry-run", is_flag=True, help="Show what would be created without creating")@click.option("--force", is_flag=True, help="Overwrite existing files")@@ -18,7 +17,7 @@ def cmd_bootstrap(name: str, dry_run: bool, force: bool) -> None:bootstrap_product(name, dry_run, force)[email protected](name="product:lint", help="Check product structure for misplaced files")[email protected](name="product:lint", help="Check product structure for misplaced files")@click.argument("name", required=False)@click.option("--all", "lint_all", is_flag=True, help="Lint all products")def cmd_lint(name: str | None, lint_all: bool) -> None:@@ -43,7 +42,7 @@ def cmd_lint(name: str | None, lint_all: bool) -> None:raise SystemExit(1)[email protected](name="product:maturity", help="Score product maturity across isolation dimensions")[email protected](name="product:maturity", help="Score product maturity across isolation dimensions")@click.argument("name", required=False)@click.option("--all", "score_all", is_flag=True, help="Score all products and generate ranked report")@click.option("--codegen", "codegen_detail", is_flag=True, help="Show detailed codegen call-site analysis")diff --git a/tools/hogli-commands/hogli_commands/quickstart.py b/tools/hogli-commands/hogli_commands/quickstart.pyindex af61d85f81aa..421b75d85987 100644--- a/tools/hogli-commands/hogli_commands/quickstart.py+++ b/tools/hogli-commands/hogli_commands/quickstart.py@@ -3,10 +3,9 @@from __future__ import annotationsimport click-from hogli.cli import cli[email protected](name="quickstart", help="Show getting started with PostHog development")[email protected](name="quickstart", help="Show getting started with PostHog development")def quickstart() -> None:"""Display essential commands for getting up and running."""click.echo("")diff --git a/tools/hogli-commands/hogli_commands/telemetry_commands.py b/tools/hogli-commands/hogli_commands/telemetry_commands.pyindex 242307c21d1a..9f546f083173 100644--- a/tools/hogli-commands/hogli_commands/telemetry_commands.py+++ b/tools/hogli-commands/hogli_commands/telemetry_commands.py@@ -4,22 +4,21 @@ from __future__ import annotationsimport clickfrom hogli import telemetry-from hogli.cli import cli[email protected](name="telemetry:on", help="Enable anonymous usage telemetry")[email protected](name="telemetry:on", help="Enable anonymous usage telemetry")def telemetry_on() -> None:telemetry.set_enabled(True)click.echo("Telemetry enabled. Thank you for helping improve hogli!")[email protected](name="telemetry:off", help="Disable anonymous usage telemetry")[email protected](name="telemetry:off", help="Disable anonymous usage telemetry")def telemetry_off() -> None:telemetry.set_enabled(False)click.echo("Telemetry disabled.")[email protected](name="telemetry:status", help="Show current telemetry settings")[email protected](name="telemetry:status", help="Show current telemetry settings")def telemetry_status() -> None:import osdiff --git a/tools/hogli-commands/hogli_commands/telemetry_props.py b/tools/hogli-commands/hogli_commands/telemetry_props.pynew file mode 100644index 000000000000..3d02b3f0a7d4--- /dev/null+++ b/tools/hogli-commands/hogli_commands/telemetry_props.py@@ -0,0 +1,92 @@+"""PostHog-specific telemetry property hooks.++Registers a hook that enriches every ``command_started`` / ``command_completed``+event with PostHog-developer context (process manager, devenv state, org+membership, etc.). Imports here are stdlib only — keep it light, this loads at+boot.+"""++from __future__ import annotations++import os+import sys+import time+import subprocess+import configparser+from pathlib import Path+from typing import Any++from hogli.hooks import register_telemetry_properties+from hogli.manifest import REPO_ROOT+from hogli.telemetry import _load_config, _save_config++_POSTHOG_DEV_CACHE_TTL_SECONDS = 30 * 86400 # 30 days+++def _infer_process_manager(command: str | None) -> str | None:+ pm = os.environ.get("HOGLI_PROCESS_MANAGER")+ if pm:+ return os.path.basename(pm)+ if command == "start":+ return "mprocs" if "--mprocs" in sys.argv[2:] else "phrocs"+ return None+++def _check_email_domain() -> bool:+ """Fallback signal: git ``user.email`` ends with ``@posthog.com``."""+ parser = configparser.RawConfigParser()+ try:+ parser.read([Path.home() / ".gitconfig", REPO_ROOT / ".git" / "config"])+ email = parser.get("user", "email", fallback="")+ return email.endswith("@posthog.com")+ except Exception:+ return False+++def _check_github_org_membership() -> bool | None:+ """Use ``gh api`` to check PostHog org membership. Returns None if gh is unavailable."""+ try:+ result = subprocess.run(+ ["gh", "api", "/user/memberships/orgs/PostHog", "--silent"],+ capture_output=True,+ timeout=5,+ )+ return result.returncode == 0+ except Exception:+ return None+++def _is_posthog_dev() -> bool:+ """Return True if the current user is a PostHog GitHub org member.++ Caches the boolean for 30 days in the telemetry config. Falls back to a+ git-email-domain check when ``gh`` is unavailable or unauthenticated.+ """+ config = _load_config()+ cached = config.get("is_posthog_org_member")+ checked_at = config.get("org_check_timestamp", 0.0)++ if cached is not None and (time.time() - checked_at) < _POSTHOG_DEV_CACHE_TTL_SECONDS:+ return cached++ is_member = _check_github_org_membership()+ if is_member is None:+ is_member = _check_email_domain()++ config["is_posthog_org_member"] = is_member+ config["org_check_timestamp"] = time.time()+ _save_config(config)+ return is_member+++def _posthog_telemetry_properties(command: str | None = None) -> dict[str, Any]:+ return {+ "has_devenv_config": (REPO_ROOT / ".posthog" / ".generated" / "mprocs.yaml").exists(),+ "in_flox": os.environ.get("FLOX_ENV") is not None,+ "is_worktree": (REPO_ROOT / ".git").is_file(),+ "is_posthog_dev": _is_posthog_dev(),+ "process_manager": _infer_process_manager(command),+ }+++register_telemetry_properties(_posthog_telemetry_properties)diff --git a/tools/hogli-commands/hogli_commands/test_runner.py b/tools/hogli-commands/hogli_commands/test_runner.pyindex 4256bd918e98..bc3e4430cbab 100644--- a/tools/hogli-commands/hogli_commands/test_runner.py+++ b/tools/hogli-commands/hogli_commands/test_runner.py@@ -15,7 +15,6 @@ from dataclasses import dataclass, fieldfrom pathlib import Path, PurePosixPathimport click-from hogli.cli import clifrom hogli.command_types import _runfrom hogli.manifest import REPO_ROOT@@ -724,7 +723,7 @@ def _run_watch(file_path: str, extra_args: list[str]) -> None:# ---------------------------------------------------------------------------name="test",help=("Auto-detect test type and run the correct test runner.\n\n"diff --git a/tools/hogli-commands/hogli_commands/tests/test_commands.py b/tools/hogli-commands/hogli_commands/tests/test_commands.pyindex 3601ac00e2a2..0c2303ebc50c 100644--- a/tools/hogli-commands/hogli_commands/tests/test_commands.py+++ b/tools/hogli-commands/hogli_commands/tests/test_commands.py@@ -8,7 +8,7 @@ import timeimport pytestfrom unittest.mock import patch-from hogli_commands.commands import _infer_process_manager, _is_posthog_dev+from hogli_commands.telemetry_props import _infer_process_manager, _is_posthog_devclass TestProcessManagerInference:@@ -46,13 +46,13 @@ class TestIsPosthogDev:self._write_config(_config_dir, is_posthog_org_member=True, org_check_timestamp=time.time())assert _is_posthog_dev() is True- @patch("hogli_commands.commands._check_github_org_membership", return_value=True)+ @patch("hogli_commands.telemetry_props._check_github_org_membership", return_value=True)def test_cache_miss_calls_gh_and_persists(self, _mock_gh, _config_dir):assert _is_posthog_dev() is Trueassert json.loads(_config_dir.read_text())["is_posthog_org_member"] is True- @patch("hogli_commands.commands._check_email_domain", return_value=True)- @patch("hogli_commands.commands._check_github_org_membership", return_value=None)+ @patch("hogli_commands.telemetry_props._check_email_domain", return_value=True)+ @patch("hogli_commands.telemetry_props._check_github_org_membership", return_value=None)def test_gh_unavailable_falls_back_to_email_and_caches(self, _mock_gh, mock_email, _config_dir):assert _is_posthog_dev() is Truemock_email.assert_called_once()diff --git a/tools/hogli-commands/hogli_commands/tests/test_test_runner.py b/tools/hogli-commands/hogli_commands/tests/test_test_runner.pyindex 7ea8373769fb..0fa905ab0989 100644--- a/tools/hogli-commands/hogli_commands/tests/test_test_runner.py+++ b/tools/hogli-commands/hogli_commands/tests/test_test_runner.py@@ -5,9 +5,11 @@ from __future__ import annotationsfrom pathlib import Pathimport pytest-from unittest.mock import patch+from unittest.mock import MagicMock, patchimport click+from click.testing import CliRunner+from hogli.cli import clifrom hogli_commands.test_runner import (_batch_find_rs_cfg_test,_detect_all,@@ -21,6 +23,8 @@ from hogli_commands.test_runner import ()from parameterized import parameterized+runner = CliRunner()+class TestDetectTestType:"""Tests hit real files on disk — they validate that detection works@@ -479,6 +483,30 @@ class TestRunGrouped:assert "nodejs/tests/cdp/cdp-api.test.ts" in nodejs_cmd+class TestCliPassthrough:+ @patch("hogli_commands.test_runner._run")+ def test_hogli_test_passes_unknown_options_to_runner(self, mock_run: MagicMock) -> None:+ result = runner.invoke(+ cli,+ [+ "test",+ "tools/hogli-commands/hogli_commands/tests/test_commands.py",+ "-k",+ "cache",+ ],+ )++ assert result.exit_code == 0, result.output+ command = mock_run.call_args[0][0]+ assert command == [+ "pytest",+ "-s",+ "tools/hogli-commands/hogli_commands/tests/test_commands.py",+ "-k",+ "cache",+ ]++def _get_repo_root():from hogli.manifest import REPO_ROOTdiff --git a/tools/hogli/README.md b/tools/hogli/README.mdindex 22317b4262e8..1ee112214fc8 100644--- a/tools/hogli/README.md+++ b/tools/hogli/README.md@@ -115,34 +115,41 @@ my:command:## Python Commands-For complex logic, create Python commands using Click. Two layouts are supported — pick based on how many commands you have.+For complex logic, define plain Click commands and reference them from `hogli.yaml` with `click: module.path:attribute`.-The directory name is yours to choose. PostHog uses `hogli-commands` (and the examples below follow that). One constraint: it **must not** be named `hogli`, since that shadows the installed framework and your commands will be silently ignored.+Click command modules are lazy-loaded. Top-level `hogli --help` uses the manifest description without importing Python command modules; `hogli <command> --help` and command execution import the target on demand.-### Minimal: single file (recommended for most repos)+The Click command name must match the manifest key — drift surfaces as a `ClickException` on resolution. The framework follows Click's recommendation that lazy loading be paired with a test that runs `--help` on each subcommand; PostHog's test suite parametrizes over every `click:` entry in `hogli.yaml` to do exactly that.-A handful of commands needs nothing more than one `commands.py`:+Mark commands hidden via `hidden: true` in `hogli.yaml`. Don't use `@click.command(hidden=True)` — the manifest is the single source of truth.++### Minimal: one importable package```textyour-repo/├── hogli.yaml└── tools/- └── hogli-commands/- └── commands.py+ └── hogli_commands/+ ├── __init__.py+ └── db.py``````yaml# hogli.yamlconfig:- commands_dir: tools/hogli-commands+ commands_dir: tools/hogli_commands++db:+ db:migrate:+ click: hogli_commands.db:db_migrate+ description: Run database migrations``````python-# tools/hogli-commands/commands.py+# tools/hogli_commands/db.pyimport click-from hogli.cli import cli[email protected](name="db:migrate")[email protected](name="db:migrate")@click.option("--dry-run", is_flag=True, help="Show SQL without executing")def db_migrate(dry_run: bool) -> None:"""Run database migrations."""@@ -153,20 +160,20 @@ def db_migrate(dry_run: bool) -> None:pass```-The directory can live anywhere `hogli.yaml` can reference — `tools/hogli-commands/` fits a monorepo with a `tools/` convention, but a top-level `hogli-commands/` or any other path works equally well.+`commands_dir` is optional and explicit: hogli only uses it when configured. It must be a relative path to an existing directory. hogli puts that directory's parent on `sys.path`, so the directory should be an importable package or module tree. It must not be named `hogli`, since that shadows the installed framework.-### Full: package with submodules (for larger surfaces)+### Full: project package with submodules-When commands grow past one file and need to import each other, promote to a package. Add an inner `hogli_commands/` directory with `__init__.py` and split commands into submodules; `commands.py` becomes the registration entry point that imports them for side-effects:+For a larger command surface, keep the distribution/project directory separate from the import package:```textyour-repo/├── hogli.yaml└── tools/└── hogli-commands/+ ├── pyproject.toml└── hogli_commands/ # underscored: this is the import name├── __init__.py- ├── commands.py # `from . import build, db, deploy`├── build.py├── db.py└── deploy.py@@ -176,17 +183,29 @@ your-repo/# hogli.yamlconfig:commands_dir: tools/hogli-commands/hogli_commands++build:+ build:+ click: hogli_commands.build:build+ description: Run build pipelines```The dashed outer dir + underscored inner package follows PEP 8 (dashed project name, underscored import name). This is the layout PostHog itself uses.## Extension Hooks-Extensions can inject behavior at three framework call sites without forking. Register from a module that runs at command-load time (e.g. your `commands_dir` package's `__init__.py` or `commands.py`). Exceptions raised by hooks are swallowed — one extension can't break another.+Extensions can inject behavior at three framework call sites without forking. Register hooks from modules listed in `config.boot_modules`; those modules are imported once at startup, before command dispatch. Keep boot modules cheap to import and move heavy work inside hook functions. Exceptions raised by hooks are swallowed, so one extension can't break another.++```yaml+config:+ commands_dir: tools/hogli_commands+ boot_modules:+ - hogli_commands.boot+```### Prechecks-Run validation before a command executes, keyed by `type:` in a `precheck:` entry in `hogli.yaml`. Return `False` to abort, `True`/`None` to continue.+Run validation before a command executes, keyed by `type:` in a `prechecks:` entry in `hogli.yaml`. Return `False` to abort, `True`/`None` to continue.```pythonfrom hogli.hooks import register_precheck@@ -201,7 +220,7 @@ register_precheck("migrations", check_migrations)```yamldev:start:cmd: docker compose up -d- precheck:+ prechecks:- type: migrations```@@ -236,7 +255,9 @@ register_post_command_hook(maybe_show_hint)```yamlconfig:- commands_dir: path/to/commands # Python commands directory (default: hogli/)+ commands_dir: path/to/commands # Optional local Python command package+ boot_modules:+ - package.boot # Optional eager hook registration modulesscripts_dir: scripts # For bin_script resolution (default: bin/)metadata:@@ -250,7 +271,7 @@ metadata:## Built-in Commands- `hogli quickstart` - Getting started guide-- `hogli meta:check` - Validate manifest, find undocumented scripts+- `hogli meta:check` - Validate manifest against bin scripts (for CI)- `hogli meta:concepts` - Show infrastructure concepts (if defined)## Requirementsdiff --git a/tools/hogli/scripts/generate_man_page.py b/tools/hogli/scripts/generate_man_page.pyindex 554e7a263d4f..23702a9bba78 100644--- a/tools/hogli/scripts/generate_man_page.py+++ b/tools/hogli/scripts/generate_man_page.py@@ -44,9 +44,9 @@ def _collect_help_text() -> str:def _collect_command_help() -> list[tuple[str, str]]:root_ctx = click.Context(cli, info_name="hogli", terminal_width=TERMINAL_WIDTH, color=False)command_help_sections: list[tuple[str, str]] = []- for command_name, command in sorted(cli.commands.items()):- config = getattr(command, "hogli_config", {})- if config.get("hidden", False):+ for command_name in cli.list_commands(root_ctx):+ command = cli.get_command(root_ctx, command_name)+ if command is None or command.hidden:continuesub_ctx = click.Context(@@ -101,8 +101,8 @@ def _render(help_text: str, command_help_sections: list[tuple[str, str]]) -> str"\\fItools/hogli/src/hogli/cli.py\\fR","CLI group and command registration.",".TP",- "\\fItools/hogli-commands/hogli_commands/commands.py\\fR",- "Custom Click commands.",+ "\\fItools/hogli-commands/hogli_commands/\\fR",+ "PostHog-specific lazy Click command modules.","",])diff --git a/tools/hogli/src/hogli/cli.py b/tools/hogli/src/hogli/cli.pyindex 5e81e4e8de12..67e655c4bb90 100644--- a/tools/hogli/src/hogli/cli.py+++ b/tools/hogli/src/hogli/cli.py@@ -12,7 +12,6 @@ import time as _timeimport shutilimport platformimport importlib-import importlib.utilfrom collections import defaultdictfrom typing import Any@@ -21,7 +20,8 @@ import clickfrom hogli import telemetryfrom hogli.command_types import BinScriptCommand, CompositeCommand, DirectCommand, HogliCommandfrom hogli.hooks import post_command_hooks, telemetry_property_hooks-from hogli.manifest import get_category_for_command, get_manifest, get_services_for_command, load_manifest+from hogli.lazy_commands import add_commands_dir_to_path, add_repo_root_to_path, resolve_click_command+from hogli.manifest import REPO_ROOT, get_category_for_command, get_manifest, get_services_for_command, load_manifestfrom hogli.validate import auto_update_manifest, find_missing_manifest_entries_DEFAULT_HELP = "Developer CLI framework with YAML-based command definitions."@@ -35,6 +35,26 @@ class CategorizedGroup(click.Group):module-level singleton."""+ def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None:+ command = super().get_command(ctx, cmd_name)+ if command is not None:+ return command++ config = get_manifest().get_command_config(cmd_name)+ if not config or "click" not in config:+ return None++ return resolve_click_command(cmd_name, config["click"])++ def list_commands(self, ctx: click.Context) -> list[str]:+ manifest_obj = get_manifest()+ commands = {name for name in super().list_commands(ctx) if not manifest_obj.is_command_hidden(name)}+ for cmd_name in manifest_obj.get_all_commands():+ config = manifest_obj.get_command_config(cmd_name)+ if config and "click" in config and not manifest_obj.is_command_hidden(cmd_name):+ commands.add(cmd_name)+ return sorted(commands)+def invoke(self, ctx: click.Context) -> Any:ctx.meta["hogli.start_time"] = _time.monotonic()ctx.meta["hogli.has_extra_argv"] = len(sys.argv) > 2@@ -64,14 +84,18 @@ class CategorizedGroup(click.Group):category_key_to_title = {cat.get("key"): cat.get("title") for cat in categories_list}# Set of commands that extend others (will be rendered under their parent)- child_commands = {child for parent in self.commands for child in manifest_obj.get_children_for_command(parent)}+ child_commands = {+ child+ for parent in manifest_obj.get_all_commands()+ for child in manifest_obj.get_children_for_command(parent)+ }# Group commands by category, storing (key, title) tuplegrouped: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list)+ grouped_command_names: set[str] = set()for cmd_name, cmd in self.commands.items():# Skip hidden commands (they're still callable, just not shown in help)- hogli_config = getattr(cmd, "hogli_config", {})- if hogli_config.get("hidden", False):+ if manifest_obj.is_command_hidden(cmd_name):continue# Skip child commands - they'll be rendered under their parent@@ -86,6 +110,21 @@ class CategorizedGroup(click.Group):(key for key, title in category_key_to_title.items() if title == category_title), "commands")grouped[(category_key, category_title)].append((cmd_name, help_text))+ grouped_command_names.add(cmd_name)++ for cmd_name in manifest_obj.get_all_commands():+ config = manifest_obj.get_command_config(cmd_name)+ if not config or "click" not in config or manifest_obj.is_command_hidden(cmd_name):+ continue+ if cmd_name in grouped_command_names or cmd_name in child_commands:+ continue++ category_title = get_category_for_command(cmd_name)+ category_key = next(+ (key for key, title in category_key_to_title.items() if title == category_title), "commands"+ )+ grouped[(category_key, category_title)].append((cmd_name, config.get("description", "")))+ grouped_command_names.add(cmd_name)# Build category order from the listcategory_order = {idx: cat.get("key") for idx, cat in enumerate(categories_list)}@@ -212,10 +251,13 @@ def concepts() -> None:def _register_script_commands() -> None:"""Dynamically register commands from hogli.yaml.- Supports three types of entries:- 1. bin_script: Delegate to a shell script (in config.scripts_dir, default: bin/)- 2. steps: Compose multiple hogli commands in sequence- 3. cmd: Execute a direct shell command+ Supports four eagerly registered entry types:+ 1. ``steps:`` — compose multiple hogli commands in sequence.+ 2. ``cmd:`` — execute a direct shell command.+ 3. ``hogli:`` — wrap another hogli command with extra args.+ 4. ``bin_script:`` — delegate to a shell script in ``config.scripts_dir``.++ ``click:`` entries are resolved lazily by ``CategorizedGroup.get_command``."""manifest = get_manifest()scripts_dir = manifest.scripts_dir@@ -228,105 +270,56 @@ def _register_script_commands() -> None:if not isinstance(config, dict):continue- # Determine command type- bin_script = config.get("bin_script")steps = config.get("steps")cmd = config.get("cmd")hogli = config.get("hogli")+ bin_script = config.get("bin_script")- if not (bin_script or steps or cmd or hogli):+ if "click" in config:continue- # Handle composition (steps field)if steps:- command = CompositeCommand(cli_name, config)- command.register(cli)+ CompositeCommand(cli_name, config).register(cli)continue- # Handle direct commands (cmd field)if cmd:- command = DirectCommand(cli_name, config)- command.register(cli)+ DirectCommand(cli_name, config).register(cli)continue- # Handle hogli wrapper commands (hogli field)if hogli:- command = HogliCommand(cli_name, config)- command.register(cli)+ HogliCommand(cli_name, config).register(cli)continue- # Handle bin_script delegationif bin_script:script_path = scripts_dir / bin_script- if not script_path.exists():- continue+ if script_path.exists():+ BinScriptCommand(cli_name, config, script_path).register(cli)- command = BinScriptCommand(cli_name, config, script_path)- command.register(cli)+def _load_boot_modules() -> None:+ """Import modules listed in ``config.boot_modules`` once at startup.-# Register all script commands from manifest before app runs-_register_script_commands()---def _import_custom_commands() -> None:- """Import custom commands from configured commands_dir.-- Looks for commands in:- 1. config.commands_dir in hogli.yaml (e.g., tools/hogli-commands/hogli_commands)- 2. Default: hogli/ folder next to hogli.yaml+ Boot modules register precheck handlers, telemetry property hooks, and+ post-command hooks against ``hogli.hooks``. They run eagerly so the hooks+ are populated before the first command dispatches. They must be cheap to+ import — keep heavy work behind lazy imports inside handler bodies. Any+ import failure aborts hogli, so these are validated implicitly by every+ test that invokes the CLI."""manifest = get_manifest()- commands_dir = manifest.commands_dir-- if not commands_dir:- return+ add_repo_root_to_path(REPO_ROOT)+ add_commands_dir_to_path(manifest.commands_dir)- # Skip if the commands package or any of its submodules is already in sys.modules.- # Submodules are what carry `@cli.command` decorators, so re-importing would create- # a second module object and duplicate registrations against different module- # identities, which breaks test patches that target one path or the other.- # NOTE: commands_dir should NOT be named "hogli" to avoid clobbering the hogli package- package_name = commands_dir.name- for mod_name in sys.modules:- if mod_name == package_name or mod_name.startswith(package_name + "."):- return-- # Add commands dir to path so imports work- parent_dir = str(commands_dir.parent)- if parent_dir not in sys.path:- sys.path.insert(0, parent_dir)+ for module_path in manifest.config.get("boot_modules", []):+ if module_path not in sys.modules:+ importlib.import_module(module_path)- try:- importlib.import_module(package_name)- return- except ModuleNotFoundError:- # The package itself isn't importable via sys.path - fall back to file-spec load.- # Narrower than ImportError so that a broken import *inside* the package- # (e.g. a typo in one of its modules) still surfaces instead of being swallowed.- pass- # Fallback: manual load via file spec when the package isn't on sys.path in the normal sense- init_file = commands_dir / "__init__.py"- commands_file = commands_dir / "commands.py"-- if init_file.exists():- spec = importlib.util.spec_from_file_location(- package_name, init_file, submodule_search_locations=[str(commands_dir)]- )- if spec and spec.loader:- module = importlib.util.module_from_spec(spec)- sys.modules[package_name] = module- spec.loader.exec_module(module)- elif commands_file.exists():- spec = importlib.util.spec_from_file_location(f"{package_name}.commands", commands_file)- if spec and spec.loader:- module = importlib.util.module_from_spec(spec)- spec.loader.exec_module(module)---# Import custom commands from configured location-_import_custom_commands()+# Register all script commands from manifest, then trigger boot modules so+# any framework-extension hooks (prechecks, telemetry props, post-command+# hints) are registered before the first command runs.+_register_script_commands()+_load_boot_modules()def _env_properties(command: str | None = None) -> dict[str, Any]:diff --git a/tools/hogli/src/hogli/lazy_commands.py b/tools/hogli/src/hogli/lazy_commands.pynew file mode 100644index 000000000000..9796b5535746--- /dev/null+++ b/tools/hogli/src/hogli/lazy_commands.py@@ -0,0 +1,94 @@+"""Lazy command import resolution for hogli manifests."""++from __future__ import annotations++import sys+import importlib+from pathlib import Path+from typing import Any++import click+++def add_repo_root_to_path(repo_root: Path) -> None:+ """Make top-level repo packages importable via their dotted name.++ Lets command modules write ``from common.migration_utils import ...`` (or+ any other repo-rooted package) without each consumer mutating ``sys.path``+ in its own ``__init__.py``. Bootstrap belongs at the entry point.++ Appended, not prepended, so installed packages of the same name win.+ """+ repo_root_str = str(repo_root)+ if repo_root_str not in sys.path:+ sys.path.append(repo_root_str)+++def add_commands_dir_to_path(commands_dir: Path | None) -> None:+ """Make a configured local commands package importable.++ ``commands_dir`` points at the package/module directory inside the repo, so+ Python needs its parent on ``sys.path``. When it is omitted, imports still+ work for installed packages or modules already on ``PYTHONPATH``.++ Appended (not prepended) so that an installed package of the same name+ wins over the repo-local checkout — same convention as Python's own+ ``site-packages`` ordering.+ """+ if commands_dir is None:+ return++ parent_dir = str(commands_dir.parent)+ if parent_dir not in sys.path:+ sys.path.append(parent_dir)+++def _parse_import_string(command_name: str, import_string: Any) -> tuple[str, str]:+ if not isinstance(import_string, str) or import_string.count(":") != 1:+ raise click.ClickException(+ f"hogli: command {command_name!r} has invalid import string {import_string!r}; expected 'module.path:attr'"+ )++ module_path, attr = import_string.split(":", 1)+ if not module_path or not attr:+ raise click.ClickException(+ f"hogli: command {command_name!r} has invalid import string {import_string!r}; expected 'module.path:attr'"+ )++ return module_path, attr+++def resolve_click_command(command_name: str, import_string: Any) -> click.Command:+ """Resolve a lazy ``click:`` manifest entry to its ``click.Command`` object.++ Raises ``click.ClickException`` for any failure (bad import string, missing+ module/attr, wrong type, name drift between the manifest key and the Click+ decorator's ``name=``). The CLI surfaces these directly to the user.+ """+ module_path, attr = _parse_import_string(command_name, import_string)++ try:+ module = importlib.import_module(module_path)+ except Exception as exc:+ raise click.ClickException(f"hogli: command {command_name!r} could not import {module_path!r}: {exc}") from exc++ try:+ command = getattr(module, attr)+ except AttributeError as exc:+ raise click.ClickException(+ f"hogli: command {command_name!r} could not resolve {import_string!r}: {exc}"+ ) from exc++ if not isinstance(command, click.Command):+ raise click.ClickException(+ f"hogli: command {command_name!r} resolved {import_string!r} to "+ f"{type(command).__name__}, expected click.Command"+ )++ if command.name != command_name:+ raise click.ClickException(+ f"hogli: command {command_name!r} resolved {import_string!r} with Click name "+ f"{command.name!r}; the names must match"+ )++ return commanddiff --git a/tools/hogli/src/hogli/manifest.py b/tools/hogli/src/hogli/manifest.pyindex d1b9db1c94fd..cd79d574c793 100644--- a/tools/hogli/src/hogli/manifest.py+++ b/tools/hogli/src/hogli/manifest.py@@ -136,26 +136,33 @@ class Manifest:def commands_dir(self) -> Path | None:"""Get custom commands directory path.- Resolution order:- 1. config.commands_dir in hogli.yaml (relative to repo root)- 2. Default: hogli/ next to hogli.yaml-- Returns None if no commands directory exists.+ ``config.commands_dir`` is optional. When present, it is resolved+ relative to the repo root and its parent directory is added to+ ``sys.path`` before resolving lazy command imports."""+ if "commands_dir" not in self.config:+ return None+configured = self.config.get("commands_dir")- if configured:- path = (REPO_ROOT / configured).resolve()- try:- path.relative_to(REPO_ROOT.resolve())- except ValueError:- raise ValueError(f"config.commands_dir '{configured}' resolves outside the repo root")- if path.exists():- return path- # Default: hogli/ next to manifest- default_path = MANIFEST_FILE.parent / "hogli"- if default_path.exists():- return default_path- return None+ if not isinstance(configured, str) or not configured:+ raise ValueError("config.commands_dir must be a non-empty relative path")++ configured_path = Path(configured)+ if configured_path.is_absolute():+ raise ValueError(f"config.commands_dir '{configured}' must be relative to the repo root")++ path = (REPO_ROOT / configured_path).resolve()+ try:+ path.relative_to(REPO_ROOT.resolve())+ except ValueError:+ raise ValueError(f"config.commands_dir '{configured}' resolves outside the repo root")++ if not path.exists():+ raise ValueError(f"config.commands_dir '{configured}' does not exist")+ if not path.is_dir():+ raise ValueError(f"config.commands_dir '{configured}' must resolve to a directory")++ return path@propertydef scripts_dir(self) -> Path:@@ -254,6 +261,14 @@ class Manifest:return category[command_name]return None+ def is_command_hidden(self, command_name: str) -> bool:+ """Whether a command should be hidden from help. Manifest is the only source of truth.++ Set ``hidden: true`` on the manifest entry; do not use ``@click.command(hidden=True)``.+ """+ config = self.get_command_config(command_name) or {}+ return bool(config.get("hidden", False))+def get_children_for_command(self, command_name: str) -> list[str]:"""Get child commands that extend this command."""return self._children_map.get(command_name, [])diff --git a/tools/hogli/tests/test_cli.py b/tools/hogli/tests/test_cli.pyindex d9f356d85f0a..18bf77bf3f68 100644--- a/tools/hogli/tests/test_cli.py+++ b/tools/hogli/tests/test_cli.py@@ -2,14 +2,39 @@from __future__ import annotations+import sys++import pytestfrom unittest.mock import MagicMock, patch+import clickfrom click.testing import CliRunnerfrom hogli.cli import cli+from hogli.manifest import get_manifestrunner = CliRunner()+def _manifest_click_commands() -> list[str]:+ manifest = get_manifest()+ return [+ cmd_name+ for cmd_name in manifest.get_all_commands()+ if (config := manifest.get_command_config(cmd_name)) and config.get("click")+ ]+++def _manifest_click_modules() -> list[str]:+ manifest = get_manifest()+ modules: set[str] = set()+ for cmd_name in _manifest_click_commands():+ click_target = (manifest.get_command_config(cmd_name) or {}).get("click", "")+ module_name = click_target.split(":", 1)[0]+ if module_name:+ modules.add(module_name)+ return sorted(modules)++class TestMainCommand:"""Test main command functionality."""@@ -102,6 +127,40 @@ class TestDynamicCommandRegistration:assert result.exit_code in (0, 2)+class TestLazyClickCommands:+ @pytest.mark.parametrize("command_name", _manifest_click_commands())+ def test_lazy_click_command_help_loads(self, command_name: str) -> None:+ # Click's recommended sanity check: every lazy command's --help must+ # succeed. Catches bad `click:` import strings, missing modules,+ # missing attrs, wrong types, and Click-name drift in one shot.+ result = runner.invoke(cli, [command_name, "--help"])+ assert result.exit_code == 0, f"{command_name}: {result.output}"+ assert "Usage:" in result.output++ def test_top_level_help_does_not_import_lazy_command_modules(self, monkeypatch: pytest.MonkeyPatch) -> None:+ lazy_modules = _manifest_click_modules()+ assert lazy_modules, "expected at least one lazy click module in the manifest"+ for module_name in lazy_modules:+ monkeypatch.delitem(sys.modules, module_name, raising=False)++ result = runner.invoke(cli, ["--help"])++ assert result.exit_code == 0+ for module_name in lazy_modules:+ assert module_name not in sys.modules, f"{module_name} was imported during top-level --help"++ def test_hidden_lazy_commands_are_hidden_from_help_and_listing(self) -> None:+ hidden_command = "dev:list-units"++ result = runner.invoke(cli, ["--help"])++ assert result.exit_code == 0+ assert hidden_command not in result.output+ with click.Context(cli) as ctx:+ assert hidden_command not in cli.list_commands(ctx)+ assert isinstance(cli.get_command(ctx, hidden_command), click.Command)++class TestCommandInjectionPrevention:"""Test that command argument handling is secure."""diff --git a/tools/hogli/tests/test_manifest.py b/tools/hogli/tests/test_manifest.pyindex a5e43211fd34..c949307817f8 100644--- a/tools/hogli/tests/test_manifest.py+++ b/tools/hogli/tests/test_manifest.py@@ -2,6 +2,9 @@from __future__ import annotations+from pathlib import Path++import pytestfrom unittest.mock import patchfrom hogli.manifest import Manifest@@ -195,3 +198,65 @@ class TestManifestCommandEnumeration:assert manifest.get_command_config("dev:setup") is Noneassert manifest.get_command_config("dev:reset") == {"cmd": "echo reset"}+++class TestCommandsDir:+ """Test local command package resolution."""++ def test_commands_dir_is_explicit(self, tmp_path: Path) -> None:+ (tmp_path / "hogli").mkdir()++ with (+ patch.object(Manifest, "_load", return_value={"config": {}}),+ patch("hogli.manifest.REPO_ROOT", tmp_path),+ patch("hogli.manifest.MANIFEST_FILE", tmp_path / "hogli.yaml"),+ ):+ manifest = Manifest()+ assert manifest.commands_dir is None++ def test_commands_dir_resolves_configured_path(self, tmp_path: Path) -> None:+ commands_dir = tmp_path / "tools" / "hogli-commands" / "hogli_commands"+ commands_dir.mkdir(parents=True)++ with (+ patch.object(+ Manifest,+ "_load",+ return_value={"config": {"commands_dir": "tools/hogli-commands/hogli_commands"}},+ ),+ patch("hogli.manifest.REPO_ROOT", tmp_path),+ patch("hogli.manifest.MANIFEST_FILE", tmp_path / "hogli.yaml"),+ ):+ manifest = Manifest()+ assert manifest.commands_dir == commands_dir.resolve()++ def test_commands_dir_rejects_missing_configured_path(self, tmp_path: Path) -> None:+ with (+ patch.object(+ Manifest,+ "_load",+ return_value={"config": {"commands_dir": "tools/missing_commands"}},+ ),+ patch("hogli.manifest.REPO_ROOT", tmp_path),+ patch("hogli.manifest.MANIFEST_FILE", tmp_path / "hogli.yaml"),+ ):+ manifest = Manifest()+ with pytest.raises(ValueError, match="does not exist"):+ _ = manifest.commands_dir++ def test_commands_dir_rejects_absolute_path(self, tmp_path: Path) -> None:+ commands_dir = tmp_path / "tools" / "hogli-commands" / "hogli_commands"+ commands_dir.mkdir(parents=True)++ with (+ patch.object(+ Manifest,+ "_load",+ return_value={"config": {"commands_dir": str(commands_dir)}},+ ),+ patch("hogli.manifest.REPO_ROOT", tmp_path),+ patch("hogli.manifest.MANIFEST_FILE", tmp_path / "hogli.yaml"),+ ):+ manifest = Manifest()+ with pytest.raises(ValueError, match="must be relative"):+ _ = manifest.commands_dirdiff --git a/tools/hogli/tests/test_migrations.py b/tools/hogli/tests/test_migrations.pyindex 47fb6139e6a9..d4c8794be3a8 100644--- a/tools/hogli/tests/test_migrations.py+++ b/tools/hogli/tests/test_migrations.py@@ -26,7 +26,7 @@ class TestPathTraversalValidation:)def test_valid_inputs_pass_validation(self, app: str, name: str) -> None:"""Valid app names and migration names should pass validation."""- from migration_utils import validate_migration_path_components+ from common.migration_utils import validate_migration_path_components# Should not raisevalidate_migration_path_components(app, name)@@ -48,7 +48,7 @@ class TestPathTraversalValidation:)def test_path_traversal_rejected(self, app: str, name: str, _field: str) -> None:"""Path traversal attempts should raise ValueError."""- from migration_utils import validate_migration_path_components+ from common.migration_utils import validate_migration_path_componentswith pytest.raises(ValueError):validate_migration_path_components(app, name)@@ -70,7 +70,7 @@ class TestPathTraversalValidation:)def test_shell_injection_rejected(self, app: str, name: str, _field: str) -> None:"""Shell metacharacters should raise ValueError."""- from migration_utils import validate_migration_path_components+ from common.migration_utils import validate_migration_path_componentswith pytest.raises(ValueError):validate_migration_path_components(app, name)@@ -97,7 +97,7 @@ class TestPathTraversalValidation:)def test_invalid_format_rejected(self, app: str, name: str, _description: str) -> None:"""Invalid format patterns should raise ValueError."""- from migration_utils import validate_migration_path_components+ from common.migration_utils import validate_migration_path_componentswith pytest.raises(ValueError):validate_migration_path_components(app, name)@@ -126,7 +126,7 @@ class TestIsValidMigrationPath:)def test_is_valid_migration_path(self, app: str, name: str, expected: bool) -> None:"""Test the bool-returning validation function."""- from migration_utils import is_valid_migration_path+ from common.migration_utils import is_valid_migration_pathresult = is_valid_migration_path(app, name)assert result is expected@@ -137,7 +137,7 @@ class TestCachePathSecurity:def test_get_cache_path_validates_inputs(self) -> None:"""get_cache_path should validate before constructing path."""- from migration_utils import get_cache_path+ from common.migration_utils import get_cache_path# Valid input should return a pathpath = get_cache_path("posthog", "0001_initial")@@ -153,7 +153,7 @@ class TestCachePathSecurity:def test_cache_path_stays_within_cache_dir(self) -> None:"""Cache path should always be under MIGRATION_CACHE_DIR."""- from migration_utils import MIGRATION_CACHE_DIR, get_cache_path+ from common.migration_utils import MIGRATION_CACHE_DIR, get_cache_pathpath = get_cache_path("posthog", "0001_initial")@@ -171,21 +171,21 @@ class TestSharedMigrationUtils:def test_validate_raises_for_invalid_app(self) -> None:"""validate_migration_path_components should raise for invalid app."""- from migration_utils import validate_migration_path_components+ from common.migration_utils import validate_migration_path_componentswith pytest.raises(ValueError, match="Invalid app name"):validate_migration_path_components("../bad", "0001_test")def test_validate_raises_for_invalid_migration(self) -> None:"""validate_migration_path_components should raise for invalid migration."""- from migration_utils import validate_migration_path_components+ from common.migration_utils import validate_migration_path_componentswith pytest.raises(ValueError, match="Invalid migration name"):validate_migration_path_components("posthog", "bad_name")def test_is_valid_returns_bool(self) -> None:"""is_valid_migration_path should return bool without raising."""- from migration_utils import is_valid_migration_path+ from common.migration_utils import is_valid_migration_pathassert is_valid_migration_path("posthog", "0001_initial") is Trueassert is_valid_migration_path("../etc", "0001_passwd") is False@@ -193,7 +193,7 @@ class TestSharedMigrationUtils:def test_get_cached_migration_returns_none_for_invalid(self) -> None:"""get_cached_migration should return None for invalid inputs."""- from migration_utils import get_cached_migration+ from common.migration_utils import get_cached_migration# Invalid inputs should return None (not raise)assert get_cached_migration("../etc", "0001_passwd") is None@@ -203,7 +203,7 @@ class TestSharedMigrationUtils:"""cache_migration_file should return False for invalid inputs."""from pathlib import Path- from migration_utils import cache_migration_file+ from common.migration_utils import cache_migration_file# Invalid inputs should return False (not raise)assert cache_migration_file("../etc", "0001_passwd", Path("/fake")) is False