: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(hog): read global options from HOG_ env vars and posthog.json (#125525)
Rafael Audibertff06831d810d
diff --git a/hog/README.md b/hog/README.mdindex 2094867cc807..b94a438ec4f5 100644--- a/hog/README.md+++ b/hog/README.md@@ -48,7 +48,6 @@ First, the commands that make hog a complete CLI:Then, once the commands above work:-- [ ] Global options from posthog-cli: `--dry-run` and `POSTHOG_CLI_DRY_RUN`, which skip the whole command without credentials, `--no-fail`, `--skip-ssl-verification`, and `--rate-limit` with `POSTHOG_CLIENT_RATE_LIMIT`.- [ ] Telemetry: the `posthog cli command run` and `error_tracking_cli_sourcemaps_upload_*` events posthog-cli sends.- [ ] Callers: the SDKs, build plugins and scripts that run `posthog-cli` with its arguments. Move them to hog, or give hog a `posthog-cli` entry point that translates the arguments.- [ ] Distribution: a binary for each platform, macOS signing and notarization, the npm package, the Homebrew formula, `hog update`, and CI on Linux and Windows.@@ -73,10 +72,32 @@ Not planned:`-o text` or `-o json` overrides the default, and `--raw` prints a command's full result as JSON.Exit codes: 0 on success, 1 when a command fails, 2 for a usage error.+## Global options++Every option below works on any command, and each has an environment variable.+A flag beats the environment variable, which beats `posthog.json`.++| Option | Environment | `posthog.json` | What it does |+| ------------------------- | --------------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------- |+| `--host <url>` | `HOG_HOST` | `host` | The PostHog host to use instead of the one in your credentials |+| `--dotenv-file <path>` | `HOG_DOTENV_FILE` | | Read credentials from this file when the environment has none |+| `-o, --output <format>` | `HOG_OUTPUT` | | `text` or `json` |+| `--raw` | `HOG_RAW` | | Print a command's full result as JSON |+| `--debug` | `HOG_DEBUG` | | Print each HTTP request, its status and duration to stderr |+| `--no-fail` | `HOG_NO_FAIL` | `cli.noFail` | Exit with code 0 when a command fails or reports a problem, such as `diff` finding drift. Usage errors still exit with code 2 |+| `--skip-ssl-verification` | `HOG_SKIP_SSL_VERIFICATION` | | Accept any TLS certificate, for a self-signed self-hosted PostHog |+| `--rate-limit <requests>` | `HOG_RATE_LIMIT` | `cli.rateLimit` | The most requests per minute. No limit by default |+| | `HOG_DRY_RUN` | | Turns on `--dry-run` for every command that has one, and fails the commands that write without one |++`--host` and `HOG_HOST` override the host of every credential source. `host` in `posthog.json` never sends your credentials elsewhere: `hog auth login` uses it, and other commands stop when your credentials are for another host.+Commands that only read run as usual in a dry run, and `auth login` and `auth logout` fail.+hog reads only the `HOG_` names. posthog-cli's `POSTHOG_CLI_` variables, `POSTHOG_HOME` and `POSTHOG_RELEASE_MODE` don't count.+## posthog.jsonProject settings live in `posthog.json`, which hog looks for from the current folder up to the git root.It never holds API keys.+When the file isn't valid, every command stops with `invalid_config` except `hog config check`, which lists the problems.Point `$schema` at the published schema to get validation in your editor:```json@@ -89,6 +110,7 @@ Point `$schema` at the published schema to get validation in your editor:}```+`errorTracking.releaseMode` sets the default for `--release-mode`. `HOG_RELEASE_MODE` overrides it.`endpoints.dir` names the folder of endpoint files, so `hog endpoints pull`, `diff` and `push` work without a path.`hog schema pull` keeps its entries under `languages` in the snake case posthog-cli uses, so either CLI can regenerate an SDK the other set up.posthog-cli rewrites `posthog.json` with only `languages` when it pulls, so it drops the other settings. Restore them from version control after running it.@@ -134,13 +156,13 @@ hog uploads the same bytes and content hashes as posthog-cli, so either CLI can## Credentials-`hog` reads the same credentials as `posthog-cli`, in the same order:+`hog` reads credentials in the same order as `posthog-cli`, with `HOG_` variable names:-1. `POSTHOG_CLI_API_KEY` and `POSTHOG_CLI_PROJECT_ID` in the environment, plus an optional `POSTHOG_CLI_HOST`-2. The same variables in the file `--dotenv-file` or `POSTHOG_CLI_DOTENV_FILE` names. A missing file prints a warning and hog moves on to the next source.-3. `~/.posthog/credentials.json`, which `hog auth login` and `posthog-cli login` write (`POSTHOG_HOME` moves the folder). `hog auth login` makes it readable only by you.+1. `HOG_API_KEY` and `HOG_PROJECT_ID` in the environment, plus an optional `HOG_HOST`+2. The same variables in the file `--dotenv-file` or `HOG_DOTENV_FILE` names. A missing file prints a warning and hog moves on to the next source.+3. `~/.posthog/credentials.json`, which `hog auth login` and `posthog-cli login` write (`HOG_HOME` moves the folder). `hog auth login` makes it readable only by you.-`--host` overrides the host from any of these.+`--host` and `HOG_HOST` override the host from any of these.### Logging in and outdiff --git a/hog/posthog.schema.json b/hog/posthog.schema.jsonindex 0f279d6e76d1..ceefab5770b4 100644--- a/hog/posthog.schema.json+++ b/hog/posthog.schema.json@@ -7,6 +7,11 @@"description": "The JSON schema for this file.","type": "string"},+ "host": {+ "description": "The PostHog host for this project, like https://eu.posthog.com. `hog auth login` uses it, and other commands stop when your credentials are for another host. --host and HOG_HOST override it.",+ "type": "string",+ "format": "uri"+ },"errorTracking": {"type": "object","properties": {@@ -27,6 +32,11 @@},"additionalProperties": false},+ "releaseMode": {+ "description": "JavaScript only: put the release in the bundle (event, the default) or in the symbol set. --release-mode and HOG_RELEASE_MODE override it.",+ "type": "string",+ "enum": ["event", "symbol-set"]+ },"sources": {"description": "What `hog error-tracking inject`, `upload` and `process` scan when no path is passed.","type": "array",@@ -65,6 +75,23 @@"additionalProperties": false,"description": "Settings for `hog error-tracking`."},+ "cli": {+ "description": "Defaults for global options. Flags and HOG_ environment variables override them.",+ "type": "object",+ "properties": {+ "noFail": {+ "description": "Exit with code 0 when a command fails, like --no-fail. HOG_NO_FAIL overrides it.",+ "type": "boolean"+ },+ "rateLimit": {+ "description": "The most requests hog sends per minute, like --rate-limit. HOG_RATE_LIMIT overrides it.",+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ }+ },+ "additionalProperties": false+ },"endpoints": {"description": "Settings for `hog endpoints`.","type": "object",diff --git a/hog/src/cli.ts b/hog/src/cli.tsindex 4a50d70ea274..ec6bb2baa32a 100644--- a/hog/src/cli.ts+++ b/hog/src/cli.ts@@ -12,8 +12,10 @@ import {type Legacy,type OptionSpec,} from '@/core/command'-import { Context, GLOBAL_OPTIONS, type GlobalOptions } from '@/core/context'-import { EXIT_USAGE, HogError } from '@/core/errors'+import { loadConfig } from '@/core/config'+import { Context } from '@/core/context'+import { EXIT_FAILURE, EXIT_USAGE, HogError } from '@/core/errors'+import { DRY_RUN_ENV, envFlag, GLOBAL_OPTIONS, networkRuntime, resolveGlobals } from '@/core/globals'import { Output } from '@/core/output'import type { Runtime } from '@/core/runtime'import { kebabCase } from '@/core/text'@@ -22,12 +24,19 @@ import { VERSION } from '@/version'const ROOT_HELP = `hog prints JSON when an agent such as Claude Code or Codex runs it, or when stdout is not a terminal.-Run \`hog auth login\` to log in, and \`hog commands -o json\` to list every command, its arguments and its options.`+Run \`hog auth login\` to log in, and \`hog commands -o json\` to list every command, its arguments and its options.+HOG_DRY_RUN=1 turns on --dry-run for every command that has one, and fails the commands that would change something without it.`const LEGACY_HELP_GROUP = 'Not ported yet (each one prints the posthog-cli command to run):'function toOption(name: string, spec: OptionSpec): Option {- const option = new Option(optionFlags(name, spec), spec.description)+ const sources = [+ spec.env?.length ? `env: ${spec.env.join(', ')}` : '',+ spec.config ? `posthog.json: ${spec.config}` : '',+ ]+ .filter(Boolean)+ .join('; ')+ const option = new Option(optionFlags(name, spec), sources ? `${spec.description} (${sources})` : spec.description)if (spec.type === 'string' && spec.multiple) {option.argParser((value: string, previous: string[] | undefined) => [...(previous ?? []), value])}@@ -107,7 +116,20 @@ async function readArgument(runtime: Runtime, name: string, value: string): Promreturn text}-function createProgram(runtime: Runtime, mode: Mode, state: { exitCode: number }): Commander {+function commandPath(command: Commander): string {+ const names: string[] = []+ for (let current: Commander | null = command; current?.parent; current = current.parent) {+ names.unshift(current.name())+ }+ return names.join(' ')+}++interface RunState {+ exitCode: number+ noFail?: boolean+}++function createProgram(runtime: Runtime, mode: Mode, state: RunState): Commander {const out = new Output(runtime, mode)function addRunnable(command: Commander, node: Command): void {@@ -125,8 +147,26 @@ function createProgram(runtime: Runtime, mode: Mode, state: { exitCode: number }command.action(async (...params: unknown[]) => {const self = params.at(-1) as Commander- const globals = self.optsWithGlobals() as GlobalOptions+ const flags = self.optsWithGlobals()+ // commander reads `--no-fail` as turning off an option named `fail`.+ flags.noFail = flags.fail === false ? true : undefined+ const config = node.allowsInvalidConfig ? undefined : loadConfig(runtime)+ const globals = resolveGlobals(flags, runtime.env, (await config)?.config)+ state.noFail = globals.noFail === true+ const commandRuntime = networkRuntime(runtime, globals)const options = self.opts()+ if (envFlag(runtime.env, DRY_RUN_ENV)) {+ if (Object.hasOwn(node.options ?? {}, 'dryRun')) {+ options.dryRun = true+ } else if (node.writes) {+ throw new HogError(+ 'dry_run_unsupported',+ `\`hog ${commandPath(self)}\` has no dry run, and HOG_DRY_RUN is set.`,+ 'Unset HOG_DRY_RUN to run it, or leave the command out of the dry run.',+ EXIT_USAGE+ )+ }+ }// Optional arguments stay undefined. The command's own types allow that, the tree's types don't.const args = {} as Record<string, string>for (const [index, [name, spec]] of argEntries.entries()) {@@ -134,7 +174,7 @@ function createProgram(runtime: Runtime, mode: Mode, state: { exitCode: number }args[name] = spec.stdin && value !== undefined ? await readArgument(runtime, name, value) : value}- const ctx = new Context(runtime, globals, mode, COMMANDS)+ const ctx = new Context(commandRuntime, globals, mode, COMMANDS, config)let result: unknowntry {result = await node.run({ args, options, ctx })@@ -205,6 +245,7 @@ type Token = ReturnType<typeof parseArgs>['tokens'] extends (infer T)[] | undefiinterface PreParsed {format: OutputFormat | undefined+ noFail: booleantokens: Token[]}@@ -227,7 +268,7 @@ function preParse(argv: readonly string[]): PreParsed {})const output = values.outputconst format = GLOBAL_OPTIONS.output.choices.find((choice) => choice === output)- return { format, tokens }+ return { format, noFail: values['no-fail'] === true, tokens }}function findLegacy(tokens: Token[]): LegacyRoute | undefined {@@ -326,11 +367,20 @@ function toHogError(caught: unknown): HogError {return new HogError('internal_error', caught instanceof Error ? caught.message : String(caught))}+function safeEnvFlag(env: Runtime['env'], names: readonly string[]): boolean {+ try {+ return envFlag(env, names) === true+ } catch {+ return false+ }+}+export async function run(argv: readonly string[], runtime: Runtime): Promise<number> {- const { format, tokens } = preParse(argv)+ const { format, noFail, tokens } = preParse(argv)const terminal = { isTTY: runtime.stdoutIsTTY, hasColors: runtime.stdoutHasColors, columns: runtime.stdoutColumns }- const mode = resolveMode(runtime.env, terminal, format)- const state = { exitCode: 0 }+ const envFormat = GLOBAL_OPTIONS.output.choices.find((choice) => choice === runtime.env.HOG_OUTPUT)+ const mode = resolveMode(runtime.env, terminal, format ?? envFormat)+ const state: RunState = { exitCode: 0 }const program = createProgram(runtime, mode, state)if (argv.length === 0) {program.outputHelp()@@ -346,13 +396,15 @@ export async function run(argv: readonly string[], runtime: Runtime): Promise<nuthrow notPorted(args, legacy)}await program.parseAsync(args, { from: 'user' })- return state.exitCode+ // --no-fail also covers a result that reports a problem, like a failed push or a stale SDK.+ return state.noFail && state.exitCode === EXIT_FAILURE ? 0 : state.exitCode} catch (caught) {if (caught instanceof CommanderError && caught.exitCode === 0) {return 0}const error = toHogError(caught)new Output(runtime, mode).error(error)- return error.exitCode+ const ignore = state.noFail ?? (noFail || safeEnvFlag(runtime.env, GLOBAL_OPTIONS.noFail.env))+ return ignore && error.exitCode === EXIT_FAILURE ? 0 : error.exitCode}}diff --git a/hog/src/commands/auth/auth.test.ts b/hog/src/commands/auth/auth.test.tsindex 3ec2121ecffa..8485c9989904 100644--- a/hog/src/commands/auth/auth.test.ts+++ b/hog/src/commands/auth/auth.test.ts@@ -61,6 +61,36 @@ describe('hog auth login', () => {])})+ test.each([+ ['a posthog.json Cloud host picks the region', [], 'https://eu.posthog.com', 'https://eu.posthog.com'],+ [+ '--region beats the posthog.json host',+ ['--region', 'eu'],+ 'https://us.posthog.com',+ 'https://eu.posthog.com',+ ],+ ])('%s', async (_name, flags, configHost, loginHost) => {+ const result = await runHog(['auth', 'login', ...flags], {+ env: { CLAUDECODE: '1' },+ files: { '/work/posthog.json': JSON.stringify({ host: configHost }) },+ respond: deviceFlow(0),+ })++ expect(result.exitCode).toBe(0)+ expect(result.requests.map((request) => request.url)).toEqual([`${loginHost}/api/cli-auth/device-code/`])+ })++ test('a posthog.json host outside PostHog Cloud never starts a login', async () => {+ const result = await runHog(['auth', 'login'], {+ env: { CLAUDECODE: '1' },+ files: { '/work/posthog.json': JSON.stringify({ host: 'https://login.example.com' }) },+ respond: deviceFlow(0),+ })++ expect(result.error()).toMatchObject({ code: 'region_required' })+ expect(result.requests).toEqual([])+ })+test('an agent that retries gets the same code, so the link it shared keeps working', async () => {const result = await runHog(['auth', 'login', '--region', 'eu'], {env: { CLAUDECODE: '1' },@@ -222,10 +252,10 @@ describe('hog auth login', () => {['a key in the environment',{ [CREDENTIALS_FILE]: STORED },- { POSTHOG_CLI_API_KEY: 'phx_env' },+ { HOG_API_KEY: 'phx_env' },'logged_out','https://eu.posthog.com/settings/user-api-keys',- ['POSTHOG_CLI_API_KEY'],+ ['HOG_API_KEY'],],])('logout with %s removes what hog stored', async (_name, files, env, status, revokeUrl, stillSet) => {const result = await runHog(['auth', 'logout'], { env: { CLAUDECODE: '1', ...env }, files })diff --git a/hog/src/commands/auth/login.ts b/hog/src/commands/auth/login.tsindex c9a16533e547..34bcf1b4c3bf 100644--- a/hog/src/commands/auth/login.ts+++ b/hog/src/commands/auth/login.ts@@ -9,6 +9,21 @@ import { completeLogin, readPendingLogin, saveLogin, startLogin, type LoggedIn }const REGIONS = { us: 'https://us.posthog.com', eu: 'https://eu.posthog.com' } as const+// A posthog.json comes with the repository, so it only picks between the PostHog Cloud regions.+// A login to any other host needs --host, because the key it gets is saved for every project.+function cloudRegion(host: string | undefined): string | undefined {+ if (host === undefined) {+ return undefined+ }+ let origin: string+ try {+ origin = new URL(host).origin+ } catch {+ return undefined+ }+ return Object.values(REGIONS).find((region) => region === origin)+}+type LoginResult =| {status: 'pending'@@ -68,6 +83,7 @@ async function keyLogin(ctx: Context, prompts: Prompts): Promise<LoginResult> {export default defineCommand({description: 'Log in to PostHog and store a personal API key on this machine',+ writes: true,options: {region: {type: 'string',@@ -84,7 +100,7 @@ export default defineCommand({notes: ['At a terminal, hog asks where your PostHog account is hosted and opens the browser to approve the login.','Agents and scripts get a link and a code to hand to a person, then finish with `hog auth login --wait`.',- 'In CI, skip login and set POSTHOG_CLI_API_KEY, POSTHOG_CLI_PROJECT_ID and POSTHOG_CLI_HOST.',+ 'In CI, skip login and set HOG_API_KEY, HOG_PROJECT_ID and HOG_HOST.',].join('\n'),examples: ['hog auth login', 'hog auth login --region eu', 'hog auth login --wait'],@@ -108,11 +124,14 @@ export default defineCommand({throw new HogError('login_needs_a_person','hog auth login needs a person to approve it in a browser, so it does not run in CI.',- 'Set POSTHOG_CLI_API_KEY, POSTHOG_CLI_PROJECT_ID and POSTHOG_CLI_HOST instead.'+ 'Set HOG_API_KEY, HOG_PROJECT_ID and HOG_HOST instead.')}- let host = ctx.globals.host?.replace(/\/+$/, '') ?? (options.region ? REGIONS[options.region] : undefined)+ let host =+ ctx.globals.host?.replace(/\/+$/, '') ??+ (options.region ? REGIONS[options.region] : undefined) ??+ cloudRegion((await ctx.config())?.config.host)if (!host) {if (!prompts) {throw new HogError(diff --git a/hog/src/commands/auth/logout.ts b/hog/src/commands/auth/logout.tsindex 5a0e7dad3947..c88e661d203b 100644--- a/hog/src/commands/auth/logout.ts+++ b/hog/src/commands/auth/logout.ts@@ -1,5 +1,5 @@import { defineCommand } from '@/core/command'-import { API_KEY_ENV_VARS, posthogFile } from '@/posthog/credentials'+import { API_KEY_ENV_VAR, posthogFile } from '@/posthog/credentials'import { clearPendingLogin } from '@/posthog/login'interface LogoutResult {@@ -12,6 +12,7 @@ interface LogoutResult {export default defineCommand({description: 'Remove the personal API key hog stored on this machine',+ writes: true,notes: 'The key itself stays valid until you delete it in PostHog under Settings > Personal API keys.',examples: ['hog auth logout'],@@ -32,7 +33,7 @@ export default defineCommand({status: stored ? 'logged_out' : 'not_logged_in',credentialsPath,revokeUrl: host ? new URL('settings/user-api-keys', `${host.replace(/\/+$/, '')}/`).toString() : null,- stillSet: API_KEY_ENV_VARS.filter((name) => runtime.env[name]),+ stillSet: runtime.env[API_KEY_ENV_VAR] ? [API_KEY_ENV_VAR] : [],}},diff --git a/hog/src/commands/auth/status.ts b/hog/src/commands/auth/status.tsindex 22fdeb1793fa..e450ededc5d3 100644--- a/hog/src/commands/auth/status.ts+++ b/hog/src/commands/auth/status.ts@@ -4,7 +4,7 @@ import { checkAuthStatus } from '@/posthog/auth-status'import type { CredentialSource } from '@/posthog/credentials'const SOURCE_LABELS: Record<CredentialSource, string> = {- env: 'the POSTHOG_CLI_API_KEY environment variable',+ env: 'the HOG_API_KEY environment variable','dotenv-file': 'the --dotenv-file file','credentials-file': 'the credentials file',}diff --git a/hog/src/commands/config/check.ts b/hog/src/commands/config/check.tsindex c60e456b7c5a..b4a9cc874715 100644--- a/hog/src/commands/config/check.ts+++ b/hog/src/commands/config/check.ts@@ -8,6 +8,7 @@ type CheckResult =export default defineCommand({description: 'Check posthog.json against its schema and list every problem',+ allowsInvalidConfig: true,notes: `hog looks for ${CONFIG_FILE} in the current folder, then in each parent up to the git root. Exits with code 1 when the file is missing or has problems.`,examples: ['hog config check'],diff --git a/hog/src/commands/config/schema.ts b/hog/src/commands/config/schema.tsindex 360d6ab08c80..f2f55dbf86b9 100644--- a/hog/src/commands/config/schema.ts+++ b/hog/src/commands/config/schema.ts@@ -3,6 +3,7 @@ import { configSchema, SCHEMA_URL } from '@/core/config'export default defineCommand({description: 'Print the JSON schema for posthog.json',+ allowsInvalidConfig: true,notes: `Editors validate posthog.json when it starts with "$schema": "${SCHEMA_URL}".`,examples: ['hog config schema > posthog.schema.json'],diff --git a/hog/src/commands/error-tracking/clone.ts b/hog/src/commands/error-tracking/clone.tsindex bad1bc8476ad..c919569d9bed 100644--- a/hog/src/commands/error-tracking/clone.ts+++ b/hog/src/commands/error-tracking/clone.ts@@ -20,8 +20,8 @@ export default defineCommand({'hog et clone main.jsbundle.map main.jsbundle.hbc.composed.map --release-mode symbol-set',],- run({ args, options, ctx }) {- return cloneMaps(ctx, args.packagerMap, args.composedMap, readOptions(options, ctx.runtime.env))+ async run({ args, options, ctx }) {+ return cloneMaps(ctx, args.packagerMap, args.composedMap, await readOptions(options, ctx))},human({ result, out }) {diff --git a/hog/src/commands/error-tracking/download.ts b/hog/src/commands/error-tracking/download.tsindex 0d0a983ff45d..d8cd2e25fa94 100644--- a/hog/src/commands/error-tracking/download.ts+++ b/hog/src/commands/error-tracking/download.ts@@ -12,6 +12,7 @@ import { renderExtracted } from './extract'export default defineCommand({description: 'Download a symbol set from PostHog and unpack it',+ writes: true,args: {symbolSet: { description: 'The symbol set ID, or its ref, such as static/chunks/app.js.map' },},@@ -21,6 +22,7 @@ export default defineCommand({type: 'boolean',description: 'Look the argument up as a ref, for refs that look like IDs, such as chunk IDs and debug IDs',},+ dryRun: { type: 'boolean', description: 'Download the symbol set and list its files without writing them' },},scopes: ['error_tracking:read'],notes: 'A sourcemap becomes a .js and a .js.map file, a Hermes map a .hbc.map file, a ProGuard mapping a .txt file, and a dSYM or ELF symbol set a folder.',@@ -35,13 +37,16 @@ export default defineCommand({const byId = !options.ref && isSymbolSetId(args.symbolSet)const id = byId ? args.symbolSet : await resolveRef(client, args.symbolSet)const data = await downloadSymbolSet(client, id, ctx.runtime.fetch)+ const dryRun = options.dryRun === truereturn {id,+ dryRun,...extractSymbolSet(data,byId ? id : deriveBaseName(args.symbolSet),options.outputDir ?? '.',- ctx.runtime.cwd()+ ctx.runtime.cwd(),+ dryRun),}},diff --git a/hog/src/commands/error-tracking/error-tracking.test.ts b/hog/src/commands/error-tracking/error-tracking.test.tsindex 17e419af028e..c6604165576a 100644--- a/hog/src/commands/error-tracking/error-tracking.test.ts+++ b/hog/src/commands/error-tracking/error-tracking.test.ts@@ -104,6 +104,27 @@ describe('hog error-tracking upload', () => {expect(readFileSync(join(folder, 'dist/a.js.map'), 'utf8')).toBe(map)})+ test.each([+ ['HOG_RELEASE_MODE', { HOG_RELEASE_MODE: 'symbol-set' }, {}],+ ['errorTracking.releaseMode in posthog.json', {}, { releaseMode: 'symbol-set' }],+ ])('%s picks symbol-set mode, which mints random chunk IDs', async (_name, env, errorTracking) => {+ const folder = project({+ 'posthog.json': JSON.stringify({+ errorTracking: { release: { name: 'app', version: '1' }, ...errorTracking },+ }),+ 'dist/a.js': 'a();\n//# sourceMappingURL=a.js.map\n',+ 'dist/a.js.map': JSON.stringify({ version: 3, sources: ['a.ts'], names: [], mappings: 'AAAA' }),+ })+ const result = await runHog(['et', 'process', 'dist', '--dry-run'], {+ env: { CLAUDECODE: '1', ...env },+ cwd: folder,+ useDisk: true,+ })+ expect(result.json().symbolSets).toEqual([+ expect.objectContaining({ chunkId: expect.stringMatching(/^[0-9a-f]{8}-[0-9a-f]{4}-7/) }),+ ])+ })+const MAP = JSON.stringify({ version: 3, sources: ['a.ts'], names: [], mappings: 'AAAA' })test.each([[diff --git a/hog/src/commands/error-tracking/extract.ts b/hog/src/commands/error-tracking/extract.tsindex 1a6a180e062f..4df9e475f7e3 100644--- a/hog/src/commands/error-tracking/extract.ts+++ b/hog/src/commands/error-tracking/extract.ts@@ -14,22 +14,25 @@ const KIND_LABELS: Record<ExtractReport['kind'], string> = {dsym: 'dSYM',}-export function renderExtracted(out: Output, result: ExtractReport): void {+export function renderExtracted(out: Output, result: ExtractReport & { dryRun: boolean }): void {for (const file of result.files) {out.line(escapeControls(file))}+ const verb = result.dryRun ? 'Dry run: would extract' : 'Extracted'out.line(- out.style(`Extracted the ${KIND_LABELS[result.kind]} symbol set to ${escapeControls(result.output)}.`, 'dim')+ out.style(`${verb} the ${KIND_LABELS[result.kind]} symbol set to ${escapeControls(result.output)}.`, 'dim'))}export default defineCommand({description: 'Unpack a symbol set file, such as one PostHog stored',+ writes: true,args: {file: { description: 'The symbol set file' },},options: {outputDir: { type: 'string', placeholder: 'folder', description: 'Where to write the files (default .)' },+ dryRun: { type: 'boolean', description: 'List the files without writing them' },},examples: ['hog error-tracking extract symbol-set.bin --output-dir symbols'],@@ -40,12 +43,17 @@ export default defineCommand({} catch (error) {throw new HogError('file_unreadable', `hog couldn't read ${args.file}: ${(error as Error).message}`)}- return extractSymbolSet(- data,- deriveBaseName(basename(args.file) || 'symbol_set'),- options.outputDir ?? '.',- ctx.runtime.cwd()- )+ const dryRun = options.dryRun === true+ return {+ dryRun,+ ...extractSymbolSet(+ data,+ deriveBaseName(basename(args.file) || 'symbol_set'),+ options.outputDir ?? '.',+ ctx.runtime.cwd(),+ dryRun+ ),+ }},human({ result, out }) {diff --git a/hog/src/commands/error-tracking/inject.ts b/hog/src/commands/error-tracking/inject.tsindex a68d78428216..0e8e2eba803f 100644--- a/hog/src/commands/error-tracking/inject.ts+++ b/hog/src/commands/error-tracking/inject.ts@@ -33,7 +33,7 @@ export default defineCommand({examples: ['hog error-tracking inject dist', 'hog et inject dist --release-name web --release-version 1.4.0'],async run({ args, options, ctx }) {- const settings = readOptions(options, ctx.runtime.env)+ const settings = await readOptions(options, ctx)const selection = await select(ctx, args.paths ?? [], settings)const report = await inject(ctx, selection, settings)return {diff --git a/hog/src/commands/error-tracking/process.ts b/hog/src/commands/error-tracking/process.tsindex 58104e08c975..256d8dbb58fc 100644--- a/hog/src/commands/error-tracking/process.ts+++ b/hog/src/commands/error-tracking/process.ts@@ -26,7 +26,7 @@ export default defineCommand({examples: ['hog error-tracking process dist', 'hog et process dist --delete-after'],async run({ args, options, ctx }) {- const settings = readOptions(options, ctx.runtime.env)+ const settings = await readOptions(options, ctx)const selection = await select(ctx, args.paths ?? [], settings)if (selection.artifacts.length === 0) {throw new HogError(diff --git a/hog/src/commands/error-tracking/release.ts b/hog/src/commands/error-tracking/release.tsindex a85f52047f41..3764a755503c 100644--- a/hog/src/commands/error-tracking/release.ts+++ b/hog/src/commands/error-tracking/release.ts@@ -1,6 +1,6 @@import { defineCommand } from '@/core/command'import { resolveJsRelease } from '@/error-tracking/js-flow'-import { fetchOrCreateRelease, type Release } from '@/error-tracking/release'+import { fetchOrCreateRelease, findRelease, releaseHashId, type Release } from '@/error-tracking/release'import { releaseFields } from '@/error-tracking/run'import { SymbolSetClient } from '@/error-tracking/upload'@@ -8,6 +8,7 @@ import { readOptions, RELEASE_OPTIONS } from './shared'export default defineCommand({description: 'Find or create the release this build belongs to',+ writes: true,options: {releaseName: {type: 'string',@@ -21,6 +22,10 @@ export default defineCommand({},build: RELEASE_OPTIONS.build,infoPlist: RELEASE_OPTIONS.infoPlist,+ dryRun: {+ type: 'boolean',+ description: 'Look the release up without creating it. The ID is null when PostHog has no such release yet',+ },},scopes: ['error_tracking:write'],notes: [@@ -33,14 +38,24 @@ export default defineCommand({'hog et release --info-plist ios/App/Info.plist',],- async run({ options, ctx }): Promise<Release | null> {- const settings = readOptions(options, ctx.runtime.env)+ async run({ options, ctx }): Promise<(Omit<Release, 'id'> & { id: string | null }) | null> {+ const settings = await readOptions(options, ctx)const fields = await releaseFields(ctx, settings)const resolved = resolveJsRelease(fields, ctx.runtime.env, ctx.runtime.cwd(), [])if (!resolved) {return null}const client = new SymbolSetClient(ctx.runtime, await ctx.credentials())+ if (options.dryRun) {+ const existing = await findRelease(client, resolved.name, resolved.version)+ const { id, hash_id, version, project } = existing ?? {+ id: null,+ hash_id: releaseHashId(resolved.name, resolved.version),+ version: resolved.version,+ project: resolved.name,+ }+ return { id, hash_id, version, project }+ }const release = await fetchOrCreateRelease(client,resolved.name,@@ -52,7 +67,7 @@ export default defineCommand({// Just the ID, so `$(hog error-tracking release -o text)` gives what a build script needs.human({ result, out }) {- if (result) {+ if (result?.id) {out.line(result.id)}},diff --git a/hog/src/commands/error-tracking/shared.ts b/hog/src/commands/error-tracking/shared.tsindex cca687c6be99..51350acc3d80 100644--- a/hog/src/commands/error-tracking/shared.ts+++ b/hog/src/commands/error-tracking/shared.ts@@ -1,8 +1,8 @@import type { OptionSpec } from '@/core/command'import { ARTIFACT_KINDS, type ArtifactKind } from '@/core/config'+import type { Context } from '@/core/context'import { EXIT_USAGE, HogError } from '@/core/errors'import type { Output } from '@/core/output'-import type { Env } from '@/core/runtime'import { plural } from '@/core/text'import type { ErrorTrackingOptions, InjectedReport, UploadReport } from '@/error-tracking/run'@@ -53,7 +53,8 @@ export const RELEASE_OPTIONS = {releaseMode: {type: 'string',choices: ['event', 'symbol-set'],- description: 'JavaScript only: put the release in the bundle (event, the default) or in the symbol set',+ description:+ 'JavaScript only: put the release in the bundle (event, the default) or in the symbol set. Defaults to HOG_RELEASE_MODE, then errorTracking.releaseMode in posthog.json',},} as const satisfies Record<string, OptionSpec>@@ -79,7 +80,11 @@ export const UPLOAD_OPTIONS = {placeholder: 'count',description: 'Symbol sets per upload request (default 50, 10 for native symbols)',},- concurrency: { type: 'string', placeholder: 'count', description: 'Parallel file uploads (default 10)' },+ concurrency: {+ type: 'string',+ placeholder: 'count',+ description: 'Parallel file uploads (default HOG_UPLOAD_CONCURRENCY, then 10)',+ },} as const satisfies Record<string, OptionSpec>export const DRY_RUN_OPTION = {@@ -123,8 +128,9 @@ function count(flag: string, value: string | undefined, fallback: number): numbereturn parsed}-// posthog-cli reads the release mode and the upload concurrency from these variables too.-export function readOptions(options: RawOptions, env: Env): ErrorTrackingOptions {+// The release mode comes from the flag, then HOG_RELEASE_MODE, then errorTracking.releaseMode in posthog.json.+export async function readOptions(options: RawOptions, ctx: Context): Promise<ErrorTrackingOptions> {+ const env = ctx.runtime.envif (options.force && options.skipOnConflict) {throw new HogError('usage_error',@@ -133,11 +139,15 @@ export function readOptions(options: RawOptions, env: Env): ErrorTrackingOptionsEXIT_USAGE)}- const releaseMode = options.releaseMode ?? env.POSTHOG_RELEASE_MODE ?? 'event'+ const releaseMode =+ options.releaseMode ??+ (env.HOG_RELEASE_MODE || undefined) ??+ (await ctx.config())?.config.errorTracking?.releaseMode ??+ 'event'if (releaseMode !== 'event' && releaseMode !== 'symbol-set') {throw new HogError('usage_error',- 'POSTHOG_RELEASE_MODE must be event or symbol-set.',+ 'HOG_RELEASE_MODE must be event or symbol-set.','Unset it, or pass --release-mode.',EXIT_USAGE)@@ -152,7 +162,7 @@ export function readOptions(options: RawOptions, env: Env): ErrorTrackingOptionsforce: options.force === true,skipOnConflict: options.skipOnConflict === true,batchSize: options.batchSize === undefined ? undefined : count('--batch-size', options.batchSize, 50),- concurrency: count('--concurrency', options.concurrency ?? env.POSTHOG_CLI_SOURCEMAP_UPLOAD_CONCURRENCY, 10),+ concurrency: count('--concurrency', options.concurrency ?? env.HOG_UPLOAD_CONCURRENCY, 10),deleteAfter: options.deleteAfter === true,includeSource: options.includeSource === true,dryRun: options.dryRun === true,diff --git a/hog/src/commands/error-tracking/upload.ts b/hog/src/commands/error-tracking/upload.tsindex 633712b035ed..96e61cd879cc 100644--- a/hog/src/commands/error-tracking/upload.ts+++ b/hog/src/commands/error-tracking/upload.ts@@ -31,7 +31,7 @@ export default defineCommand({],async run({ args, options, ctx }) {- const settings = readOptions(options, ctx.runtime.env)+ const settings = await readOptions(options, ctx)const selection = await select(ctx, args.paths ?? [], settings)if (selection.artifacts.length === 0) {throw new HogError(diff --git a/hog/src/commands/schema/pull.ts b/hog/src/commands/schema/pull.tsindex 253819dbfbc1..1297c7d4635d 100644--- a/hog/src/commands/schema/pull.ts+++ b/hog/src/commands/schema/pull.ts@@ -9,13 +9,14 @@ import { chosenFile, configRoot, fetchDefinitions, isLanguage, LANGUAGE_INFO, LAinterface PulledLanguage {language: Languagefile: string- status: 'written' | 'unchanged'+ status: 'written' | 'would_write' | 'unchanged'eventCount: numberschemaHash: string}export default defineCommand({description: 'Generate a typed PostHog SDK from your event definitions',+ writes: true,options: {language: {type: 'string',@@ -28,6 +29,10 @@ export default defineCommand({placeholder: 'path',description: 'Where to write the module. posthog.json remembers it for the next run',},+ dryRun: {+ type: 'boolean',+ description: 'Fetch the event definitions and show what would change, without writing',+ },},scopes: ['event_definition:read'],notes: 'hog writes the module only when the event definitions changed or the file is missing, and records the language, path and schema hash in posthog.json. posthog-cli reads the same entries.',@@ -98,7 +103,7 @@ export default defineCommand({saved?.output_path === outputPath &&saved.schema_hash === definitions.schema_hash &&(await ctx.runtime.exists(file))- if (!unchanged) {+ if (!unchanged && !options.dryRun) {await ctx.runtime.writeFile(file, definitions.content)entries[language] = {output_path: outputPath,@@ -110,19 +115,20 @@ export default defineCommand({pulled.push({language,file: outputPath,- status: unchanged ? 'unchanged' : 'written',+ status: unchanged ? 'unchanged' : options.dryRun ? 'would_write' : 'written',eventCount: definitions.event_count,schemaHash: definitions.schema_hash,})}+ const dryRun = options.dryRun === trueif (Object.keys(entries).length === 0) {- return { config: loaded?.path ?? null, configUpdated: false, languages: pulled }+ return { config: loaded?.path ?? null, configUpdated: false, dryRun, languages: pulled }}const config = await updateConfig(ctx.runtime, loaded, (raw) => {raw.languages = { ...(raw.languages as object | undefined), ...entries }})- return { config: storedPath(ctx.runtime.cwd(), config), configUpdated: true, languages: pulled }+ return { config: storedPath(ctx.runtime.cwd(), config), configUpdated: true, dryRun, languages: pulled }},human({ result, out }) {@@ -133,6 +139,10 @@ export default defineCommand({out.line(`${out.style('Up to date', 'green', 'bold')} ${name} in ${pulled.file} (${events})`)continue}+ if (pulled.status === 'would_write') {+ out.line(`${out.style('Would generate', 'yellow', 'bold')} ${name} in ${pulled.file} (${events})`)+ continue+ }out.line(`${out.style('Generated', 'green', 'bold')} ${name} in ${pulled.file} (${events})`)out.line()out.line(out.style('Next steps:', 'bold'))@@ -142,6 +152,9 @@ export default defineCommand({if (result.configUpdated) {out.line(out.style(`Saved the settings in ${result.config}`, 'dim'))}+ if (result.dryRun) {+ out.line(out.style('Dry run: no files written.', 'dim'))+ }},agent({ result, out }) {diff --git a/hog/src/core/command.ts b/hog/src/core/command.tsindex dd36f97e9b07..561e5685379d 100644--- a/hog/src/core/command.ts+++ b/hog/src/core/command.ts@@ -11,9 +11,16 @@ export interface ArgumentSpec {stdin?: boolean}+// `env` and `config` are for global options only: the env vars and the posthog.json key path, such+// as `cli.noFail`, that set them.+interface OptionSource {+ env?: readonly string[]+ config?: string+}+export type OptionSpec =- | { type: 'boolean'; description: string; short?: string }- | {+ | ({ type: 'boolean'; description: string; short?: string } & OptionSource)+ | ({type: 'string'description: stringshort?: string@@ -22,7 +29,7 @@ export type OptionSpec =choices?: readonly string[]// The option can repeat, as in `--var a=1 --var b=2`, and its value is a list.multiple?: boolean- }+ } & OptionSource)type ArgumentValues<Args> = {[Name in keyof Args]: Args[Name] extends { variadic: true }@@ -55,6 +62,12 @@ interface CommandDefinition<Args, Options, Result> {args?: Args// The key becomes the flag: `dotenvFile` is `--dotenv-file`.options?: Options+ // The command changes something in PostHog or on disk. HOG_DRY_RUN turns on its `dryRun` option,+ // and fails it when it has none. Commands that only read run as usual in a dry run.+ writes?: boolean+ // The command runs when posthog.json is invalid, like `hog config check`, which reports why.+ // Every other command stops, so it never runs with settings hog couldn't read.+ allowsInvalidConfig?: boolean// Personal API key scopes the command needs. `hog commands` lists them, and a 403 names them.scopes?: readonly string[]notes?: stringdiff --git a/hog/src/core/config.ts b/hog/src/core/config.tsindex 4d70d36d2c9d..9fcd75fcb7aa 100644--- a/hog/src/core/config.ts+++ b/hog/src/core/config.ts@@ -41,6 +41,12 @@ const ErrorTracking = z}).optional().describe('The release every uploaded symbol set belongs to.'),+ releaseMode: z+ .enum(['event', 'symbol-set'])+ .optional()+ .describe(+ 'JavaScript only: put the release in the bundle (event, the default) or in the symbol set. --release-mode and HOG_RELEASE_MODE override it.'+ ),sources: z.array(Source).optional()@@ -63,7 +69,30 @@ export type SchemaLanguage = z.infer<typeof SchemaLanguage>export const PostHogConfig = z.strictObject({$schema: z.string().optional().describe('The JSON schema for this file.'),+ host: z+ .url()+ .optional()+ .describe(+ 'The PostHog host for this project, like https://eu.posthog.com. `hog auth login` uses it, and other commands stop when your credentials are for another host. --host and HOG_HOST override it.'+ ),errorTracking: ErrorTracking.optional(),+ cli: z+ .strictObject({+ noFail: z+ .boolean()+ .optional()+ .describe('Exit with code 0 when a command fails, like --no-fail. HOG_NO_FAIL overrides it.'),+ rateLimit: z+ .number()+ .int()+ .positive()+ .optional()+ .describe(+ 'The most requests hog sends per minute, like --rate-limit. HOG_RATE_LIMIT overrides it.'+ ),+ })+ .optional()+ .describe('Defaults for global options. Flags and HOG_ environment variables override them.'),endpoints: z.strictObject({dir: zdiff --git a/hog/src/core/context.ts b/hog/src/core/context.tsindex 4e8b65e7e796..57933cc11cc7 100644--- a/hog/src/core/context.ts+++ b/hog/src/core/context.ts@@ -4,37 +4,12 @@ import { PostHogApi } from '@/posthog/api'import { resolveCredentials, type ResolvedCredentials } from '@/posthog/credentials'import type { Mode } from './agent'-import type { CommandTree, OptionSpec, OptionValues } from './command'+import type { CommandTree } from './command'import { loadConfig, type LoadedConfig } from './config'+import type { GlobalOptions } from './globals'import type { Prompts } from './prompts'import type { Runtime } from './runtime'-export const GLOBAL_OPTIONS = {- host: {- type: 'string',- placeholder: 'url',- description: 'The PostHog host to use instead of the one in your credentials',- },- dotenvFile: {- type: 'string',- placeholder: 'path',- description: 'Read POSTHOG_CLI_* credentials from this file when the environment has none',- },- output: {- type: 'string',- short: 'o',- placeholder: 'format',- choices: ['text', 'json'],- description: 'Output format, json by default for agents and pipes',- },- raw: {- type: 'boolean',- description: 'Print the full result as JSON, without the formatting for people or agents',- },-} as const satisfies Record<string, OptionSpec>--export type GlobalOptions = OptionValues<typeof GLOBAL_OPTIONS>-// What a command's `run` gets besides its own arguments and options. It has no output on// purpose: `run` returns data, and the command's `human` and `agent` views print it.export class Context {@@ -47,8 +22,11 @@ export class Context {readonly runtime: Runtime,readonly globals: GlobalOptions,readonly mode: Mode,- readonly tree: CommandTree- ) {}+ readonly tree: CommandTree,+ loaded?: Promise<LoadedConfig | undefined>+ ) {+ this.loaded = loaded+ }// Undefined unless a person is at the terminal, so a command can ask questions only when// someone can answer them. Agents, pipes and `-o json` never get prompts.@@ -78,7 +56,10 @@ export class Context {// Throws `not_authenticated` when there are none.async credentials(): Promise<ResolvedCredentials> {- this.resolved ??= await resolveCredentials(this.runtime, this.globals)+ this.resolved ??= await resolveCredentials(this.runtime, {+ ...this.globals,+ configHost: (await this.config())?.config.host,+ })return this.resolved}}diff --git a/hog/src/core/globals.test.ts b/hog/src/core/globals.test.tsnew file mode 100644index 000000000000..fc3d3fe75a0a--- /dev/null+++ b/hog/src/core/globals.test.ts@@ -0,0 +1,185 @@+import { describe, expect, test } from 'bun:test'++import { runHog, TEST_CREDENTIALS } from '@/testing'++const AGENT = { CLAUDECODE: '1' }+const ENDPOINTS = 'https://ph.example.com/api/environments/7/endpoints/'++const threePages = (url: string): { status: number; body: unknown } => {+ const page = Number(new URL(url).searchParams.get('page') ?? '1')+ return { status: 200, body: { results: [], next: page < 3 ? `${ENDPOINTS}?page=${page + 1}&token=secret` : null } }+}++describe('global options', () => {+ test.each([+ ['--no-fail', ['--no-fail'], {}, {}],+ ['HOG_NO_FAIL', [], { HOG_NO_FAIL: '1' }, {}],+ ['cli.noFail in posthog.json', [], {}, { '/work/posthog.json': JSON.stringify({ cli: { noFail: true } }) }],+ ])('%s turns a failure into exit code 0 and still prints it', async (_name, flags, env, files) => {+ const result = await runHog(['endpoints', 'list', ...flags], { env: { ...AGENT, ...env }, files })+ expect(result.exitCode).toBe(0)+ expect(result.error().code).toBe('not_authenticated')+ })++ test('--no-fail covers a result that reports a problem', async () => {+ const result = await runHog(['endpoints', 'diff', 'a.yaml', '--no-fail'], {+ env: { ...AGENT, ...TEST_CREDENTIALS },+ files: { '/work/a.yaml': 'name: a\nquery: SELECT 1\n' },+ respond: () => ({ status: 200, body: { results: [] } }),+ })+ expect(result.json().plan).toEqual([expect.objectContaining({ action: 'create' })])+ expect(result.exitCode).toBe(0)+ })++ test('--no-fail keeps usage errors at exit code 2', async () => {+ const result = await runHog(['endpoints', 'run', '--no-fail'], { env: { ...AGENT, ...TEST_CREDENTIALS } })+ expect(result.exitCode).toBe(2)+ })++ test.each([+ ['an env var', { HOG_RATE_LIMIT: '2' }, {}],+ ['posthog.json', {}, { '/work/posthog.json': JSON.stringify({ cli: { rateLimit: 2 } }) }],+ ])('a rate limit from %s holds the third request in a minute', async (_name, env, files) => {+ const result = await runHog(['endpoints', 'list'], {+ env: { ...AGENT, ...TEST_CREDENTIALS, ...env },+ files,+ respond: threePages,+ })+ expect(result.requests).toHaveLength(3)+ expect(result.elapsedMs).toBe(60_000)+ })++ test('a flag beats the env var, which beats posthog.json', async () => {+ const result = await runHog(['endpoints', 'list', '--rate-limit', '100'], {+ env: { ...AGENT, ...TEST_CREDENTIALS, HOG_RATE_LIMIT: '1' },+ files: { '/work/posthog.json': JSON.stringify({ cli: { rateLimit: 1 } }) },+ respond: threePages,+ })+ expect(result.elapsedMs).toBe(0)+ })++ test('a rate limit leaves signed storage URLs alone, as posthog-cli does', async () => {+ const result = await runHog(['et', 'download', '0192f0a0-0000-7000-8000-000000000001', '--rate-limit', '1'], {+ env: { ...AGENT, ...TEST_CREDENTIALS },+ respond: (url) =>+ url.endsWith('/download/')+ ? { status: 200, body: { url: 'https://storage.example.com/symbol-set' } }+ : { status: 500, body: {} },+ })++ expect(result.requests.map((request) => new URL(request.url).host)).toEqual([+ 'ph.example.com',+ 'storage.example.com',+ ])+ expect(result.elapsedMs).toBe(0)+ })++ test('HOG_DEBUG prints each request without its query string', async () => {+ const result = await runHog(['endpoints', 'list'], {+ env: { ...AGENT, ...TEST_CREDENTIALS, HOG_DEBUG: 'true' },+ respond: threePages,+ })+ expect(result.stderr).toContain(`[debug] GET ${ENDPOINTS} 200`)+ expect(result.stderr).not.toContain('secret')+ })++ test.each([+ ['an env flag that is not a boolean', ['endpoints', 'list'], { HOG_DEBUG: 'maybe' }],+ ['a rate limit that is not a number', ['endpoints', 'list'], { HOG_RATE_LIMIT: 'fast' }],+ ])('%s is a usage error', async (_name, argv, env) => {+ const result = await runHog(argv, { env: { ...AGENT, ...TEST_CREDENTIALS, ...env } })+ expect(result.exitCode).toBe(2)+ expect(result.error().code).toBe('invalid_setting')+ })++ test('HOG_OUTPUT picks the format', async () => {+ const result = await runHog(['commands'], { env: { HOG_OUTPUT: 'json' }, stdoutIsTTY: true })+ expect(() => JSON.parse(result.stdout)).not.toThrow()+ })++ test('--skip-ssl-verification turns off certificate checks', async () => {+ const result = await runHog(['commands', '--skip-ssl-verification'], { env: AGENT })+ expect(result.tls.verify).toBe(false)+ })++ test('HOG_DRY_RUN dry-runs every command that writes, and fails the ones that cannot', async () => {+ const env = { ...AGENT, ...TEST_CREDENTIALS, HOG_DRY_RUN: '1' }+ const push = await runHog(['endpoints', 'push', 'a.yaml'], {+ env,+ files: { '/work/a.yaml': 'name: a\nquery: SELECT 1\n' },+ respond: () => ({ status: 200, body: { results: [] } }),+ })+ expect(push.json()).toMatchObject({ status: 'preview' })++ const pull = await runHog(['schema', 'pull', '-l', 'python'], {+ env,+ respond: () => ({ status: 200, body: { content: 'x = 1\n', event_count: 1, schema_hash: 'h' } }),+ })+ expect(pull.json()).toMatchObject({ status: 'would_write' })+ expect(pull.files).toEqual({})++ const logout = await runHog(['auth', 'logout'], {+ env,+ files: { '/home/test/.posthog/credentials.json': '{}' },+ })+ expect(logout.exitCode).toBe(2)+ expect(logout.error().code).toBe('dry_run_unsupported')+ expect(logout.files).toEqual({ '/home/test/.posthog/credentials.json': '{}' })+ })++ test.each([+ [+ 'a posthog.json host that matches the credentials',+ 'https://stored.example.com',+ {},+ 'https://stored.example.com',+ ],+ [+ 'HOG_HOST beats posthog.json',+ 'https://config.example.com',+ { HOG_HOST: 'https://env.example.com' },+ 'https://env.example.com',+ ],+ ])('%s', async (_name, configHost, env, host) => {+ const result = await runHog(['endpoints', 'list'], {+ env: { ...AGENT, ...env },+ files: {+ '/work/posthog.json': JSON.stringify({ host: configHost }),+ '/home/test/.posthog/credentials.json': JSON.stringify({+ token: 'phx_test',+ env_id: '7',+ host: 'https://stored.example.com',+ }),+ },+ respond: () => ({ status: 200, body: { results: [] } }),+ })++ expect(result.requests[0]!.url).toStartWith(`${host}/api/`)+ })++ test('a posthog.json host never receives credentials stored for another host', async () => {+ const result = await runHog(['endpoints', 'list'], {+ env: AGENT,+ files: {+ '/work/posthog.json': JSON.stringify({ host: 'https://config.example.com' }),+ '/home/test/.posthog/credentials.json': JSON.stringify({+ token: 'phx_test',+ env_id: '7',+ host: 'https://stored.example.com',+ }),+ },+ })++ expect(result.error().code).toBe('host_mismatch')+ expect(result.requests).toEqual([])+ })++ test('a posthog.json hog cannot read stops the command before it sends anything', async () => {+ const result = await runHog(['endpoints', 'list'], {+ env: { ...AGENT, ...TEST_CREDENTIALS },+ files: { '/work/posthog.json': '{ "cli": ' },+ })+ expect(result.error().code).toBe('invalid_config')+ expect(result.requests).toEqual([])+ })+})diff --git a/hog/src/core/globals.ts b/hog/src/core/globals.tsnew file mode 100644index 000000000000..831aa6129e2c--- /dev/null+++ b/hog/src/core/globals.ts@@ -0,0 +1,201 @@+import type { OptionSpec, OptionValues } from './command'+import type { PostHogConfig } from './config'+import { EXIT_USAGE, HogError } from './errors'+import type { Env, Runtime, RuntimeFetch } from './runtime'+import { kebabCase } from './text'++// Options every command takes. Each one also reads the env vars in `env`, in order, and some read+// the posthog.json key at the `config` path. A flag beats an env var, which beats posthog.json.+export const GLOBAL_OPTIONS = {+ host: {+ type: 'string',+ placeholder: 'url',+ env: ['HOG_HOST'],+ description: 'The PostHog host to use instead of the one in your credentials',+ },+ dotenvFile: {+ type: 'string',+ placeholder: 'path',+ env: ['HOG_DOTENV_FILE'],+ description: 'Read HOG_API_KEY, HOG_PROJECT_ID and HOG_HOST from this file when the environment has none',+ },+ output: {+ type: 'string',+ short: 'o',+ placeholder: 'format',+ choices: ['text', 'json'],+ env: ['HOG_OUTPUT'],+ description: 'Output format, json by default for agents and pipes',+ },+ raw: {+ type: 'boolean',+ env: ['HOG_RAW'],+ description: 'Print the full result as JSON, without the formatting for people or agents',+ },+ debug: {+ type: 'boolean',+ env: ['HOG_DEBUG'],+ description: 'Print each HTTP request hog sends, with its status and duration, to stderr',+ },+ noFail: {+ type: 'boolean',+ env: ['HOG_NO_FAIL'],+ config: 'cli.noFail',+ description: 'Exit with code 0 when the command fails or reports a problem, for builds that must not break',+ },+ skipSslVerification: {+ type: 'boolean',+ env: ['HOG_SKIP_SSL_VERIFICATION'],+ description: 'Accept any TLS certificate, for a self-hosted PostHog with a self-signed one',+ },+ rateLimit: {+ type: 'string',+ placeholder: 'requests',+ env: ['HOG_RATE_LIMIT'],+ config: 'cli.rateLimit',+ description: 'The most requests hog sends per minute',+ },+} as const satisfies Record<string, OptionSpec>++export type GlobalOptions = OptionValues<typeof GLOBAL_OPTIONS>++export const DRY_RUN_ENV = ['HOG_DRY_RUN'] as const++const TRUE_VALUES = new Set(['1', 'true', 'yes', 'on'])+const FALSE_VALUES = new Set(['0', 'false', 'no', 'off', ''])++export function envFlag(env: Env, names: readonly string[]): boolean | undefined {+ for (const name of names) {+ const value = env[name]+ if (value === undefined) {+ continue+ }+ const normalized = value.trim().toLowerCase()+ if (TRUE_VALUES.has(normalized)) {+ return true+ }+ if (FALSE_VALUES.has(normalized)) {+ return false+ }+ throw new HogError(+ 'invalid_setting',+ `${name} must be true or false, but it is "${value}".`,+ `Set ${name} to 1 or 0.`,+ EXIT_USAGE+ )+ }+ return undefined+}++function envValue(env: Env, names: readonly string[]): { name: string; value: string } | undefined {+ for (const name of names) {+ const value = env[name]+ if (value) {+ return { name, value }+ }+ }+ return undefined+}++function configValue(config: PostHogConfig, path: string): unknown {+ return path+ .split('.')+ .reduce<unknown>((parent, key) => (parent as Record<string, unknown> | undefined)?.[key], config)+}++export function resolveGlobals(+ flags: Readonly<Record<string, unknown>>,+ env: Env,+ config: PostHogConfig = {}+): GlobalOptions {+ const resolved: Record<string, unknown> = {}+ for (const [name, spec] of Object.entries(GLOBAL_OPTIONS) as [string, OptionSpec][]) {+ const envNames = spec.env ?? []+ let value: unknown = flags[name]+ let source = `--${kebabCase(name)}`+ if (value === undefined && spec.type === 'boolean') {+ value = envFlag(env, envNames)+ source = envNames.find((envName) => env[envName] !== undefined) ?? source+ } else if (value === undefined) {+ const fromEnv = envValue(env, envNames)+ value = fromEnv?.value+ source = fromEnv?.name ?? source+ }+ const configured = spec.config === undefined ? undefined : configValue(config, spec.config)+ if (value === undefined && configured !== undefined) {+ value = spec.type === 'string' ? String(configured) : configured+ source = `${spec.config} in posthog.json`+ }+ if (spec.type === 'string' && spec.choices && value !== undefined && !spec.choices.includes(String(value))) {+ throw new HogError(+ 'invalid_setting',+ `${source} must be one of ${spec.choices.join(', ')}, but it is "${String(value)}".`,+ undefined,+ EXIT_USAGE+ )+ }+ resolved[name] = value+ }+ const globals = resolved as GlobalOptions+ if (globals.rateLimit !== undefined && !/^[1-9]\d*$/.test(globals.rateLimit)) {+ throw new HogError(+ 'invalid_setting',+ `The rate limit must be a whole number of requests per minute, but it is "${globals.rateLimit}".`,+ undefined,+ EXIT_USAGE+ )+ }+ return globals+}++const WINDOW_MS = 60_000++export function networkRuntime(runtime: Runtime, globals: GlobalOptions): Runtime {+ if (globals.skipSslVerification) {+ runtime.skipTlsVerification()+ }+ const limit = globals.rateLimit === undefined ? undefined : Number(globals.rateLimit)+ if (limit === undefined && !globals.debug) {+ return runtime+ }+ const started: number[] = []+ let queue = Promise.resolve()+ const waitTurn = (): Promise<void> => {+ const turn = queue.then(async () => {+ if (limit === undefined) {+ return+ }+ while (started.length > 0 && runtime.now() - started[0]! >= WINDOW_MS) {+ started.shift()+ }+ if (started.length >= limit) {+ await runtime.sleep(WINDOW_MS - (runtime.now() - started[0]!))+ started.shift()+ }+ started.push(runtime.now())+ })+ queue = turn+ return turn+ }+ const fetch: RuntimeFetch = async (input, init) => {+ if (!init?.skipRateLimit) {+ await waitTurn()+ }+ if (!globals.debug) {+ return runtime.fetch(input, init)+ }+ const url = new URL(input instanceof Request ? input.url : String(input))+ // The query string can carry a signed upload URL's credentials, so only the path prints.+ const label = `${init?.method ?? 'GET'} ${url.origin}${url.pathname}`+ const begin = runtime.now()+ try {+ const response = await runtime.fetch(input, init)+ runtime.writeStderr(`[debug] ${label} ${response.status} ${runtime.now() - begin}ms\n`)+ return response+ } catch (error) {+ runtime.writeStderr(`[debug] ${label} failed: ${error instanceof Error ? error.message : error}\n`)+ throw error+ }+ }+ return { ...runtime, fetch }+}diff --git a/hog/src/core/manifest.ts b/hog/src/core/manifest.tsindex a9df11756cca..df83d320ba6c 100644--- a/hog/src/core/manifest.ts+++ b/hog/src/core/manifest.ts@@ -1,5 +1,5 @@import { optionFlags, type CommandTree, type OptionSpec } from './command'-import { GLOBAL_OPTIONS } from './context'+import { GLOBAL_OPTIONS } from './globals'import { kebabCase } from './text'interface OptionEntry {@@ -8,6 +8,8 @@ interface OptionEntry {takesValue: booleanchoices?: readonly string[]repeatable?: boolean+ env?: readonly string[]+ config?: string}export interface ManifestEntry {@@ -29,6 +31,8 @@ function describeOptions(options: Readonly<Record<string, OptionSpec>>): OptionEtakesValue: spec.type === 'string',choices: spec.type === 'string' ? spec.choices : undefined,repeatable: spec.type === 'string' && spec.multiple === true ? true : undefined,+ env: spec.env,+ config: spec.config,}))}diff --git a/hog/src/core/runtime.ts b/hog/src/core/runtime.tsindex 261541eb5360..e9126c1417cc 100644--- a/hog/src/core/runtime.ts+++ b/hog/src/core/runtime.ts@@ -10,6 +10,13 @@ import { clackPrompts, type Prompts } from './prompts'export type Env = Readonly<Record<string, string | undefined>>+// `timeoutMs` starts when the request leaves, so time spent waiting for --rate-limit doesn't count.+// `skipRateLimit` marks a signed storage URL, which posthog-cli's --rate-limit doesn't count either.+export type RuntimeFetch = (+ input: string | URL | Request,+ init?: RequestInit & { timeoutMs?: number; skipRateLimit?: boolean }+) => Promise<Response>+// Everything a command touches outside its own arguments. Tests build one by hand,// so no command reads `process` or the network directly.export interface Runtime {@@ -20,7 +27,7 @@ export interface Runtime {stdoutColumns: number | undefinedwriteStdout: (text: string) => voidwriteStderr: (text: string) => void- fetch: typeof fetch+ fetch: RuntimeFetchnow: () => numbersleep: (ms: number) => Promise<void>homeDir: () => string | undefined@@ -40,6 +47,8 @@ export interface Runtime {// Resolves to false when no browser could be started, for example on a server without one.openUrl: (url: string) => Promise<boolean>prompts: Prompts+ // Accepts any TLS certificate from here on, for every request, including the API tools' own.+ skipTlsVerification: () => void// The MCP server's tool catalog, which `hog api` browses and calls. Loaded on first use: it is large.loadApiTools: () => Promise<ApiToolLibrary>}@@ -71,7 +80,11 @@ export function processRuntime(): Runtime {writeStderr: (text) => {process.stderr.write(text)},- fetch: globalThis.fetch,+ fetch: (input, { timeoutMs, skipRateLimit: _skipRateLimit, ...init } = {}) =>+ globalThis.fetch(+ input,+ timeoutMs === undefined ? init : { ...init, signal: AbortSignal.timeout(timeoutMs) }+ ),now: () => Date.now(),sleep: (ms) => Bun.sleep(ms),homeDir: () => {@@ -137,6 +150,10 @@ export function processRuntime(): Runtime {}},prompts: clackPrompts(),+ skipTlsVerification: () => {+ // Runs only for --skip-ssl-verification, posthog-cli's opt-in flag for self-hosted certificates.+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0' // nosemgrep: trailofbits.generic.node-disable-certificate-validation.node-disable-certificate-validation+ },loadApiTools: async () => {try {const { createApiToolLibrary } = await import('@posthog/mcp/dist/cli-library.mjs')diff --git a/hog/src/error-tracking/release.ts b/hog/src/error-tracking/release.tsindex 3eeef728c65a..432428b19f87 100644--- a/hog/src/error-tracking/release.ts+++ b/hog/src/error-tracking/release.ts@@ -47,6 +47,16 @@ function gitMetadata(git: GitInfo): Record<string, string> {)}+// Looks the release up without creating it, for a dry run.+export async function findRelease(+ client: SymbolSetClient,+ name: string,+ version: string+): Promise<Release | undefined> {+ const existing = await lookup(client, releaseHashId(name, version))+ return existing && { ...existing, id: existing.id.toLowerCase() }+}+async function lookup(client: SymbolSetClient, hashId: string): Promise<Release | undefined> {try {return (await client.api('GET', `error_tracking/releases/hash/${hashId}`)) as Releasediff --git a/hog/src/error-tracking/symbols.ts b/hog/src/error-tracking/symbols.tsindex da78c4209c2d..ff376fe41a04 100644--- a/hog/src/error-tracking/symbols.ts+++ b/hog/src/error-tracking/symbols.ts@@ -3,6 +3,7 @@ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'import { inflateRawSync, zstdDecompressSync } from 'node:zlib'import { HogError } from '@/core/errors'+import type { RuntimeFetch } from '@/core/runtime'import { SymbolDataType } from './container'import { decodeUtf8 } from './json'@@ -191,10 +192,12 @@ function readZip(zip: Buffer): ZipEntry[] {// `extract_dsym_zip`: entries go under `{output}/{base}/`, keeping only normal path components so// an entry can't escape the folder.-function extractZip(zip: Buffer, baseName: string, output: string, cwd: string): string[] {+function extractZip(zip: Buffer, baseName: string, output: string, cwd: string, dryRun: boolean): string[] {const folder = join(output, baseName)const root = resolve(cwd, folder)- mkdirSync(root, { recursive: true })+ if (!dryRun) {+ mkdirSync(root, { recursive: true })+ }const written: string[] = []for (const entry of readZip(zip)) {const parts = pathParts(entry.name, process.platform).filter(@@ -215,8 +218,10 @@ function extractZip(zip: Buffer, baseName: string, output: string, cwd: string):`The symbol set's zip has an entry outside its folder: ${entry.name}`)}- mkdirSync(dirname(resolve(cwd, path)), { recursive: true })- writeFileSync(resolve(cwd, path), entry.data)+ if (!dryRun) {+ mkdirSync(dirname(resolve(cwd, path)), { recursive: true })+ writeFileSync(resolve(cwd, path), entry.data)+ }written.push(path)}return written@@ -224,11 +229,24 @@ function extractZip(zip: Buffer, baseName: string, output: string, cwd: string):// `extract_symbol_data`: tries each type in posthog-cli's order. A container whose payload fails// to decode falls through to the next type, as in posthog-cli.-// Paths in the report are as the caller gave them. Files are written relative to `cwd`.-export function extractSymbolSet(bytes: Uint8Array, baseName: string, output: string, cwd: string): ExtractReport {+// Paths in the report are as the caller gave them. Files are written relative to `cwd`, and a dry+// run lists them without writing.+export function extractSymbolSet(+ bytes: Uint8Array,+ baseName: string,+ output: string,+ cwd: string,+ dryRun = false+): ExtractReport {const data = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)- mkdirSync(resolve(cwd, output), { recursive: true })- const write = (path: string, data: Uint8Array): void => writeFileSync(resolve(cwd, path), data)+ if (!dryRun) {+ mkdirSync(resolve(cwd, output), { recursive: true })+ }+ const write = (path: string, data: Uint8Array): void => {+ if (!dryRun) {+ writeFileSync(resolve(cwd, path), data)+ }+ }// A container of a known type whose payload fails to decode: posthog-cli reports it as an// unknown type, which sends people after the wrong cause.let decodeError: { type: number; message: string } | undefined@@ -273,7 +291,7 @@ export function extractSymbolSet(bytes: Uint8Array, baseName: string, output: st}const elf = attempt(() => readPayload(data, SymbolDataType.ElfDebugInfo), SymbolDataType.ElfDebugInfo)if (elf) {- return { kind: 'elf', output: join(output, baseName), files: extractZip(elf, baseName, output, cwd) }+ return { kind: 'elf', output: join(output, baseName), files: extractZip(elf, baseName, output, cwd, dryRun) }}let dsym: Buffertry {@@ -290,7 +308,7 @@ export function extractSymbolSet(bytes: Uint8Array, baseName: string, output: st}throw new HogError('invalid_symbol_set', `hog couldn't read the symbol set: ${(error as Error).message}`)}- return { kind: 'dsym', output: join(output, baseName), files: extractZip(dsym, baseName, output, cwd) }+ return { kind: 'dsym', output: join(output, baseName), files: extractZip(dsym, baseName, output, cwd, dryRun) }}// `urlencoding::encode`: everything except A-Z, a-z, 0-9 and `-._~` is percent-encoded.@@ -347,7 +365,7 @@ export async function resolveRef(client: SymbolSetClient, reference: string): Prexport async function downloadSymbolSet(client: SymbolSetClient,id: string,- fetcher: typeof fetch+ fetcher: RuntimeFetch): Promise<Uint8Array> {if (!isSymbolSetId(id)) {throw new HogError('invalid_symbol_set_id', `${id} isn't a symbol set ID.`, 'Symbol set IDs are UUIDs.')@@ -357,7 +375,7 @@ export async function downloadSymbolSet(`No symbol set has the ID ${id}.`)) as { url: string }try {- const response = await fetcher(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) })+ const response = await fetcher(url, { timeoutMs: DOWNLOAD_TIMEOUT_MS, skipRateLimit: true })if (!response.ok) {throw new HogError('download_failed', `The symbol set download failed with status ${response.status}.`)}diff --git a/hog/src/error-tracking/upload.ts b/hog/src/error-tracking/upload.tsindex f822c657b536..07496a6a01ad 100644--- a/hog/src/error-tracking/upload.ts+++ b/hog/src/error-tracking/upload.ts@@ -166,7 +166,7 @@ export class SymbolSetClient {'User-Agent': USER_AGENT,},body: body === undefined ? undefined : JSON.stringify(body),- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ timeoutMs: REQUEST_TIMEOUT_MS,})} catch (error) {throw new ApiFailure(undefined, error instanceof Error ? error.message : String(error), url.toString())@@ -405,7 +405,8 @@ export class SymbolSetClient {return this.runtime.fetch(target.url, {method: 'PUT',body: data as BodyInit,- signal: AbortSignal.timeout(transferTimeout(data.length)),+ timeoutMs: transferTimeout(data.length),+ skipRateLimit: true,})}const form = new FormData()@@ -417,7 +418,8 @@ export class SymbolSetClient {return this.runtime.fetch(target.form.url, {method: 'POST',body: form,- signal: AbortSignal.timeout(transferTimeout(data.length)),+ timeoutMs: transferTimeout(data.length),+ skipRateLimit: true,})}}diff --git a/hog/src/posthog/api.ts b/hog/src/posthog/api.tsindex e30b7676bb7f..4fbbb20fc4e7 100644--- a/hog/src/posthog/api.ts+++ b/hog/src/posthog/api.ts@@ -1,5 +1,6 @@import { HogError } from '@/core/errors'import { parseLossless } from '@/core/raw-json'+import type { RuntimeFetch } from '@/core/runtime'import { VERSION } from '@/version'import type { Credentials } from './credentials'@@ -26,7 +27,7 @@ export interface HttpResponse {// Sends one JSON request to PostHog. Any failure before the whole body arrives, including the// deadline, is a `network_error`, so callers handle a dropped connection in one place.-export async function sendRequest(fetchFn: typeof fetch, url: URL, request: HttpRequest): Promise<HttpResponse> {+export async function sendRequest(fetchFn: RuntimeFetch, url: URL, request: HttpRequest): Promise<HttpResponse> {const headers: Record<string, string> = { 'Content-Type': 'application/json', 'User-Agent': USER_AGENT }if (request.apiKey) {headers.Authorization = `Bearer ${request.apiKey}`@@ -38,7 +39,7 @@ export async function sendRequest(fetchFn: typeof fetch, url: URL, request: Httpmethod: request.method,headers,body: request.body === undefined ? undefined : JSON.stringify(request.body),- signal: AbortSignal.timeout(request.timeoutMs ?? REQUEST_TIMEOUT_MS),+ timeoutMs: request.timeoutMs ?? REQUEST_TIMEOUT_MS,})text = await response.text()} catch (error) {@@ -73,7 +74,7 @@ export class ApiError extends HogError {export class PostHogApi {constructor(private readonly credentials: Credentials,- private readonly fetchFn: typeof fetch+ private readonly fetchFn: RuntimeFetch) {}// Paths are relative to the project, so `query` is /api/environments/<project id>/query. A pathdiff --git a/hog/src/posthog/credentials.test.ts b/hog/src/posthog/credentials.test.tsindex d29a73210a04..129ed505d77a 100644--- a/hog/src/posthog/credentials.test.ts+++ b/hog/src/posthog/credentials.test.ts@@ -5,8 +5,8 @@ import { fakeRuntime } from '@/testing'import { DEFAULT_HOST, resolveCredentials } from './credentials'-const ENV = { POSTHOG_CLI_API_KEY: 'phx_env', POSTHOG_CLI_PROJECT_ID: '1', POSTHOG_CLI_HOST: 'https://env.example.com' }-const DOTENV = 'POSTHOG_CLI_API_KEY="phx_dotenv"\n# comment\nPOSTHOG_CLI_PROJECT_ID=2\n'+const ENV = { HOG_API_KEY: 'phx_env', HOG_PROJECT_ID: '1', HOG_HOST: 'https://env.example.com' }+const DOTENV = 'HOG_API_KEY="phx_dotenv"\n# comment\nHOG_PROJECT_ID=2\n'const STORED = JSON.stringify({ token: 'phx_stored', env_id: '3', host: 'https://stored.example.com' })describe('resolveCredentials', () => {@@ -21,16 +21,6 @@ describe('resolveCredentials', () => {'1','https://env.example.com',],- [- 'legacy env aliases still work',- { POSTHOG_CLI_TOKEN: 'phx_old', POSTHOG_CLI_ENV_ID: '9' },- {},- undefined,- undefined,- 'phx_old',- '9',- DEFAULT_HOST,- ],['the dotenv file is next',{},@@ -41,16 +31,6 @@ describe('resolveCredentials', () => {'2',DEFAULT_HOST,],- [- 'POSTHOG_CLI_DOTENV_FILE names the dotenv file',- { POSTHOG_CLI_DOTENV_FILE: '/x/.env' },- { '/x/.env': DOTENV },- undefined,- undefined,- 'phx_dotenv',- '2',- DEFAULT_HOST,- ],['a missing dotenv file falls back to the credentials file',{},@@ -72,8 +52,8 @@ describe('resolveCredentials', () => {'https://stored.example.com',],[- 'POSTHOG_HOME moves the credentials file',- { POSTHOG_HOME: '/custom' },+ 'HOG_HOME moves the credentials file',+ { HOG_HOME: '/custom' },{ '/custom/credentials.json': STORED },undefined,undefined,@@ -97,27 +77,39 @@ describe('resolveCredentials', () => {})test.each([- ['nothing configured', {}, 'not_authenticated', {}],+ ['nothing configured', {}, 'not_authenticated', {}, undefined],+ [+ "posthog-cli's variable names",+ { POSTHOG_CLI_API_KEY: 'phx_a', POSTHOG_CLI_PROJECT_ID: '1' },+ 'not_authenticated',+ {},+ undefined,+ ],['a key without the phx_ prefix',- { POSTHOG_CLI_API_KEY: 'abc', POSTHOG_CLI_PROJECT_ID: '1' },+ { HOG_API_KEY: 'abc', HOG_PROJECT_ID: '1' },'invalid_credentials',{},+ undefined,],['a project ID that is not a number',- { POSTHOG_CLI_API_KEY: 'phx_a', POSTHOG_CLI_PROJECT_ID: 'two' },+ { HOG_API_KEY: 'phx_a', HOG_PROJECT_ID: 'two' },'invalid_credentials',{},+ undefined,],['a dotenv file without the credentials',- { POSTHOG_CLI_DOTENV_FILE: '/x/.env' },+ {},'not_authenticated',{ '/x/.env': 'OTHER=1\n', '/home/test/.posthog/credentials.json': STORED },+ '/x/.env',],- ] as const)('fails on %s', async (_name, env, code, files: Record<string, string>) => {- const error = await resolveCredentials(fakeRuntime({ env, files }), {}).catch((caught: unknown) => caught)+ ] as const)('fails on %s', async (_name, env, code, files: Record<string, string>, dotenvFile) => {+ const error = await resolveCredentials(fakeRuntime({ env, files }), { dotenvFile }).catch(+ (caught: unknown) => caught+ )expect(error).toBeInstanceOf(HogError)expect((error as HogError).code).toBe(code)})diff --git a/hog/src/posthog/credentials.ts b/hog/src/posthog/credentials.tsindex ca6103810852..6088e79e360e 100644--- a/hog/src/posthog/credentials.ts+++ b/hog/src/posthog/credentials.ts@@ -1,6 +1,6 @@import { join } from 'node:path'-import { HogError } from '@/core/errors'+import { EXIT_USAGE, HogError } from '@/core/errors'import type { Env, Runtime } from '@/core/runtime'// posthog-cli falls back to this host when neither --host nor the credentials name one.@@ -22,17 +22,17 @@ interface RawCredentials {host: string | undefined}-export const API_KEY_ENV_VARS = ['POSTHOG_CLI_API_KEY', 'POSTHOG_CLI_TOKEN'] as const+export const API_KEY_ENV_VAR = 'HOG_API_KEY'-// Same variables and aliases as posthog-cli. The host only counts when it comes from the-// same source as the key, so a stray host cannot redirect a key from somewhere else.+// The host only counts when it comes from the same source as the key, so a stray host cannot+// redirect a key from somewhere else.function fromLookup(lookup: (name: string) => string | undefined): RawCredentials | undefined {- const apiKey = lookup(API_KEY_ENV_VARS[0]) ?? lookup(API_KEY_ENV_VARS[1])- const projectId = lookup('POSTHOG_CLI_PROJECT_ID') ?? lookup('POSTHOG_CLI_ENV_ID')+ const apiKey = lookup(API_KEY_ENV_VAR)+ const projectId = lookup('HOG_PROJECT_ID')if (!apiKey || !projectId) {return undefined}- return { apiKey, projectId, host: lookup('POSTHOG_CLI_HOST') || undefined }+ return { apiKey, projectId, host: lookup('HOG_HOST') || undefined }}function parseDotenv(contents: string, path: string): Map<string, string> {@@ -80,8 +80,8 @@ async function readDotenv(runtime: Runtime, path: string): Promise<string | unde}function posthogHomeDir(env: Env, homeDir: string | undefined): string | undefined {- if (env.POSTHOG_HOME) {- return env.POSTHOG_HOME+ if (env.HOG_HOME) {+ return env.HOG_HOME}return homeDir === undefined ? undefined : join(homeDir, '.posthog')}@@ -92,7 +92,7 @@ export function posthogFile(runtime: Runtime, name: string): string {throw new HogError('no_home_directory',"hog couldn't find your home folder to store credentials in.",- 'Set POSTHOG_HOME to the folder to use.'+ 'Set HOG_HOME to the folder to use.')}return join(home, name)@@ -106,6 +106,10 @@ export function checkProjectId(projectId: string): string | undefined {return /^\d+$/.test(projectId) ? undefined : `The project ID must be a number, but it is "${projectId}".`}+function sameOrigin(a: string, b: string): boolean {+ return URL.canParse(a) && URL.canParse(b) && new URL(a).origin === new URL(b).origin+}+export function checkHost(host: string): string | undefined {return URL.canParse(host) ? undefined : `The host must be a valid URL, but it is "${host}".`}@@ -143,22 +147,33 @@ export async function saveCredentials(runtime: Runtime, credentials: Credentials}// Lookup order matches posthog-cli: process env, then --dotenv-file, then the credentials-// file `hog auth login` and `posthog-cli login` write. --host overrides whichever host the source carried.+// file `hog auth login` and `posthog-cli login` write. The global host overrides whichever host the+// source carried. posthog.json comes from the repository, so its host never redirects a key: it+// only stops the command when the key belongs to another host.export async function resolveCredentials(runtime: Runtime,- options: { host?: string; dotenvFile?: string }+ options: { host?: string; dotenvFile?: string; configHost?: string }): Promise<ResolvedCredentials> {- const withHost = (raw: RawCredentials, source: CredentialSource): ResolvedCredentials => ({- ...validate(raw, options.host ?? raw.host ?? DEFAULT_HOST),- source,- })+ const withHost = (raw: RawCredentials, source: CredentialSource): ResolvedCredentials => {+ const host = options.host ?? raw.host ?? DEFAULT_HOST+ const { configHost } = options+ if (options.host === undefined && configHost !== undefined && !sameOrigin(configHost, host)) {+ throw new HogError(+ 'host_mismatch',+ `posthog.json sets the host to ${configHost}, but your credentials are for ${host}.`,+ `Pass --host ${configHost} or set HOG_HOST to send your credentials there, or log in to that host with \`hog auth login --host ${configHost}\`.`,+ EXIT_USAGE+ )+ }+ return { ...validate(raw, host), source }+ }const fromEnv = fromLookup((name) => runtime.env[name] || undefined)if (fromEnv) {return withHost(fromEnv, 'env')}- const dotenvFile = options.dotenvFile ?? (runtime.env.POSTHOG_CLI_DOTENV_FILE || undefined)+ const dotenvFile = options.dotenvFileif (dotenvFile) {const contents = await readDotenv(runtime, dotenvFile)if (contents !== undefined) {@@ -167,7 +182,7 @@ export async function resolveCredentials(if (!fromFile) {throw new HogError('not_authenticated',- `hog couldn't find POSTHOG_CLI_API_KEY and POSTHOG_CLI_PROJECT_ID in the environment or in ${dotenvFile}.`,+ `hog couldn't find HOG_API_KEY and HOG_PROJECT_ID in the environment or in ${dotenvFile}.`,'Add both variables to the file, or remove --dotenv-file.')}@@ -196,6 +211,6 @@ export async function resolveCredentials(throw new HogError('not_authenticated',"hog couldn't find PostHog credentials.",- 'Run `hog auth login`, or set POSTHOG_CLI_API_KEY and POSTHOG_CLI_PROJECT_ID.'+ 'Run `hog auth login`, or set HOG_API_KEY and HOG_PROJECT_ID.')}diff --git a/hog/src/testing.ts b/hog/src/testing.tsindex d23762a2259e..360dc35db9cf 100644--- a/hog/src/testing.ts+++ b/hog/src/testing.ts@@ -31,6 +31,7 @@ export interface FakeRuntime extends Runtime {requests: { method: string; url: string; body: unknown }[]files: Record<string, string>opened: string[]+ tls: { verify: boolean }}function fakePrompts(answers: string[]): Prompts {@@ -57,6 +58,7 @@ export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {const requests: FakeRuntime['requests'] = []const files = { ...options.files }const opened: string[] = []+ const tls = { verify: true }// A clock that only moves when hog sleeps, so polling runs instantly.let clock = Date.UTC(2026, 0, 1)return {@@ -134,6 +136,9 @@ export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {return true},prompts: fakePrompts([...(options.answers ?? [])]),+ skipTlsVerification: () => {+ tls.verify = false+ },loadApiTools: async () => {if (!options.apiTools) {throw new Error('This test loads the API tools without passing apiTools')@@ -145,14 +150,15 @@ export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {requests,files,opened,+ tls,}}// Credentials that pass validation, plus NO_COLOR so text output has no escape codes.export const TEST_CREDENTIALS = {- POSTHOG_CLI_API_KEY: 'phx_test',- POSTHOG_CLI_PROJECT_ID: '7',- POSTHOG_CLI_HOST: 'https://ph.example.com',+ HOG_API_KEY: 'phx_test',+ HOG_PROJECT_ID: '7',+ HOG_HOST: 'https://ph.example.com',NO_COLOR: '1',}@@ -163,12 +169,15 @@ export interface HogRun {requests: FakeRuntime['requests']files: Record<string, string>opened: string[]+ elapsedMs: number+ tls: { verify: boolean }json: () => anyerror: () => any}export async function runHog(argv: string[], options: FakeRuntimeOptions = {}): Promise<HogRun> {const runtime = fakeRuntime(options)+ const start = runtime.now()const exitCode = await run(argv, runtime)return {exitCode,@@ -177,6 +186,8 @@ export async function runHog(argv: string[], options: FakeRuntimeOptions = {}):requests: runtime.requests,files: runtime.files,opened: runtime.opened,+ elapsedMs: runtime.now() - start,+ tls: runtime.tls,json: () => JSON.parse(runtime.stdout()),error: () => JSON.parse(runtime.stderr()).error,}diff --git a/hog/test/parity/run.ts b/hog/test/parity/run.tsindex 6e09821fa9b0..e7ee3c5f4d82 100644--- a/hog/test/parity/run.ts+++ b/hog/test/parity/run.ts@@ -18,13 +18,18 @@ export interface ParityResult {files?: Record<string, string | null>}+// posthog-cli reads the POSTHOG_CLI_ names and hog the HOG_ ones, so both CLIs get the same credentials.function environment(serverUrl: string, home: string): Record<string, string> {return {HOME: home,POSTHOG_HOME: home,+ HOG_HOME: home,POSTHOG_CLI_API_KEY: 'phx_parity',POSTHOG_CLI_PROJECT_ID: '1',POSTHOG_CLI_HOST: serverUrl,+ HOG_API_KEY: 'phx_parity',+ HOG_PROJECT_ID: '1',+ HOG_HOST: serverUrl,NO_COLOR: '1',}}