:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hogli): make env loading generic + drop 1Password from core (#59212)
Julian Bez3f6fe51fb49e
diff --git a/hogli.yaml b/hogli.yamlindex 948e0cf0e7f9..ed676437cacd 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -13,6 +13,14 @@ config:- mprocs-test.yaml- sandbox-entrypoint.py- lint-feature-flag-sorting.mjs+ env:+ files:+ - .env.development+ - .env.services+ secrets:+ file: .env.local+ marker: 'op://'+ wrap: [op, run, --env-file, '{file}', --]telemetry:# Write-only project token for PostHog's internal hogli project.# It cannot read data; safe to commit. Standalone hogli users get a blankdiff --git a/tools/hogli/AGENTS.md b/tools/hogli/AGENTS.mdnew file mode 100644index 000000000000..af6e851fdaa4--- /dev/null+++ b/tools/hogli/AGENTS.md@@ -0,0 +1,85 @@+# hogli — framework boundary and conventions++`tools/hogli/` is the **generic** developer-CLI framework published on PyPI as `hogli`. It is not PostHog-specific. PostHog happens to be its primary consumer today, but the framework must remain usable by any project that wants a YAML-driven dev CLI.++The PostHog-specific extension layer lives in `tools/hogli-commands/hogli_commands/` and is wired in via `config.commands_dir` + `config.boot_modules` in `hogli.yaml`.++## What belongs where++| Concern | `tools/hogli/` (core, PyPI) | `tools/hogli-commands/` (PostHog extension) |+| -------------------------------------------------------------------------- | --------------------------- | -------------------------------------------- |+| Command discovery (manifest schema, lazy click, extends) | ✅ | ❌ |+| Categorized help output | ✅ | ❌ |+| Telemetry framework (hook registration) | ✅ | ❌ |+| Generic env file loading (`config.env.files`) | ✅ | ❌ |+| Generic secret-wrapper hook (`config.env.secrets` — file, marker, wrap) | ✅ | ❌ |+| PostHog command implementations (`migrations:run`, `test`, `doctor`…) | ❌ | ✅ |+| PostHog precheck handlers / telemetry properties / hint hooks | ❌ | ✅ |+| Knowledge of `1Password` / `op` / `op://` specifically | ❌ | ❌ — _neither._ Use the generic wrap config |+| Knowledge of `.env.development` / `.env.services` / `.env.local` filenames | ❌ | ❌ — _neither._ Declare them in `hogli.yaml` |++## Reviewer checklist for PRs touching `tools/hogli/`++- [ ] Is the change generic, or does it bake in knowledge of a specific consumer (PostHog, a specific secrets tool, a specific filename)?+- [ ] If it's specific, does it need to be in core, or can it move to `tools/hogli-commands/` (or be declared in `hogli.yaml` config)?+- [ ] If new config schema, does it follow the existing pattern (`config.scripts_dir`, `config.commands_dir`, `config.boot_modules`)?+- [ ] Tests live in `tools/hogli/tests/` and use temp configs/files — they don't depend on PostHog's `hogli.yaml`.++## Prior art (env files + secrets)++Researched 2026-05-20 before committing to the `config.env` schema. Summary, so the next contributor doesn't have to re-derive this:++| Tool | Generic env files in core? | Secret resolution in core? |+| --------------------------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |+| [just](https://just.systems/man/en/settings.html) | ✅ (`dotenv-load`, `dotenv-filename`, `dotenv-path`, `dotenv-override`) | ❌ — wrap with `op run`/`doppler run` |+| [mise](https://mise.jdx.dev/environments/) | ✅ (`[env] _.file`, list, formats, redact) | ❌ — [maintainer explicitly excluded](https://github.com/jdx/mise/discussions/3712), built [fnox](https://github.com/jdx/fnox) as a separate tool |+| [task](https://taskfile.dev/docs/guide) | ✅ (`dotenv: [...]`, global + per-task) | ❌ |+| `op run` / `doppler run` / `infisical run` / `dotenvx` / `fnox` | ❌ (they wrap your command) | ✅ — _this is their whole product_ |+| [varlock](https://varlock.dev/) | ✅ + typed schema | ✅ via _provider plugins_ — but varlock is itself a dedicated secrets product, not a task runner |++**The pattern that emerged:** generic env-file loading is a normal CLI framework feature with a small contract. Specific secret resolution (1Password, Vault, Doppler…) is its own product, invoked as a wrapper via `<secret-cli> run -- <your-command>`. mise's maintainer puts it best:++> "mise reloads its environment too often and because secrets often rely on remote calls to things like kms or 1Password, it would make it too slow to be helpful."++Even 1Password's own docs don't recommend a "task runner integration" — they just say to invoke `op run --` directly.++## How hogli applies the pattern++**In core (generic):**++- `config.env.files: [...]` — list of dotenv files, loaded in order, first wins, shell env always wins.+- `config.env.secrets.{file, marker, wrap}` — optional generic wrapper hook. When the secrets file contains the marker substring AND the wrap binary is on PATH, hogli re-execs the whole invocation under the wrap command. When the binary isn't installed, hogli loads the file directly with marker-matching lines skipped (so literals don't leak as garbage strings). A `HOGLI_SECRETS_WRAPPED=1` sentinel prevents re-exec loops.++**Not in core:**++- `op` / `op://` / 1Password as concepts — _declare them in `config.env.secrets`_.+- Any specific file names (`.env.local`, `.env.development`, …) — _declare them in `config.env.files`_.++PostHog declares its setup in the root `hogli.yaml`:++```yaml+config:+ env:+ files:+ - .env.development+ - .env.services+ secrets:+ file: .env.local+ marker: 'op://'+ wrap: [op, run, --env-file, '{file}', --]+```++Same primitive works for Doppler (`wrap: [doppler, run, --]`), Infisical (`wrap: [infisical, run, --]`), Vault, dotenvx, fnox, or anything else that follows the wrap-and-exec convention.++## How not to evolve hogli++Anti-patterns flagged during PR review (don't re-introduce):++- Hardcoded filenames in `hogli/cli.py`. Always read from manifest.+- `if shutil.which("op"):` or any tool-specific binary check in core. The wrap config makes the binary configurable; use `shutil.which(wrap[0])` so any wrap tool the user declared works the same way.+- Provider-specific helpful error messages ("install brew install 1password-cli"). Core's error message should be tool-agnostic ("the configured wrap binary `<x>` is not on PATH"). The PostHog-side extension can layer richer messaging via the hooks API if needed.+- Adding behavior to `tools/hogli/src/hogli/cli.py` that's only useful to PostHog. Move it to `tools/hogli-commands/` and register via `boot_modules`.++## When in doubt++If you're about to add code to `tools/hogli/` and you're not sure whether it's generic enough: it probably isn't. Ask first, or write it in `tools/hogli-commands/` and we can promote it later if multiple consumers want it.diff --git a/tools/hogli/CLAUDE.md b/tools/hogli/CLAUDE.mdnew file mode 120000index 000000000000..47dc3e3d863c--- /dev/null+++ b/tools/hogli/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/tools/hogli/README.md b/tools/hogli/README.mdindex 1ee112214fc8..c49318f665b9 100644--- a/tools/hogli/README.md+++ b/tools/hogli/README.md@@ -251,6 +251,73 @@ def maybe_show_hint(command: str | None, exit_code: int) -> None:register_post_command_hook(maybe_show_hint)```+## Environment files++hogli can load dotenv files into every command's environment, the same way+[just](https://just.systems/man/en/settings.html),+[mise](https://mise.jdx.dev/environments/), and+[task](https://taskfile.dev/docs/guide) do. Declare them in `hogli.yaml`:++```yaml+config:+ env:+ files:+ - .env.development # loaded in order; earlier wins for duplicate keys+ - .env.services # shell env always wins (only_if_unset)+```++Missing files are silently skipped — same convention as the other tools — so+`.env.local` is fine to leave optional.++### Secret references (`config.env.secrets`)++Loading raw secrets from disk is a separate problem from loading dotenv files,+and tools like [1Password CLI](https://www.1password.dev/cli/),+[Doppler](https://docs.doppler.com/docs/cli), [Infisical](https://infisical.com/docs/cli/overview),+[Vault](https://developer.hashicorp.com/vault/docs/commands), and+[dotenvx](https://dotenvx.com/) all expose the same pattern: wrap the command+they should run, fetch the secrets at runtime, inject them into the subprocess+env. hogli supports this generically — no provider-specific knowledge in core:++```yaml+config:+ env:+ secrets:+ file: .env.local # the file that contains secret references+ marker: 'op://' # substring that triggers the wrap; required, non-empty+ wrap: [op, run, --env-file, '{file}', --]+```++What happens at startup:++1. If the secrets file exists AND contains `marker` AND `wrap[0]` is on `PATH`:+ hogli re-execs itself under `wrap` (with `{file}` substituted to the+ absolute path of the secrets file). The wrap binary resolves secrets and+ re-runs hogli with them in the env. A `HOGLI_SECRETS_WRAPPED=1` sentinel+ prevents infinite re-exec loops.+2. If the wrap binary is missing or the marker isn't present, hogli loads the+ file directly with marker-matching lines skipped (so unresolved `op://...`+ strings don't leak as garbage env values that produce confusing 401s+ downstream — only literal values get loaded).++Precedence in either path (highest wins): shell env > secrets file > env+files. So a literal override in `.env.local` always beats `.env.development`,+matching what `op run` does when it's available.++`marker` is required (not optional) — an "always wrap" mode would force a+process exec on every hogli invocation, which we never want.++The same shape works for Doppler (`wrap: [doppler, run, --]`), Vault+(`wrap: [vault, exec, --]`), Infisical (`wrap: [infisical, run, --]`),+dotenvx (`wrap: [dotenvx, run, --]`), or anything else following the+wrap-and-exec convention. hogli itself stays ignorant of which tool you use.++Why this split (and not built-in 1Password/Doppler/Vault knowledge)? Because+[mise's maintainer explicitly excluded secret resolution from mise core for+good reasons](https://github.com/jdx/mise/discussions/3712): secret APIs are+slow, caching them is a security risk, and CLI frameworks reload env too+often for that to play nicely. Better to delegate to a purpose-built tool.+## Configuration Reference```yaml@@ -259,6 +326,12 @@ config:boot_modules:- package.boot # Optional eager hook registration modulesscripts_dir: scripts # For bin_script resolution (default: bin/)+ env:+ files: [.env.development, .env.services] # Optional dotenv files (in order)+ secrets: # Optional secret-wrapper hook+ file: .env.local+ marker: 'op://'+ wrap: [op, run, --env-file, '{file}', --]metadata:categories:diff --git a/tools/hogli/src/hogli/cli.py b/tools/hogli/src/hogli/cli.pyindex 0979c0f09d09..c72c05a098eb 100644--- a/tools/hogli/src/hogli/cli.py+++ b/tools/hogli/src/hogli/cli.py@@ -13,6 +13,7 @@ import shutilimport platformimport importlibfrom collections import defaultdict+from pathlib import Pathfrom typing import Anyimport click@@ -171,7 +172,10 @@ def _auto_update_manifest() -> None:@click.pass_contextdef cli(ctx: click.Context) -> None:"""hogli - YAML-driven developer CLI."""- _load_default_env_files()+ # Skip env loading during shell completion — completion fires this+ # callback for every Tab press and doesn't need the env populated.+ if not ctx.resilient_parsing:+ _apply_env_config()# Auto-update manifest on every invocation (but skip for meta:check and git hooks)# Skip during git hooks to prevent manifest modifications during lint-staged executionin_git_hook = os.environ.get("GIT_DIR") is not None or os.environ.get("HUSKY") is not None@@ -255,15 +259,34 @@ def concepts() -> None:click.echo()-def _load_env_file(path: os.PathLike[str], only_if_unset: bool = True) -> None:- """Load environment variables from a file (KEY=VALUE per line, # comments).-- op:// refs are always skipped — they only get resolved by `op run`, never by- sourcing the file directly. Setting them as literal strings would break- downstream services with cryptic API errors.+# Sentinel that prevents `_apply_env_config` from re-execing into the wrap+# command in an infinite loop. Set by hogli right before exec'ing the wrap+# binary; checked at the top of `_apply_env_config` on subsequent invocations.+_SECRETS_WRAPPED_ENV = "HOGLI_SECRETS_WRAPPED"++# Substituted to the absolute path of the secrets file when building the wrap+# argv. Kept as a constant so the README, AGENTS.md, and runtime stay in sync.+_WRAP_FILE_PLACEHOLDER = "{file}"+++def _load_env_file(+ path: os.PathLike[str],+ only_if_unset: bool = True,+ skip_pattern: str | None = None,+) -> None:+ """Load environment variables from a dotenv file (KEY=VALUE, # comments).++ Args:+ path: Path to the env file. Missing files are silently skipped+ (matches just/mise/task convention so optional `.env.local` etc.+ don't error).+ only_if_unset: If True (default), don't overwrite existing env vars.+ Lets shell env always win.+ skip_pattern: If set, any line whose VALUE substring-matches this+ pattern is skipped entirely. Used to keep secret-reference lines+ (e.g. `op://...`) from leaking into the environment as literal+ strings when the resolver isn't available. None disables filtering."""- from pathlib import Path-env_file = Path(path)if not env_file.exists():return@@ -273,75 +296,124 @@ def _load_env_file(path: os.PathLike[str], only_if_unset: bool = True) -> None:if not line or line.startswith("#") or "=" not in line:continuename, _, value = line.partition("=")- # Substring match so quoted (`KEY="op://..."`) and space-padded- # (`KEY= op://...`) forms are also skipped — matches what op run itself- # accepts. Leaking these as literals would break downstream services- # with cryptic API errors.- if "op://" in value:+ if skip_pattern and skip_pattern in value:continueif only_if_unset and name in os.environ:continueos.environ[name] = value-def _load_default_env_files() -> None:- """Load .env.development and .env.services for every hogli subcommand.+def _apply_env_config() -> None:+ """Apply ``config.env`` from hogli.yaml: load files, optionally re-exec via wrap.++ Behavior depends on what's declared in the manifest:++ - No ``config.env``: no-op. hogli stays a transparent CLI.+ - ``config.env.files``: each file is loaded with only_if_unset=True. First+ file in the list wins for duplicate keys; shell env always wins.+ - ``config.env.secrets``: wrapper for a secrets file (e.g. one containing+ 1Password ``op://`` refs).+ * If the file exists, contains the marker, and the wrap binary is on+ PATH: set the ``HOGLI_SECRETS_WRAPPED`` sentinel and ``execvp`` into+ the wrap command, which re-runs hogli with secrets resolved. Files+ are pre-loaded so wrap's child inherits them.+ * If the wrap binary is missing or the marker doesn't hit, load the+ file directly. Lines whose value contains the marker are skipped+ (so unresolved refs don't leak as garbage env values).+ * If the sentinel is already set we are the child of a wrap re-exec —+ skip the wrap entirely and proceed to load the files normally.++ Precedence (in both wrap-resolved and fallback paths, highest wins):+ shell env > secrets file > env files (earlier files in the list win for+ duplicate keys).+ """+ manifest = get_manifest()+ try:+ secrets = manifest.secrets_config+ env_files = manifest.env_files+ except ValueError as e:+ click.echo(f"⚠️ Invalid config.env in hogli.yaml: {e}", err=True)+ return++ # Consume the sentinel — we're either the wrap-child (sentinel set) or+ # the initial parent (sentinel unset). Pop so the sentinel never leaks+ # to subprocesses or repeat in-process calls.+ already_wrapped = os.environ.pop(_SECRETS_WRAPPED_ENV, None) is not None++ if secrets is not None and not already_wrapped:+ _maybe_reexec_via_wrap(secrets, env_files)++ # Reached here = no re-exec happened (no marker hit, file missing, or+ # wrap binary missing). Load secrets BEFORE env_files so .env.local+ # literals override .env.development / .env.services — matches the+ # wrap-resolved path's precedence (where op layers .env.local on top).+ _load_env_file(secrets["file"], only_if_unset=True, skip_pattern=secrets["marker"])++ for path in env_files:+ _load_env_file(path, only_if_unset=True)+- Mirrors bin/start so commands that shell out to manage.py / bin scripts- (dev:reset, migrations:run, etc.) see the same service connection defaults- the dev stack uses. Shell vars win; we never overwrite.+def _maybe_reexec_via_wrap(secrets: dict[str, Any], env_files: list[Path]) -> None:+ """Re-exec hogli under the configured wrap command if the secrets file warrants it.- .env.local is intentionally NOT loaded here — it can contain 1Password- op:// refs that only `hogli run` knows how to resolve via `op run`.+ Returns normally if no re-exec is needed (caller falls through to direct+ file loading). Otherwise replaces the current process via ``os.execvp``."""- _load_env_file(REPO_ROOT / ".env.development", only_if_unset=True)- _load_env_file(REPO_ROOT / ".env.services", only_if_unset=True)+ secrets_file: Path = secrets["file"]+ marker: str = secrets["marker"]+ wrap: list[str] | None = secrets["wrap"]+ if wrap is None or not secrets_file.exists():+ return[email protected](name="run", help="Run a command with resolved environment (1Password + defaults)")+ # Marker-gated re-exec: only wrap when the file actually references the+ # external resolver. Saves a process exec on dev workflows that haven't+ # set up secrets yet.+ try:+ if marker not in secrets_file.read_text():+ return+ except OSError:+ return++ wrap_binary = wrap[0]+ if not shutil.which(wrap_binary):+ click.echo(+ f"⚠️ {secrets_file.name} contains '{marker}' refs but the configured wrap binary "+ f"'{wrap_binary}' is not on PATH.",+ err=True,+ )+ click.echo(+ f" Refs will be skipped — services that need them will fail with their own errors. "+ f"Install '{wrap_binary}' or replace the refs with literal values in {secrets_file.name}.",+ err=True,+ )+ return++ # Pre-load non-secrets files so the wrap binary's child inherits them.+ # The wrap binary layers secrets on top, overriding these for any key+ # also defined in the secrets file.+ for path in env_files:+ _load_env_file(path, only_if_unset=True)++ resolved_wrap = [arg.replace(_WRAP_FILE_PLACEHOLDER, str(secrets_file)) for arg in wrap]+ os.environ[_SECRETS_WRAPPED_ENV] = "1"+ os.execvp(resolved_wrap[0], [*resolved_wrap, sys.executable, "-m", "hogli", *sys.argv[1:]])++[email protected](name="run", help="Run a command with the manifest's resolved environment")@click.argument("command", nargs=-1, required=True)def run_with_env(command: tuple[str, ...]) -> None:- """Run a command with PostHog environment variables.+ """Run a command with the env loaded from ``config.env`` in hogli.yaml.- Loads .env.development defaults and .env.local overrides.- If .env.local contains 1Password references (op://), resolves them via `op run`.-- Note: When using 1Password, op run's .env.local takes precedence over shell env.- This is op's design — secrets from 1Password are meant to win.+ Env loading (files + optional wrap) is applied by the parent ``cli()``+ group before this command runs, so by the time we get here ``os.environ``+ already reflects whatever the manifest declared. This command is just a+ thin ``execvp`` so callers don't need to repeat the wrapper pattern.Examples:hogli run ./manage.py shellhogli run pytest posthog/api/"""- env_dev = REPO_ROOT / ".env.development"- env_services = REPO_ROOT / ".env.services"- env_local = REPO_ROOT / ".env.local"-- has_op_refs = env_local.exists() and "op://" in env_local.read_text()-- if has_op_refs and shutil.which("op"):- # Pre-load .env.development and .env.services (only if not already set in shell)- # so op run's child inherits them. op run then layers .env.local on top,- # overriding any variable it defines — including ones from shell. That's- # the precedence the docstring above promises: shell env > .env.local- # only applies to vars NOT defined in .env.local.- _load_env_file(env_dev, only_if_unset=True)- _load_env_file(env_services, only_if_unset=True)- os.execvp("op", ["op", "run", f"--env-file={env_local}", "--", *command])- return-- # No op refs OR op CLI not installed — source files directly. _load_env_file- # skips op:// lines, so missing op CLI degrades gracefully: vars that needed- # 1Password are simply unset, and the downstream command fails with its own- # "missing key" error rather than swallowing a literal "op://..." string.- if has_op_refs:- click.echo("⚠️ .env.local contains 1Password refs (op://) but 'op' CLI is not installed.", err=True)- click.echo(" These refs will be skipped. Install: brew install 1password-cli", err=True)- click.echo(" Or replace op:// refs with literal values in .env.local.", err=True)-- _load_env_file(env_local, only_if_unset=True)- _load_env_file(env_dev, only_if_unset=True)- _load_env_file(env_services, only_if_unset=True)os.execvp(command[0], list(command))diff --git a/tools/hogli/src/hogli/manifest.py b/tools/hogli/src/hogli/manifest.pyindex cd79d574c793..f418dd2efac1 100644--- a/tools/hogli/src/hogli/manifest.py+++ b/tools/hogli/src/hogli/manifest.py@@ -147,21 +147,11 @@ class Manifest: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")-+ path = self._resolve_repo_relative_path("config.commands_dir", configured)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@property@@ -175,14 +165,85 @@ class Manifest:Always returns a path (may not exist)."""configured = self.config.get("scripts_dir")- if configured:- path = (REPO_ROOT / configured).resolve()- try:- path.relative_to(REPO_ROOT.resolve())- except ValueError:- raise ValueError(f"config.scripts_dir '{configured}' resolves outside the repo root")- return path- return REPO_ROOT / "bin"+ if not configured:+ return REPO_ROOT / "bin"+ return self._resolve_repo_relative_path("config.scripts_dir", configured)++ @property+ def env_files(self) -> list[Path]:+ """Resolved env files to load before every command (`config.env.files`).++ Files are NOT checked for existence here — the loader treats missing+ files as silent no-ops (matches just/mise/task convention).++ Precedence between files: hogli loads in the order returned here; the+ loader uses only-if-unset so earlier entries win for duplicate keys.+ """+ env_config = self.config.get("env") or {}+ raw_files = env_config.get("files") or []+ if not isinstance(raw_files, list):+ raise ValueError("config.env.files must be a list of repo-relative paths")+ resolved: list[Path] = []+ for entry in raw_files:+ if not isinstance(entry, str) or not entry:+ raise ValueError("config.env.files entries must be non-empty strings")+ resolved.append(self._resolve_repo_relative_path("config.env.files", entry))+ return resolved++ @property+ def secrets_config(self) -> dict[str, Any] | None:+ """Parsed `config.env.secrets` block, or None if unset.++ Returned dict has:+ - ``file``: absolute Path to the secrets file (caller checks existence)+ - ``marker``: required, non-empty substring that triggers the wrap.+ Required (rather than optional) to keep behavior unambiguous: an+ "always wrap" mode would force a process exec on every invocation+ even when no secrets need resolving, which we never want.+ - ``wrap``: list[str], with ``{file}`` placeholder substituted to the+ absolute path of ``file`` at call time by the loader (not here, so+ the manifest stays declarative).+ """+ env_config = self.config.get("env") or {}+ secrets = env_config.get("secrets")+ if secrets is None:+ return None+ if not isinstance(secrets, dict):+ raise ValueError("config.env.secrets must be a mapping")++ file_str = secrets.get("file")+ if not isinstance(file_str, str) or not file_str:+ raise ValueError("config.env.secrets.file is required and must be a non-empty string")+ file_path = self._resolve_repo_relative_path("config.env.secrets.file", file_str)++ marker = secrets.get("marker")+ if not isinstance(marker, str) or not marker:+ raise ValueError("config.env.secrets.marker is required and must be a non-empty string")++ wrap = secrets.get("wrap")+ if wrap is not None:+ if not isinstance(wrap, list) or not all(isinstance(p, str) for p in wrap):+ raise ValueError("config.env.secrets.wrap must be a list of strings when set")+ if not wrap:+ raise ValueError("config.env.secrets.wrap must not be empty when set")++ return {"file": file_path, "marker": marker, "wrap": wrap}++ def _resolve_repo_relative_path(self, key: str, raw: str) -> Path:+ """Resolve a repo-relative path used in config.*, with sandbox checks.++ Shared by commands_dir, scripts_dir, env_files, and secrets.file —+ every config path must be relative and stay inside the repo root.+ """+ candidate = Path(raw)+ if candidate.is_absolute():+ raise ValueError(f"{key} '{raw}' must be relative to the repo root")+ resolved = (REPO_ROOT / candidate).resolve()+ try:+ resolved.relative_to(REPO_ROOT.resolve())+ except ValueError:+ raise ValueError(f"{key} '{raw}' resolves outside the repo root")+ return resolveddef get_category_for_command(self, command_name: str) -> str:"""Get category for a command based on which section it's placed in.diff --git a/tools/hogli/tests/test_cli.py b/tools/hogli/tests/test_cli.pyindex 782abc9deb96..e35c2ec6fb1b 100644--- a/tools/hogli/tests/test_cli.py+++ b/tools/hogli/tests/test_cli.py@@ -204,7 +204,7 @@ class TestHelpText:class TestLoadEnvFile:- """Test _load_env_file behavior — esp. graceful handling of op:// refs."""+ """Test _load_env_file behavior — esp. the optional skip_pattern."""def _write_env(self, tmp_path, content: str):env_file = tmp_path / ".env.test"@@ -220,13 +220,13 @@ class TestLoadEnvFile:],ids=["bare", "double-quoted", "leading-space"],)- def test_skips_op_refs_so_they_dont_leak_as_literals(+ def test_skip_pattern_filters_matching_values(self, tmp_path, monkeypatch: pytest.MonkeyPatch, op_line: str) -> None:- """op:// values must never be set as literal env vars — they'd break downstream services.+ """skip_pattern filters values that should never leak as literal env vars.- Covers bare, quoted, and space-padded forms (op run itself accepts all three,- so users may write any of them).+ Covers bare/quoted/space-padded forms (op run itself accepts all three),+ so users may write any of them and the substring match still skips them."""from hogli.cli import _load_env_file@@ -234,11 +234,28 @@ class TestLoadEnvFile:monkeypatch.delenv("OPENAI_API_KEY", raising=False)monkeypatch.delenv("LITERAL_VAR", raising=False)- _load_env_file(env_file)+ _load_env_file(env_file, skip_pattern="op://")assert "OPENAI_API_KEY" not in os.environassert os.environ["LITERAL_VAR"] == "actual_value"+ def test_no_skip_pattern_loads_everything(self, tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ """Without skip_pattern the loader stays a transparent dotenv parser.++ Important so the loader is reusable for plain dotenv files that have+ nothing to do with secrets resolution.+ """+ from hogli.cli import _load_env_file++ env_file = self._write_env(tmp_path, "API_KEY=op://foo/bar\nOTHER=baz\n")+ monkeypatch.delenv("API_KEY", raising=False)+ monkeypatch.delenv("OTHER", raising=False)++ _load_env_file(env_file) # no skip_pattern++ assert os.environ["API_KEY"] == "op://foo/bar"+ assert os.environ["OTHER"] == "baz"+def test_missing_file_is_silent(self, tmp_path) -> None:"""Missing env files should not raise — caller may pass an optional file."""from hogli.cli import _load_env_file@@ -264,3 +281,276 @@ class TestLoadEnvFile:_load_env_file(env_file)assert os.environ["REAL_VAR"] == "42"+++class TestApplyEnvConfig:+ """End-to-end behavior of _apply_env_config against mocked manifest config.++ Patches `get_manifest` so each test can declare its own env_files /+ secrets_config and we don't depend on PostHog's hogli.yaml. The mocked+ manifest also keeps existing PostHog tests in the same file unaffected.+ """++ def _make_manifest(self, env_files=None, secrets_config=None) -> MagicMock:+ m = MagicMock()+ m.env_files = env_files or []+ m.secrets_config = secrets_config+ return m++ def test_no_env_config_is_noop(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Generic hogli installs with no `config.env` should not touch os.environ.++ The PyPI hogli package must stay transparent for users who don't opt in.+ """+ from hogli.cli import _apply_env_config++ monkeypatch.setattr("hogli.cli.get_manifest", lambda: self._make_manifest())+ monkeypatch.delenv("UNRELATED_VAR", raising=False)+ before = dict(os.environ)++ _apply_env_config()++ assert os.environ == before++ def test_loads_files_in_declared_order_first_wins(self, tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ """Earlier files in `config.env.files` win for duplicate keys (matches just/mise/task)."""+ from hogli.cli import _apply_env_config++ first = tmp_path / ".env.first"+ second = tmp_path / ".env.second"+ first.write_text("SHARED=from_first\nONLY_FIRST=1\n")+ second.write_text("SHARED=from_second\nONLY_SECOND=2\n")++ monkeypatch.setattr(+ "hogli.cli.get_manifest",+ lambda: self._make_manifest(env_files=[first, second]),+ )+ for k in ("SHARED", "ONLY_FIRST", "ONLY_SECOND", "HOGLI_SECRETS_WRAPPED"):+ monkeypatch.delenv(k, raising=False)++ _apply_env_config()++ assert os.environ["SHARED"] == "from_first"+ assert os.environ["ONLY_FIRST"] == "1"+ assert os.environ["ONLY_SECOND"] == "2"++ def test_shell_env_always_wins(self, tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ """Shell env beats every config file — same precedence as bin/start."""+ from hogli.cli import _apply_env_config++ env_file = tmp_path / ".env"+ env_file.write_text("OVERRIDE_ME=from_file\n")++ monkeypatch.setattr(+ "hogli.cli.get_manifest",+ lambda: self._make_manifest(env_files=[env_file]),+ )+ monkeypatch.setenv("OVERRIDE_ME", "from_shell")+ monkeypatch.delenv("HOGLI_SECRETS_WRAPPED", raising=False)++ _apply_env_config()++ assert os.environ["OVERRIDE_ME"] == "from_shell"++ def test_secrets_file_without_marker_loads_literals_directly(+ self, tmp_path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Secrets file with no marker hit: load directly, no wrap re-exec."""+ from hogli.cli import _apply_env_config++ secrets_file = tmp_path / ".env.local"+ secrets_file.write_text("PLAIN_KEY=plain_value\n")++ secrets = {+ "file": secrets_file,+ "marker": "op://",+ "wrap": ["op", "run", "--env-file", "{file}", "--"],+ }+ monkeypatch.setattr(+ "hogli.cli.get_manifest",+ lambda: self._make_manifest(secrets_config=secrets),+ )+ monkeypatch.delenv("PLAIN_KEY", raising=False)+ monkeypatch.delenv("HOGLI_SECRETS_WRAPPED", raising=False)++ with patch("os.execvp") as mock_exec:+ _apply_env_config()++ mock_exec.assert_not_called()+ assert os.environ["PLAIN_KEY"] == "plain_value"++ def test_secrets_file_overrides_env_files_in_fallback_path(self, tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ """In the no-wrap fallback path, .env.local literal values must win+ over .env.development / .env.services — same precedence the wrap path+ gives (where the resolver layers .env.local on top). This guards the+ regression Codex flagged: loading env_files first with only_if_unset+ meant .env.development was beating .env.local literal overrides."""+ from hogli.cli import _apply_env_config++ secrets_file = tmp_path / ".env.local"+ secrets_file.write_text("SHARED_KEY=local_wins\n")+ env_file = tmp_path / ".env.development"+ env_file.write_text("SHARED_KEY=dev_loses\nDEV_ONLY=dev_value\n")++ secrets = {+ "file": secrets_file,+ "marker": "op://",+ "wrap": ["op", "run", "--env-file", "{file}", "--"],+ }+ monkeypatch.setattr(+ "hogli.cli.get_manifest",+ lambda: self._make_manifest(env_files=[env_file], secrets_config=secrets),+ )+ for k in ("SHARED_KEY", "DEV_ONLY", "HOGLI_SECRETS_WRAPPED"):+ monkeypatch.delenv(k, raising=False)++ with patch("os.execvp") as mock_exec:+ _apply_env_config()++ mock_exec.assert_not_called()+ assert os.environ["SHARED_KEY"] == "local_wins"+ assert os.environ["DEV_ONLY"] == "dev_value"++ def test_missing_secrets_file_falls_through_silently(self, tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ """No `.env.local` file at all (fresh user) — env_files still load and+ no errors are raised. This is the bin/start "if one does not have the+ .env.local file already" scenario."""+ from hogli.cli import _apply_env_config++ env_file = tmp_path / ".env.development"+ env_file.write_text("DEV_ONLY=ok\n")+ secrets = {+ "file": tmp_path / ".env.local", # doesn't exist+ "marker": "op://",+ "wrap": ["op", "run", "--env-file", "{file}", "--"],+ }+ monkeypatch.setattr(+ "hogli.cli.get_manifest",+ lambda: self._make_manifest(env_files=[env_file], secrets_config=secrets),+ )+ for k in ("DEV_ONLY", "HOGLI_SECRETS_WRAPPED"):+ monkeypatch.delenv(k, raising=False)++ with patch("os.execvp") as mock_exec:+ _apply_env_config()++ mock_exec.assert_not_called()+ assert os.environ["DEV_ONLY"] == "ok"++ def test_marker_hit_with_wrap_binary_present_reexecs(self, tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ """When marker matches and wrap binary is on PATH, hogli re-execs under it.++ Verifies the wrap command is built with `{file}` substituted, the+ sentinel is set so the child won't loop, and pre-existing env_files+ were loaded into os.environ so the wrap child inherits them.+ """+ from hogli.cli import _apply_env_config++ env_file = tmp_path / ".env.development"+ env_file.write_text("PRELOADED=yes\n")+ secrets_file = tmp_path / ".env.local"+ secrets_file.write_text("API_KEY=op://vault/item/credential\n")++ secrets = {+ "file": secrets_file,+ "marker": "op://",+ "wrap": ["op", "run", "--env-file", "{file}", "--"],+ }+ monkeypatch.setattr(+ "hogli.cli.get_manifest",+ lambda: self._make_manifest(env_files=[env_file], secrets_config=secrets),+ )+ for k in ("PRELOADED", "HOGLI_SECRETS_WRAPPED"):+ monkeypatch.delenv(k, raising=False)++ with (+ patch("shutil.which", return_value="/usr/local/bin/op"),+ patch("os.execvp") as mock_exec,+ ):+ _apply_env_config()++ mock_exec.assert_called_once()+ args, _kwargs = mock_exec.call_args+ binary, argv = args+ assert binary == "op"+ # {file} got substituted with the absolute path+ assert str(secrets_file) in argv+ assert "{file}" not in argv+ # argv re-runs hogli (so the child completes the original invocation)+ assert any("hogli" in arg for arg in argv)+ # pre-loaded files were applied before the exec (so wrap-child inherits)+ assert os.environ["PRELOADED"] == "yes"+ # sentinel set to prevent infinite re-exec loop+ assert os.environ["HOGLI_SECRETS_WRAPPED"] == "1"++ def test_marker_hit_but_wrap_binary_missing_falls_back_with_warning(+ self, tmp_path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture+ ) -> None:+ """When wrap binary isn't installed, load files but skip ref lines + warn.++ This is the user-friendly degradation: the dev still gets `.env.local`+ literal values (if any), but the unresolved refs don't leak as garbage+ env values that produce confusing 401s downstream.+ """+ from hogli.cli import _apply_env_config++ secrets_file = tmp_path / ".env.local"+ secrets_file.write_text("OPENAI_API_KEY=op://vault/item/credential\nLITERAL=keep_me\n")++ secrets = {+ "file": secrets_file,+ "marker": "op://",+ "wrap": ["op", "run", "--env-file", "{file}", "--"],+ }+ monkeypatch.setattr(+ "hogli.cli.get_manifest",+ lambda: self._make_manifest(secrets_config=secrets),+ )+ for k in ("OPENAI_API_KEY", "LITERAL", "HOGLI_SECRETS_WRAPPED"):+ monkeypatch.delenv(k, raising=False)++ with (+ patch("shutil.which", return_value=None),+ patch("os.execvp") as mock_exec,+ ):+ _apply_env_config()++ mock_exec.assert_not_called()+ assert "OPENAI_API_KEY" not in os.environ+ assert os.environ["LITERAL"] == "keep_me"+ err = capsys.readouterr().err+ assert "op://" in err+ assert "op" in err # wrap binary name surfaced++ def test_sentinel_skips_reexec_so_child_doesnt_loop(self, tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ """After wrap re-execs hogli, the child sees HOGLI_SECRETS_WRAPPED and skips wrap.++ Without this, the wrap binary would re-exec hogli forever.+ """+ from hogli.cli import _apply_env_config++ secrets_file = tmp_path / ".env.local"+ secrets_file.write_text("API_KEY=op://vault/item/credential\n")++ secrets = {+ "file": secrets_file,+ "marker": "op://",+ "wrap": ["op", "run", "--env-file", "{file}", "--"],+ }+ monkeypatch.setattr(+ "hogli.cli.get_manifest",+ lambda: self._make_manifest(secrets_config=secrets),+ )+ # Simulate being the child of a wrap re-exec: sentinel set, wrap already+ # populated the env via op run (so OPENAI_API_KEY would be in env).+ monkeypatch.setenv("HOGLI_SECRETS_WRAPPED", "1")+ monkeypatch.setenv("API_KEY", "resolved_by_op")++ with patch("os.execvp") as mock_exec:+ _apply_env_config()++ mock_exec.assert_not_called()+ # Wrap binary's resolved value wins; the file isn't sourced over it+ assert os.environ["API_KEY"] == "resolved_by_op"+ # Sentinel is consumed so subsequent in-process calls behave normally+ assert "HOGLI_SECRETS_WRAPPED" not in os.environdiff --git a/tools/hogli/tests/test_manifest.py b/tools/hogli/tests/test_manifest.pyindex c949307817f8..3869bb9ce3df 100644--- a/tools/hogli/tests/test_manifest.py+++ b/tools/hogli/tests/test_manifest.py@@ -260,3 +260,109 @@ class TestCommandsDir:manifest = Manifest()with pytest.raises(ValueError, match="must be relative"):_ = manifest.commands_dir+++class TestEnvConfig:+ """Test `config.env` schema parsing.++ Uses monkeypatch (not `with patch(...)`) so the module-level REPO_ROOT+ swap survives the assertions — the existing TestCommandsDir style of+ asserting inside a `with patch` block doesn't compose with `pytest.raises`+ or with multi-assertion tests.+ """++ @pytest.fixture+ def manifest_at(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ """Factory: build a Manifest rooted at tmp_path with the given config."""+ # Resolve through symlinks once so equality checks work on macOS where+ # /var/folders -> /private/var/folders.+ repo = tmp_path.resolve()++ def _build(config: dict) -> Manifest:+ monkeypatch.setattr("hogli.manifest.REPO_ROOT", repo)+ monkeypatch.setattr("hogli.manifest.MANIFEST_FILE", repo / "hogli.yaml")+ monkeypatch.setattr(Manifest, "_load", lambda self: {"config": config})+ return Manifest()++ return _build++ def test_unset_returns_empty_and_none(self, manifest_at) -> None:+ """Without `config.env`, both accessors stay quiet — generic hogli is transparent."""+ manifest = manifest_at({})+ assert manifest.env_files == []+ assert manifest.secrets_config is None++ def test_env_files_resolves_repo_relative_paths(self, tmp_path: Path, manifest_at) -> None:+ manifest = manifest_at({"env": {"files": [".env.development", ".env.services"]}})+ repo = tmp_path.resolve()+ assert manifest.env_files == [repo / ".env.development", repo / ".env.services"]++ def test_env_files_rejects_absolute_path(self, tmp_path: Path, manifest_at) -> None:+ manifest = manifest_at({"env": {"files": [str(tmp_path / ".env")]}})+ with pytest.raises(ValueError, match="must be relative"):+ _ = manifest.env_files++ def test_env_files_rejects_escape_outside_repo(self, manifest_at) -> None:+ manifest = manifest_at({"env": {"files": ["../etc/passwd"]}})+ with pytest.raises(ValueError, match="outside the repo root"):+ _ = manifest.env_files++ def test_env_files_rejects_non_list(self, manifest_at) -> None:+ manifest = manifest_at({"env": {"files": ".env"}})+ with pytest.raises(ValueError, match="must be a list"):+ _ = manifest.env_files++ def test_env_files_rejects_non_string_entry(self, manifest_at) -> None:+ """YAML can drop a number or mapping into the list — reject explicitly so+ we don't silently `str()`-coerce it into a surprise path like `.` or `42`."""+ manifest = manifest_at({"env": {"files": [".env.development", 42]}})+ with pytest.raises(ValueError, match="non-empty strings"):+ _ = manifest.env_files++ def test_secrets_config_full(self, tmp_path: Path, manifest_at) -> None:+ manifest = manifest_at(+ {+ "env": {+ "secrets": {+ "file": ".env.local",+ "marker": "op://",+ "wrap": ["op", "run", "--env-file", "{file}", "--"],+ }+ }+ }+ )+ cfg = manifest.secrets_config+ assert cfg is not None+ assert cfg["file"] == tmp_path.resolve() / ".env.local"+ assert cfg["marker"] == "op://"+ assert cfg["wrap"] == ["op", "run", "--env-file", "{file}", "--"]++ def test_secrets_config_requires_file(self, manifest_at) -> None:+ manifest = manifest_at({"env": {"secrets": {"marker": "op://", "wrap": ["op", "run", "--"]}}})+ with pytest.raises(ValueError, match="file is required"):+ _ = manifest.secrets_config++ def test_secrets_config_requires_marker(self, manifest_at) -> None:+ """Marker must be set + non-empty: 'always wrap' would force a process+ exec on every invocation, and an empty string is too ambiguous to+ deserve a behavior."""+ manifest = manifest_at({"env": {"secrets": {"file": ".env.local", "wrap": ["op", "run", "--"]}}})+ with pytest.raises(ValueError, match="marker is required"):+ _ = manifest.secrets_config++ def test_secrets_config_rejects_empty_marker(self, manifest_at) -> None:+ manifest = manifest_at({"env": {"secrets": {"file": ".env.local", "marker": "", "wrap": ["op"]}}})+ with pytest.raises(ValueError, match="marker is required"):+ _ = manifest.secrets_config++ def test_secrets_config_rejects_empty_wrap(self, manifest_at) -> None:+ manifest = manifest_at({"env": {"secrets": {"file": ".env.local", "marker": "op://", "wrap": []}}})+ with pytest.raises(ValueError, match="must not be empty"):+ _ = manifest.secrets_config++ def test_secrets_config_rejects_non_string_wrap_items(self, manifest_at) -> None:+ manifest = manifest_at(+ {"env": {"secrets": {"file": ".env.local", "marker": "op://", "wrap": ["op", 42, "--"]}}}+ )+ with pytest.raises(ValueError, match="list of strings"):+ _ = manifest.secrets_config