: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
fix(devex): bin/start silent exit + 1Password CLI graceful fallback (#59183)
Julian Beza5aa9b560abb
diff --git a/bin/start b/bin/startindex 7866e70acf83..6ccaa6aef07f 100755--- a/bin/start+++ b/bin/start@@ -16,8 +16,10 @@ if [ -f "$REPOSITORY_ROOT/.env.local" ] && grep -q "op://" "$REPOSITORY_ROOT/.enexport _POSTHOG_OP_RESOLVED=1exec op run --env-file="$REPOSITORY_ROOT/.env.local" -- "$0" "$@"else- echo "⚠️ .env.local contains 1Password refs (op://) but 'op' CLI not found"- echo " Install: brew install 1password-cli"+ echo "⚠️ .env.local contains 1Password refs (op://) but 'op' CLI is not installed."+ echo " These refs will be skipped — services that depend on them will fail with their own"+ echo " 'missing key' errors. To resolve them automatically, install: brew install 1password-cli"+ echo " Or replace op:// refs with literal values in .env.local."fififi@@ -45,16 +47,37 @@ trap cleanup_lock EXIT INT TERM## Source env files respecting precedence:# shell env > .env.local > .env.development > .env.services-# Only set vars that aren't already in the environment+# Only set vars that aren't already in the environment.+# op:// refs are always skipped here — they only get resolved by `op run` in+# the re-exec block above. Sourcing them as literals would set env vars to+# garbage strings that break downstream services with cryptic errors.source_env_defaults() {+ if [[ ! -f "$1" ]]; then+ echo "⚠️ Expected env file missing: $1 — skipping. Did your checkout get truncated?" >&2+ return 0+ fi+ # Use explicit if/fi (not `[[ ... ]] && cmd`) so the loop body always+ # returns 0. With `&&`, the last iteration's `[[ -z … ]]` returning false+ # (variable already set) makes the function return non-zero, and `set -e`+ # silently kills the entire script — no error, no output, just exit. This+ # was the root cause of "hogli start" failing in Cursor and other terminals+ # where some of the trailing env vars happened to already be in the shell.while IFS='=' read -r name value; do[[ -z "$name" || "$name" == \#* ]] && continue- [[ -z "${!name:-}" ]] && export "$name=$value"+ # Substring match so quoted ("op://...") and space-padded values are+ # also caught — mirrors what op run itself accepts.+ [[ "$value" == *op://* ]] && continue+ if [[ -z "${!name:-}" ]]; then+ export "$name=$value"+ fidone < "$1"}# .env.local: already in env if processed by op run, otherwise source directlyif [[ -f "$REPOSITORY_ROOT/.env.local" ]] && [[ -z "$_POSTHOG_OP_RESOLVED" ]]; thensource_env_defaults "$REPOSITORY_ROOT/.env.local"+elif [[ ! -f "$REPOSITORY_ROOT/.env.local" ]] && [[ -f "$REPOSITORY_ROOT/.env.local.example" ]]; then+ echo "💡 No .env.local found — running with committed defaults only."+ echo " For personal overrides or secrets: cp .env.local.example .env.local"fisource_env_defaults "$REPOSITORY_ROOT/.env.development"source_env_defaults "$REPOSITORY_ROOT/.env.services"diff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.mdindex 9cd0c33cc021..d4202903af54 100644--- a/docs/published/handbook/engineering/developing-locally.md+++ b/docs/published/handbook/engineering/developing-locally.md@@ -170,6 +170,8 @@ hogli start # auto-resolves op:// via `op run`If `bin/start` sees any `op://` reference in `.env.local`, it re-execs itself under `op run --env-file=.env.local`. No need to remember the wrapper command.+If the `op` CLI isn't installed, `op://` lines are skipped (rather than sourced as literal `op://...` strings that break downstream services with cryptic errors). Services that need those secrets will fail with their own "missing key" errors — install `1password-cli` or replace the refs with literal values.+### Running in detached modeBy default, `hogli start` runs interactively with a terminal UI (phrocs) that displays logs from all processes. If you prefer to run the dev stack in the background without an attached terminal, use detached mode:diff --git a/tools/hogli/src/hogli/cli.py b/tools/hogli/src/hogli/cli.pyindex 71b990a415f0..e8cf56ef8df0 100644--- a/tools/hogli/src/hogli/cli.py+++ b/tools/hogli/src/hogli/cli.py@@ -255,7 +255,12 @@ def concepts() -> None: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)."""+ """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.+ """from pathlib import Pathenv_file = Path(path)@@ -267,6 +272,12 @@ 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:+ continueif only_if_unset and name in os.environ:continueos.environ[name] = value@@ -293,21 +304,30 @@ def run_with_env(command: tuple[str, ...]) -> None:has_op_refs = env_local.exists() and "op://" in env_local.read_text()- if has_op_refs:- if not shutil.which("op"):- click.echo("⚠️ .env.local contains 1Password refs (op://) but 'op' CLI not found", err=True)- click.echo(" Install: brew install 1password-cli", err=True)- raise SystemExit(1)- # Load .env.development and .env.services first (only if not already set in shell).- # op run then layers .env.local on top — overriding our files but not shell.+ 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])- else:- _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))+ 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))def _register_script_commands() -> None:diff --git a/tools/hogli/tests/test_cli.py b/tools/hogli/tests/test_cli.pyindex 18bf77bf3f68..782abc9deb96 100644--- a/tools/hogli/tests/test_cli.py+++ b/tools/hogli/tests/test_cli.py@@ -2,6 +2,7 @@from __future__ import annotations+import osimport sysimport pytest@@ -200,3 +201,66 @@ class TestHelpText:lines = result.output.split("\n")# Look for section headers (typically uppercase or titled)assert len(lines) > 10+++class TestLoadEnvFile:+ """Test _load_env_file behavior — esp. graceful handling of op:// refs."""++ def _write_env(self, tmp_path, content: str):+ env_file = tmp_path / ".env.test"+ env_file.write_text(content)+ return env_file++ @pytest.mark.parametrize(+ "op_line",+ [+ "OPENAI_API_KEY=op://General/abc/credential",+ 'OPENAI_API_KEY="op://General/abc/credential"',+ "OPENAI_API_KEY= op://General/abc/credential",+ ],+ ids=["bare", "double-quoted", "leading-space"],+ )+ def test_skips_op_refs_so_they_dont_leak_as_literals(+ 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.++ Covers bare, quoted, and space-padded forms (op run itself accepts all three,+ so users may write any of them).+ """+ from hogli.cli import _load_env_file++ env_file = self._write_env(tmp_path, f"{op_line}\nLITERAL_VAR=actual_value\n")+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ monkeypatch.delenv("LITERAL_VAR", raising=False)++ _load_env_file(env_file)++ assert "OPENAI_API_KEY" not in os.environ+ assert os.environ["LITERAL_VAR"] == "actual_value"++ 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++ _load_env_file(tmp_path / "does_not_exist.env")++ def test_only_if_unset_preserves_shell_env(self, tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ from hogli.cli import _load_env_file++ env_file = self._write_env(tmp_path, "MY_VAR=from_file\n")+ monkeypatch.setenv("MY_VAR", "from_shell")++ _load_env_file(env_file, only_if_unset=True)++ assert os.environ["MY_VAR"] == "from_shell"++ def test_ignores_comments_and_blanks(self, tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ from hogli.cli import _load_env_file++ env_file = self._write_env(tmp_path, "# comment\n\nREAL_VAR=42\n# another\n")+ monkeypatch.delenv("REAL_VAR", raising=False)++ _load_env_file(env_file)++ assert os.environ["REAL_VAR"] == "42"