Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(hog): add query run and query check with agent-aware output (#124430)

Rafael Audibert90ebd37f9e23
diff --git a/.flox/env/manifest.lock b/.flox/env/manifest.lock
index d10598843c39..6ed575fc3e16 100644
--- a/.flox/env/manifest.lock
+++ b/.flox/env/manifest.lock
@@ -11,6 +11,11 @@
"pkg-path": "brotli",
"pkg-group": "nodejs"
},
+ "bun": {
+ "pkg-path": "bun",
+ "pkg-group": "bun",
+ "version": "^1.4.2"
+ },
"cargo": {
"pkg-path": "cargo",
"pkg-group": "rust-toolchain",
@@ -3230,6 +3235,95 @@
"system": "x86_64-linux",
"group": "uv",
"priority": 5
+ },
+ {
+ "attr_path": "bun",
+ "broken": false,
+ "derivation": "/nix/store/f23cfy3n50pzsx5apyxmwfmlkjnwkiqa-bun-1.4.2.drv",
+ "description": "Incredibly fast JavaScript runtime, bundler, transpiler and package manager – all in one",
+ "install_id": "bun",
+ "license": "[ MIT, LGPL-2.1-only ]",
+ "locked_url": "https://github.com/flox/nixpkgs?rev=3ec636362e1816bc2f0888fa0fa2c69f1bc9e504",
+ "name": "bun-1.4.2",
+ "pname": "bun",
+ "rev": "3ec636362e1816bc2f0888fa0fa2c69f1bc9e504",
+ "rev_count": 1100280,
+ "rev_date": "2026-10-23T16:35:39Z",
+ "scrape_date": "2026-10-25T05:51:32.488429Z",
+ "stabilities": [
+ "unstable"
+ ],
+ "unfree": false,
+ "version": "1.4.2",
+ "outputs_to_install": [
+ "out"
+ ],
+ "outputs": {
+ "out": "/nix/store/wjpdgxsjymr2nczy9y3d5h3h1xrbhhml-bun-1.4.2"
+ },
+ "system": "aarch64-darwin",
+ "group": "bun",
+ "priority": 5
+ },
+ {
+ "attr_path": "bun",
+ "broken": false,
+ "derivation": "/nix/store/3239bpm54higlwfdznq8cbsi4ln35fri-bun-1.4.2.drv",
+ "description": "Incredibly fast JavaScript runtime, bundler, transpiler and package manager – all in one",
+ "install_id": "bun",
+ "license": "[ MIT, LGPL-2.1-only ]",
+ "locked_url": "https://github.com/flox/nixpkgs?rev=3ec636362e1816bc2f0888fa0fa2c69f1bc9e504",
+ "name": "bun-1.4.2",
+ "pname": "bun",
+ "rev": "3ec636362e1816bc2f0888fa0fa2c69f1bc9e504",
+ "rev_count": 1100280,
+ "rev_date": "2026-10-23T16:35:39Z",
+ "scrape_date": "2026-10-25T06:24:58.728611Z",
+ "stabilities": [
+ "unstable"
+ ],
+ "unfree": false,
+ "version": "1.4.2",
+ "outputs_to_install": [
+ "out",
+ "out"
+ ],
+ "outputs": {
+ "out": "/nix/store/f8hiv5nmim0dpaxixmxiijdm8x0mffsy-bun-1.4.2"
+ },
+ "system": "aarch64-linux",
+ "group": "bun",
+ "priority": 5
+ },
+ {
+ "attr_path": "bun",
+ "broken": false,
+ "derivation": "/nix/store/4ql11clbibnp4l68sf11j49fkaf0zivl-bun-1.4.2.drv",
+ "description": "Incredibly fast JavaScript runtime, bundler, transpiler and package manager – all in one",
+ "install_id": "bun",
+ "license": "[ MIT, LGPL-2.1-only ]",
+ "locked_url": "https://github.com/flox/nixpkgs?rev=3ec636362e1816bc2f0888fa0fa2c69f1bc9e504",
+ "name": "bun-1.4.2",
+ "pname": "bun",
+ "rev": "3ec636362e1816bc2f0888fa0fa2c69f1bc9e504",
+ "rev_count": 1100280,
+ "rev_date": "2026-10-23T16:35:39Z",
+ "scrape_date": "2026-10-25T07:01:24.175483Z",
+ "stabilities": [
+ "unstable"
+ ],
+ "unfree": false,
+ "version": "1.4.2",
+ "outputs_to_install": [
+ "out",
+ "out"
+ ],
+ "outputs": {
+ "out": "/nix/store/2mxhj3nrvxxqm6gf6rwnrvz048zqdclp-bun-1.4.2"
+ },
+ "system": "x86_64-linux",
+ "group": "bun",
+ "priority": 5
}
]
}
diff --git a/.flox/env/manifest.toml b/.flox/env/manifest.toml
index 6f36c9c644d8..1de26ba650f4 100644
--- a/.flox/env/manifest.toml
+++ b/.flox/env/manifest.toml
@@ -61,6 +61,8 @@ trunk-io = { pkg-path = "trunk-io", version = "^1.3.4" } # Launcher for the Trun
# depot-cli has its own group because the toplevel group's version pins cannot resolve with it.
# Keep its version floor current: flox puts its bin first on PATH, so an old lock shadows a newer host `depot`.
depot-cli = { pkg-path = "depot-cli", pkg-group = "depot", version = "^2.102" }
+# hog (hog/) needs Bun 1.3.3+ to turn off .env and bunfig.toml autoloading. 1.4.2 is the newest in the catalog.
+bun = { pkg-path = "bun", pkg-group = "bun", version = "^1.4.2" }
# Set environment variables in the `[vars]` section. These variables may not
# reference one another, and are added to the environment without first
diff --git a/hog/AGENTS.md b/hog/AGENTS.md
new file mode 100644
index 000000000000..0fcabe4a2f3f
--- /dev/null
+++ b/hog/AGENTS.md
@@ -0,0 +1,60 @@
+# hog
+
+`hog` is the PostHog command line, version 1. Read [README.md](README.md) for what it does and how to run it.
+
+## Layout
+
+| Path | Holds |
+| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
+| `src/commands/` | One file per command. `index.ts` is the tree of every command; `legacy.ts` holds the ones posthog-cli still owns |
+| `src/core/` | The shared parts every command uses: command definitions, context and global options, output, agent detection, errors, runtime, the manifest |
+| `src/posthog/` | The PostHog API client and credentials |
+| `src/cli.ts` | Turns the command tree into a commander program, runs it, and maps errors to exit codes |
+| `src/testing.ts` | `runHog` and a fake runtime, so tests run the real CLI without a process or a network |
+
+Import from another folder with `@/`, which `tsconfig.json` maps to `src/`, as in `import { defineCommand } from '@/core/command'`. Use `./` only inside the same folder.
+
+## Add a command
+
+1. Write `src/commands/<group>/<name>.ts` with `defineCommand`. Put it in a `defineGroup` when it has siblings.
+2. Add it to the tree in `src/commands/index.ts`, and remove its `defineLegacy` entry from `src/commands/legacy.ts` if posthog-cli has one. A legacy entry can sit inside a group, so a group can be half ported.
+3. Add cases to `src/commands/<group>/<group>.test.ts` with `runHog`.
+
+```ts
+export default defineCommand({
+ description: 'List the feature flags in your project',
+ args: { search: { description: 'Only show flags whose key contains this text', optional: true } },
+ options: { active: { type: 'boolean', description: 'Only show active flags' } },
+ scopes: ['feature_flag:read'],
+ examples: ['hog flags list checkout'],
+
+ async run({ args, options, ctx }) {
+ const api = await ctx.posthog()
+ const flags = await api.get<{ results: Flag[] }>(`feature_flags/?search=${encodeURIComponent(args.search ?? '')}`)
+ return options.active ? flags.results.filter((flag) => flag.active) : flags.results
+ },
+ human({ result, out }) {
+ out.table(
+ ['key', 'active'],
+ result.map((flag) => [flag.key, flag.active])
+ )
+ },
+ agent({ result, out }) {
+ out.jsonLines(result)
+ },
+})
+```
+
+## Rules
+
+- `run` returns data and never prints. `human` decides what a person at a terminal sees, and `agent` decides what agents, pipes and `-o json` see. Without them, people get indented JSON and agents get one line of JSON.
+- Agent output is JSON only, on stdout, with no color and no prose. Prefer `out.jsonLines` for lists, so an agent can stream them.
+- `out.table` colors each column by kind (number, date, boolean, JSON) and fits the terminal width. Pass a `kind` when the API declares column types, as `hog query run` does with ClickHouse types. Otherwise the kind comes from the values.
+- A failure throws a `HogError` with a stable `code` and a `hint` that names the next step. `cli.ts` prints it as text or as JSON on stderr. Do not catch errors to print them yourself.
+- `exitCode` is for results that are not failures but that a script must branch on, like `hog query check` finding errors.
+- `--raw` is global: it prints the result of `run` as JSON and skips both views. Do not add per-command `--raw` or `--debug` flags; return enough data from `run` instead.
+- An argument with `stdin: true` reads stdin when the caller passes `-`, and fails when it is empty. `hog commands` tells agents which arguments accept it.
+- Commands reach the outside world only through `ctx` (`ctx.posthog()`, `ctx.runtime`), so tests can fake it. Do not read `process` or call `fetch` directly.
+- Import heavy dependencies inside `run` with `await import()`. Every command module loads on every call, so a top-level import of a large library slows down all commands.
+- Declare `scopes`. `hog commands` lists them for agents, and a 403 names them in its hint.
+- Every string a person reads follows `/writing-user-facing-copy`: sentence case, no em dashes.
diff --git a/hog/CLAUDE.md b/hog/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/hog/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/hog/README.md b/hog/README.md
index becee42bf302..62b839b87b74 100644
--- a/hog/README.md
+++ b/hog/README.md
@@ -10,12 +10,44 @@ It is not published yet.
`hog` has no `exp` namespace.
The commands `posthog-cli` keeps under `exp` (`query`, `endpoints`, `logs`, `tasks`, `schema`) are top-level commands in `hog`.
-Every command fails until it is implemented.
-It exits with code 1 and prints the `posthog-cli` command to run instead, with the same arguments.
+
+| Command | Status |
+| ------------------------- | --------------------------------------------------------------------------------------------------------------- |
+| `hog query run <query>` | Runs a HogQL query. `-` reads the query from stdin. |
+| `hog query check <query>` | Checks a query without running it. Exits with code 1 when the query has errors. |
+| `hog commands` | Lists every command, its arguments, options and scopes. |
+| Everything else | Not ported yet. Exits with code 1 and prints the `posthog-cli` command to run instead, with the same arguments. |
+
+## Agents, people and pipes
+
+`hog` detects an agent from the env vars agents set for the commands they run, such as `CLAUDECODE`, `CODEX_SANDBOX`, `CURSOR_AGENT`, `GEMINI_CLI` and the generic `AI_AGENT`.
+`HOG_AGENT=1` forces agent mode, and `HOG_AGENT=0` turns detection off.
+
+| Caller | Default output | Errors |
+| ---------------------- | ----------------------------------------- | ---------------------------------------------------------------- |
+| A person at a terminal | Text, with color unless `NO_COLOR` is set | Text on stderr |
+| An agent | JSON | One JSON object on stderr: `{"error":{"code","message","hint"}}` |
+| A pipe or a script | JSON | Same as an agent |
+
+`-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.
+
+## Credentials
+
+`hog` reads the same credentials as `posthog-cli`, in the same order:
+
+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 `posthog-cli login` writes (`POSTHOG_HOME` moves the folder)
+
+`--host` overrides the host from any of these.
## Develop
-Install [Bun](https://bun.sh), then from the repo root:
+Each command is one file under `src/commands/`, and declares what people and agents see separately.
+[AGENTS.md](AGENTS.md) has the layout and the steps to add a command.
+
+Install [Bun](https://bun.sh) 1.3.3 or later, then from the repo root:
```bash
pnpm --filter @posthog/hog hog --help # run hog from source
@@ -23,3 +55,5 @@ pnpm --filter @posthog/hog unit # run the tests
pnpm --filter @posthog/hog typecheck # check types
pnpm --filter @posthog/hog compile # build dist/hog for this machine
```
+
+hog reads credentials only from the sources above, like posthog-cli. Bun would otherwise load a `.env` or `bunfig.toml` from the working folder, so the scripts turn that off. Older Bun versions ignore those flags, hence the minimum version.
diff --git a/hog/package.json b/hog/package.json
index e425849b73cc..9b72affdfc4b 100644
--- a/hog/package.json
+++ b/hog/package.json
@@ -8,13 +8,20 @@
},
"type": "module",
"scripts": {
- "hog": "bun src/index.ts",
- "compile": "bun build --compile src/index.ts --outfile dist/hog",
+ "hog": "bun --no-env-file src/index.ts",
+ "compile": "bun build --compile --no-compile-autoload-dotenv --no-compile-autoload-bunfig src/index.ts --outfile dist/hog",
"typecheck": "tsc --noEmit",
"unit": "bun test"
},
+ "dependencies": {
+ "cli-table3": "0.6.5",
+ "commander": "15.0.0"
+ },
"devDependencies": {
"@types/bun": "1.3.14",
"typescript": "catalog:"
+ },
+ "engines": {
+ "bun": ">=1.3.3"
}
}
diff --git a/hog/src/cli.test.ts b/hog/src/cli.test.ts
index f6d2470df096..50159c22611c 100644
--- a/hog/src/cli.test.ts
+++ b/hog/src/cli.test.ts
@@ -1,52 +1,94 @@
import { describe, expect, test } from 'bun:test'
-import pkg from '../package.json' with { type: 'json' }
-import { run } from './cli'
-import { COMMANDS } from './commands'
-
-function capture(argv: readonly string[]): { code: number; stdout: string; stderr: string } {
- let stdout = ''
- let stderr = ''
- const code = run(argv, {
- stdout: (text) => (stdout += text),
- stderr: (text) => (stderr += text),
- })
- return { code, stdout, stderr }
-}
+import { LEGACY_COMMANDS } from '@/commands/legacy'
+import { VERSION } from '@/version'
+
+import { runHog } from './testing'
describe('hog', () => {
test.each([
- ['no arguments prints help', [], 0, 'Usage: hog <command>', ''],
- ['--version prints the version', ['--version'], 0, pkg.version, ''],
- ['an unknown command fails', ['nope'], 1, '', 'Unknown command: nope'],
+ ['no arguments prints help', [], 'Usage: hog'],
+ ['--version prints the version', ['--version'], VERSION],
+ ['help for a command prints its usage', ['help', 'query', 'run'], 'Usage: hog query run'],
[
- 'an unported command passes its arguments to posthog-cli, quoted',
- ['query', 'run', "select 'a' from events"],
- 1,
- '',
- `posthog-cli exp query run 'select '\\''a'\\'' from events'`,
+ 'help after a global option still finds the command',
+ ['-o', 'json', 'help', 'query', 'run'],
+ 'Usage: hog query run',
],
[
- 'help for an unported command points to its posthog-cli help',
- ['help', 'dsym', 'upload'],
- 1,
- '',
- 'posthog-cli dsym upload --help',
+ 'command help lists examples and scopes',
+ ['query', 'run', '--help'],
+ 'Needs a personal API key with: query:read',
],
- ] as const)('%s', (_name, argv, code, stdout, stderr) => {
- const result = capture(argv)
- expect(result.code).toBe(code)
+ ])('%s', async (_name, argv, stdout) => {
+ const result = await runHog(argv)
+ expect(result.exitCode).toBe(0)
expect(result.stdout).toContain(stdout)
- expect(result.stderr).toContain(stderr)
})
- test.each(COMMANDS.map((command) => [command.name, command.legacyCommand]))(
+ test.each(Object.entries(LEGACY_COMMANDS).map(([name, command]) => [name, 'use' in command ? command.use : '']))(
'%s fails and points to %s',
- (name, legacyCommand) => {
- const result = capture([name, '--some-flag'])
- expect(result.code).toBe(1)
- expect(result.stdout).toBe('')
- expect(result.stderr).toContain(`${legacyCommand} --some-flag`)
+ async (name, use) => {
+ const result = await runHog([name, 'sub', "it's", '--flag'])
+ expect(result.exitCode).toBe(1)
+ expect(result.error()).toMatchObject({ code: 'not_ported' })
+ expect(result.error().message).toContain(`${use} sub 'it'\\''s' --flag`)
}
)
+
+ test.each([
+ ['help for an unported command', ['help', 'dsym', 'upload'], 'posthog-cli dsym upload --help'],
+ ['an unported subcommand of a ported group', ['query', 'editor'], 'posthog-cli exp query editor'],
+ [
+ 'hog globals that posthog-cli takes before the subcommand',
+ ['-o', 'json', '--host', 'https://eu.example.com', 'dsym', 'upload', '--dotenv-file=p.env', '--dir', 'x'],
+ 'posthog-cli --host https://eu.example.com --dotenv-file p.env dsym upload --dir x',
+ ],
+ [
+ 'an --output that the legacy command owns',
+ ['endpoints', 'pull', 'example', '--output', './queries'],
+ 'posthog-cli exp endpoints pull example --output ./queries',
+ ],
+ ])('%s points to posthog-cli', async (_name, argv, invocation) => {
+ const result = await runHog(argv)
+ expect(result.exitCode).toBe(1)
+ expect(result.error().message).toEndWith(`Run this instead:\n ${invocation}`)
+ })
+
+ test.each([
+ ['an unknown command', ['nope'], 'unknown_command'],
+ ['a missing argument', ['query', 'run'], 'usage_error'],
+ ['an invalid --output', ['query', 'run', 'select 1', '-o', 'yaml'], 'usage_error'],
+ ])('%s is a usage error, reported as JSON to agents', async (_name, argv, code) => {
+ const result = await runHog(argv, { env: { CLAUDECODE: '1' } })
+ expect(result.exitCode).toBe(2)
+ expect(result.error()).toMatchObject({ code })
+ })
+
+ test('a person sees errors as text', async () => {
+ const result = await runHog(['qury'], { stdoutIsTTY: true, env: { NO_COLOR: '1' } })
+ expect(result.stderr).toBe(
+ "Error: Unknown command 'qury'\n(Did you mean query?)\nRun `hog --help` to see the available commands.\n"
+ )
+ })
+
+ test('commands lists every command for agents', async () => {
+ const result = await runHog(['commands'], { env: { CLAUDECODE: '1' } })
+ expect(result.exitCode).toBe(0)
+ const manifest = result.json()
+ expect(manifest).toMatchObject({ cli: 'hog', agent: 'claude-code' })
+ expect(manifest.globalOptions).toContainEqual(expect.objectContaining({ flags: '-o, --output <format>' }))
+ expect(manifest.commands[0]).toMatchObject({
+ name: 'query run',
+ arguments: [{ name: 'query', required: true, stdin: true }],
+ scopes: ['query:read'],
+ })
+ expect(manifest.commands.map((command: { name: string }) => command.name)).toEqual([
+ 'query run',
+ 'query check',
+ 'query editor',
+ 'commands',
+ ...Object.keys(LEGACY_COMMANDS),
+ ])
+ })
})
diff --git a/hog/src/cli.ts b/hog/src/cli.ts
index b16e69813dab..ea17ad9d1e56 100644
--- a/hog/src/cli.ts
+++ b/hog/src/cli.ts
@@ -1,58 +1,303 @@
-import pkg from '../package.json' with { type: 'json' }
-import { COMMANDS } from './commands'
+import { Command as Commander, CommanderError, Option } from 'commander'
+import { parseArgs, type ParseArgsOptionsConfig } from 'node:util'
-export interface Output {
- stdout: (text: string) => void
- stderr: (text: string) => void
+import { COMMANDS } from '@/commands'
+import { resolveMode, type Mode, type OutputFormat } from '@/core/agent'
+import {
+ argumentSyntax,
+ optionFlags,
+ type Command,
+ type CommandTree,
+ type Group,
+ type Legacy,
+ type OptionSpec,
+} from '@/core/command'
+import { Context, GLOBAL_OPTIONS, type GlobalOptions } from '@/core/context'
+import { EXIT_USAGE, HogError } from '@/core/errors'
+import { Output } from '@/core/output'
+import type { Runtime } from '@/core/runtime'
+import { kebabCase } from '@/core/text'
+import { ApiError } from '@/posthog/api'
+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 commands -o json\` to list every command, its arguments and its options.`
+
+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)
+ return spec.type === 'string' && spec.choices ? option.choices(spec.choices) : option
+}
+
+function helpText(command: Command): string {
+ const sections = [
+ command.notes,
+ command.examples?.length ? `Examples:\n${command.examples.map((example) => ` ${example}`).join('\n')}` : '',
+ command.scopes?.length ? `Needs a personal API key with: ${command.scopes.join(', ')}` : '',
+ ]
+ return sections
+ .filter(Boolean)
+ .map((section) => `\n${section}`)
+ .join('\n')
}
-const HELP_FLAGS = new Set(['-h', '--help', 'help'])
-const VERSION_FLAGS = new Set(['-V', '--version'])
const SHELL_SAFE_ARG = /^[\w@%+=:,./-]+$/
-export function shellQuote(arg: string): string {
+function shellQuote(arg: string): string {
return SHELL_SAFE_ARG.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`
}
-export function helpText(): string {
- const width = Math.max(...COMMANDS.map((command) => command.name.length)) + 2
- const commandLines = COMMANDS.map((command) => ` ${command.name.padEnd(width)}${command.summary}`)
- return [
- `hog ${pkg.version}`,
- 'The PostHog command line',
- '',
- 'Usage: hog <command> [options]',
- '',
- 'Commands:',
- ...commandLines,
- '',
- 'Options:',
- ' -h, --help Show this help',
- ' -V, --version Show the version',
- ].join('\n')
-}
-
-export function run(argv: readonly string[], output: Output): number {
- const [first, ...rest] = argv
- const [helpTarget, ...helpRest] = rest
- if (first === undefined || (HELP_FLAGS.has(first) && helpTarget === undefined)) {
- output.stdout(helpText())
- return 0
+// posthog-cli takes --host and --dotenv-file before the subcommand only. Every other argument
+// belongs to the legacy command, including an --output that names a path there.
+const LEGACY_GLOBALS = new Set(['host', 'dotenv-file'])
+
+function notPorted(argv: readonly string[], route: LegacyRoute): HogError {
+ const globals: string[] = []
+ const rest: string[] = []
+ const skip = new Set(route.pathIndices)
+ for (const token of route.tokens) {
+ if (token.kind !== 'option') {
+ continue
+ }
+ const beforePath = token.index < route.pathIndices[0]!
+ if (LEGACY_GLOBALS.has(token.name) || beforePath) {
+ skip.add(token.index)
+ if (token.value !== undefined && !token.inlineValue) {
+ skip.add(token.index + 1)
+ }
+ if (LEGACY_GLOBALS.has(token.name) && token.value !== undefined) {
+ globals.push(`--${token.name}`, token.value)
+ }
+ }
+ }
+ argv.forEach((arg, index) => {
+ if (!skip.has(index)) {
+ rest.push(arg)
+ }
+ })
+ const [binary, ...subcommand] = route.legacy.use.split(' ')
+ const invocation = [binary, ...globals.map(shellQuote), ...subcommand, ...rest.map(shellQuote)].join(' ')
+ return new HogError('not_ported', `\`hog ${route.path}\` isn't available yet. Run this instead:\n ${invocation}`)
+}
+
+// A 403 names the scopes the command declares, which the API client doesn't know about.
+function withScopeHint(error: unknown, scopes: readonly string[] | undefined): unknown {
+ if (error instanceof ApiError && error.status === 403 && scopes?.length) {
+ return error.withHint(
+ `Check that the personal API key has the ${scopes.join(', ')} scope and access to this project.`
+ )
+ }
+ return error
+}
+
+async function readArgument(runtime: Runtime, name: string, value: string): Promise<string> {
+ const text = value === '-' ? await runtime.readStdin() : value
+ if (!text.trim()) {
+ throw new HogError(
+ `empty_${name}`,
+ `The ${name} is empty.`,
+ `Pass the ${name} as an argument, or pipe it in with -.`
+ )
+ }
+ return text
+}
+
+function createProgram(runtime: Runtime, mode: Mode, state: { exitCode: number }): Commander {
+ const out = new Output(runtime, mode)
+
+ function addRunnable(command: Commander, node: Command): void {
+ const argEntries = Object.entries(node.args ?? {})
+ for (const [name, spec] of argEntries) {
+ command.argument(argumentSyntax(name, spec), spec.description)
+ }
+ for (const [name, spec] of Object.entries(node.options ?? {})) {
+ command.addOption(toOption(name, spec))
+ }
+ const help = helpText(node)
+ if (help) {
+ command.addHelpText('after', help)
+ }
+
+ command.action(async (...params: unknown[]) => {
+ const self = params.at(-1) as Commander
+ const globals = self.optsWithGlobals() as GlobalOptions
+ const options = self.opts()
+ // 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()) {
+ const value = self.processedArgs[index] as string
+ args[name] = spec.stdin && value !== undefined ? await readArgument(runtime, name, value) : value
+ }
+
+ const ctx = new Context(runtime, globals, mode, COMMANDS)
+ let result: unknown
+ try {
+ result = await node.run({ args, options, ctx })
+ } catch (error) {
+ throw withScopeHint(error, node.scopes)
+ }
+
+ const render = mode.format === 'json' ? node.agent : node.human
+ if (render && !globals.raw) {
+ render({ result, out, args, options })
+ } else if (result !== undefined) {
+ out.json(result)
+ }
+ state.exitCode = node.exitCode?.(result) ?? 0
+ })
+ }
+
+ function addNode(parent: Commander, name: string, node: Command | Group | Legacy): void {
+ const command = parent.command(name).description(node.description)
+ switch (node.kind) {
+ case 'group':
+ for (const [childName, child] of Object.entries(node.commands)) {
+ addNode(command, childName, child)
+ }
+ return
+ case 'legacy':
+ // Listed in help only: run() answers a legacy command before commander parses it.
+ command.helpGroup(LEGACY_HELP_GROUP)
+ return
+ case 'command':
+ addRunnable(command, node)
+ }
+ }
+
+ const program = new Commander('hog')
+ .description('The PostHog command line')
+ .version(VERSION, '-V, --version', 'Show the version')
+ .helpOption('-h, --help', 'Show help')
+ // Listed in help only: run() turns `hog help <command...>` into `hog <command...> --help`.
+ .helpCommand('help [command...]', 'Show help for a command')
+ .configureOutput({
+ writeOut: (text) => runtime.writeStdout(text),
+ writeErr: (text) => runtime.writeStderr(text),
+ // run() prints parse errors itself, in the caller's output format.
+ outputError: () => {},
+ })
+ .exitOverride()
+ .showSuggestionAfterError(true)
+ .addHelpText('after', ROOT_HELP)
+ for (const [name, spec] of Object.entries(GLOBAL_OPTIONS)) {
+ program.addOption(toOption(name, spec))
}
- if (VERSION_FLAGS.has(first)) {
- output.stdout(pkg.version)
+ for (const [name, node] of Object.entries(COMMANDS)) {
+ addNode(program, name, node)
+ }
+ return program
+}
+
+const PRE_PARSE_OPTIONS: ParseArgsOptionsConfig = Object.fromEntries(
+ Object.entries(GLOBAL_OPTIONS).map(([name, spec]) => [
+ kebabCase(name),
+ 'short' in spec ? { type: spec.type, short: spec.short } : { type: spec.type },
+ ])
+)
+
+type Token = ReturnType<typeof parseArgs>['tokens'] extends (infer T)[] | undefined ? T : never
+
+interface PreParsed {
+ format: OutputFormat | undefined
+ tokens: Token[]
+}
+
+interface LegacyRoute {
+ legacy: Legacy
+ path: string
+ pathIndices: number[]
+ tokens: Token[]
+}
+
+// Reads the global options before commander runs, so hog knows the output format for errors
+// raised while parsing, and where the command name starts.
+function preParse(argv: readonly string[]): PreParsed {
+ const { values, tokens } = parseArgs({
+ args: [...argv],
+ options: PRE_PARSE_OPTIONS,
+ strict: false,
+ allowPositionals: true,
+ tokens: true,
+ })
+ const output = values.output
+ const format = GLOBAL_OPTIONS.output.choices.find((choice) => choice === output)
+ return { format, tokens }
+}
+
+function findLegacy(tokens: Token[]): LegacyRoute | undefined {
+ let tree: CommandTree = COMMANDS
+ const names: string[] = []
+ const pathIndices: number[] = []
+ for (const token of tokens) {
+ if (token.kind !== 'positional') {
+ continue
+ }
+ const node: CommandTree[string] | undefined = Object.hasOwn(tree, token.value) ? tree[token.value] : undefined
+ if (!node) {
+ return undefined
+ }
+ names.push(token.value)
+ pathIndices.push(token.index)
+ if (node.kind === 'legacy') {
+ return { legacy: node, path: names.join(' '), pathIndices, tokens }
+ }
+ if (node.kind === 'command') {
+ return undefined
+ }
+ tree = node.commands
+ }
+ return undefined
+}
+
+function toHogError(caught: unknown): HogError {
+ if (caught instanceof HogError) {
+ return caught
+ }
+ if (caught instanceof CommanderError) {
+ const message = caught.message.replace(/^error: /, '')
+ const sentence = message.charAt(0).toUpperCase() + message.slice(1)
+ if (caught.code === 'commander.unknownCommand') {
+ return new HogError(
+ 'unknown_command',
+ sentence,
+ 'Run `hog --help` to see the available commands.',
+ EXIT_USAGE
+ )
+ }
+ return new HogError('usage_error', sentence, 'Run the command with --help to see its usage.', EXIT_USAGE)
+ }
+ return new HogError('internal_error', caught instanceof Error ? caught.message : String(caught))
+}
+
+export async function run(argv: readonly string[], runtime: Runtime): Promise<number> {
+ const { format, 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 program = createProgram(runtime, mode, state)
+ if (argv.length === 0) {
+ program.outputHelp()
return 0
}
+ const commandIndex = tokens.find((token) => token.kind === 'positional')?.index
+ const isHelp = commandIndex !== undefined && argv[commandIndex] === 'help'
+ const args = isHelp ? [...argv.slice(0, commandIndex), ...argv.slice(commandIndex + 1), '--help'] : [...argv]
- // `hog help <command>` asks for that command's own help, which only posthog-cli has today.
- const name = first === 'help' && helpTarget !== undefined ? helpTarget : first
- const args = first === 'help' && helpTarget !== undefined ? [...helpRest, '--help'] : rest
- const command = COMMANDS.find((candidate) => candidate.name === name)
- if (!command) {
- output.stderr(`Unknown command: ${name}. Run \`hog --help\` to see the available commands.`)
- return 1
+ try {
+ const legacy = findLegacy(isHelp ? preParse(args).tokens : tokens)
+ if (legacy) {
+ throw notPorted(args, legacy)
+ }
+ await program.parseAsync(args, { from: 'user' })
+ return 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 legacyInvocation = [command.legacyCommand, ...args.map(shellQuote)].join(' ')
- output.stderr(`\`hog ${command.name}\` isn't available yet. Run this instead:\n ${legacyInvocation}`)
- return 1
}
diff --git a/hog/src/commands.ts b/hog/src/commands.ts
deleted file mode 100644
index 77a26269bcad..000000000000
--- a/hog/src/commands.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-export interface CommandSpec {
- name: string
- summary: string
- // The posthog-cli invocation that covers this command until hog implements it.
- legacyCommand: string
-}
-
-export const COMMANDS: readonly CommandSpec[] = [
- {
- name: 'login',
- summary: 'Log in to PostHog and store a personal API key on this machine',
- legacyCommand: 'posthog-cli login',
- },
- { name: 'api', summary: 'Agent-first PostHog API tools', legacyCommand: 'posthog-cli api' },
- { name: 'query', summary: 'Run and check SQL queries', legacyCommand: 'posthog-cli exp query' },
- { name: 'endpoints', summary: 'Manage PostHog endpoints', legacyCommand: 'posthog-cli exp endpoints' },
- {
- name: 'logs',
- summary: 'Import historical logs from another log store into PostHog',
- legacyCommand: 'posthog-cli exp logs',
- },
- { name: 'tasks', summary: 'List, track and update PostHog tasks', legacyCommand: 'posthog-cli exp task' },
- {
- name: 'schema',
- summary: 'Download event definitions and generate a typed SDK',
- legacyCommand: 'posthog-cli exp schema',
- },
- {
- name: 'sourcemap',
- summary: 'Inject chunk IDs into bundles and upload their sourcemaps',
- legacyCommand: 'posthog-cli sourcemap',
- },
- { name: 'hermes', summary: 'Upload Hermes sourcemaps to PostHog', legacyCommand: 'posthog-cli hermes' },
- { name: 'dsym', summary: 'Upload Apple dSYM debug symbol files to PostHog', legacyCommand: 'posthog-cli dsym' },
- { name: 'proguard', summary: 'Upload ProGuard mapping files to PostHog', legacyCommand: 'posthog-cli proguard' },
- {
- name: 'symbol-sets',
- summary: 'Upload, download, and manage symbol sets',
- legacyCommand: 'posthog-cli symbol-sets',
- },
- { name: 'release', summary: 'Look up the release a build belongs to', legacyCommand: 'posthog-cli release' },
- { name: 'update', summary: 'Update hog to the latest version', legacyCommand: 'posthog-cli update' },
-]
diff --git a/hog/src/commands/commands.ts b/hog/src/commands/commands.ts
new file mode 100644
index 000000000000..657bd2bfbbef
--- /dev/null
+++ b/hog/src/commands/commands.ts
@@ -0,0 +1,26 @@
+import { defineCommand } from '@/core/command'
+import { describeCommands, describeGlobalOptions } from '@/core/manifest'
+import { VERSION } from '@/version'
+
+export default defineCommand({
+ description: 'List every command, for agents and scripts',
+ notes: 'Agents can learn the whole CLI from one call: every command, its arguments, options and scopes.',
+ examples: ['hog commands -o json'],
+
+ run: ({ ctx }) => ({
+ cli: 'hog',
+ version: VERSION,
+ agent: ctx.mode.agent ?? null,
+ agentReason: ctx.mode.agentReason,
+ globalOptions: describeGlobalOptions(),
+ commands: describeCommands(ctx.tree),
+ }),
+
+ human({ result, out }) {
+ const width = Math.max(...result.commands.map((entry) => entry.name.length)) + 2
+ for (const entry of result.commands) {
+ const use = entry.use ? out.style(` (use ${entry.use})`, 'dim') : ''
+ out.line(` ${entry.name.padEnd(width)}${entry.description}${use}`)
+ }
+ },
+})
diff --git a/hog/src/commands/index.ts b/hog/src/commands/index.ts
new file mode 100644
index 000000000000..c6e0ec3a19ec
--- /dev/null
+++ b/hog/src/commands/index.ts
@@ -0,0 +1,11 @@
+import query from '@/commands/query'
+import type { CommandTree } from '@/core/command'
+
+import commands from './commands'
+import { LEGACY_COMMANDS } from './legacy'
+
+export const COMMANDS: CommandTree = {
+ query,
+ commands,
+ ...LEGACY_COMMANDS,
+}
diff --git a/hog/src/commands/legacy.ts b/hog/src/commands/legacy.ts
new file mode 100644
index 000000000000..61bae4ed288c
--- /dev/null
+++ b/hog/src/commands/legacy.ts
@@ -0,0 +1,32 @@
+import { defineLegacy, type CommandTree } from '@/core/command'
+
+export const LEGACY_COMMANDS: CommandTree = {
+ login: defineLegacy({
+ description: 'Log in to PostHog and store a personal API key on this machine',
+ use: 'posthog-cli login',
+ }),
+ api: defineLegacy({ description: 'Agent-first PostHog API tools', use: 'posthog-cli api' }),
+ endpoints: defineLegacy({ description: 'Manage PostHog endpoints', use: 'posthog-cli exp endpoints' }),
+ logs: defineLegacy({
+ description: 'Import historical logs from another log store into PostHog',
+ use: 'posthog-cli exp logs',
+ }),
+ tasks: defineLegacy({ description: 'List, track and update PostHog tasks', use: 'posthog-cli exp task' }),
+ schema: defineLegacy({
+ description: 'Download event definitions and generate a typed SDK',
+ use: 'posthog-cli exp schema',
+ }),
+ sourcemap: defineLegacy({
+ description: 'Inject chunk IDs into bundles and upload their sourcemaps',
+ use: 'posthog-cli sourcemap',
+ }),
+ hermes: defineLegacy({ description: 'Upload Hermes sourcemaps to PostHog', use: 'posthog-cli hermes' }),
+ dsym: defineLegacy({ description: 'Upload Apple dSYM debug symbol files to PostHog', use: 'posthog-cli dsym' }),
+ proguard: defineLegacy({ description: 'Upload ProGuard mapping files to PostHog', use: 'posthog-cli proguard' }),
+ 'symbol-sets': defineLegacy({
+ description: 'Upload, download, and manage symbol sets',
+ use: 'posthog-cli symbol-sets',
+ }),
+ release: defineLegacy({ description: 'Look up the release a build belongs to', use: 'posthog-cli release' }),
+ update: defineLegacy({ description: 'Update hog to the latest version', use: 'posthog-cli update' }),
+}
diff --git a/hog/src/commands/query/check.ts b/hog/src/commands/query/check.ts
new file mode 100644
index 000000000000..7b65aa79c319
--- /dev/null
+++ b/hog/src/commands/query/check.ts
@@ -0,0 +1,34 @@
+import { defineCommand } from '@/core/command'
+import { printDiagnostics, type Diagnostics } from '@/core/diagnostics'
+
+interface MetadataResponse extends Diagnostics {
+ isValid?: boolean | null
+}
+
+export default defineCommand({
+ description: 'Check the syntax and types of a HogQL query without running it',
+ args: {
+ query: { description: 'The HogQL query to check, or - to read it from stdin', stdin: true },
+ },
+ scopes: ['query:read'],
+ notes: 'Exits with code 1 when the query has errors, so scripts and agents can branch on it.',
+ examples: ['hog query check "select event from events"'],
+
+ async run({ args, ctx }) {
+ const api = await ctx.posthog()
+ const response = await api.post<MetadataResponse>('query', {
+ query: { kind: 'HogQLMetadata', language: 'hogQL', query: args.query },
+ })
+ return { query: args.query, response }
+ },
+
+ human({ result, out }) {
+ printDiagnostics(out, result.query, result.response)
+ },
+
+ agent({ result, out }) {
+ out.json(result.response)
+ },
+
+ exitCode: ({ response }) => ((response.errors ?? []).length > 0 ? 1 : 0),
+})
diff --git a/hog/src/commands/query/index.ts b/hog/src/commands/query/index.ts
new file mode 100644
index 000000000000..ecf809be040b
--- /dev/null
+++ b/hog/src/commands/query/index.ts
@@ -0,0 +1,13 @@
+import { defineGroup, defineLegacy } from '@/core/command'
+
+import check from './check'
+import run from './run'
+
+export default defineGroup({
+ description: 'Run and check HogQL queries against your project',
+ commands: {
+ run,
+ check,
+ editor: defineLegacy({ description: 'Open the interactive query editor', use: 'posthog-cli exp query editor' }),
+ },
+})
diff --git a/hog/src/commands/query/query.test.ts b/hog/src/commands/query/query.test.ts
new file mode 100644
index 000000000000..58f60a32b654
--- /dev/null
+++ b/hog/src/commands/query/query.test.ts
@@ -0,0 +1,211 @@
+import { describe, expect, test } from 'bun:test'
+import { styleText } from 'node:util'
+
+import { runHog, TEST_CREDENTIALS } from '@/testing'
+
+const ROWS = {
+ columns: ['event', 'total'],
+ results: [
+ ['$pageview', 70],
+ ['signup', null],
+ ],
+ hasMore: false,
+}
+
+describe('hog query', () => {
+ test.each([
+ ['a pipe gets one JSON array per row', false, [], '["$pageview",70]\n["signup",null]\n'],
+ [
+ 'a terminal gets a table with numbers on the right',
+ true,
+ [],
+ '│ $pageview │ 70 │\n│ signup │ null │\n└───────────┴───────┘\n2 rows\n',
+ ],
+ [
+ '--raw prints the full response',
+ false,
+ ['--raw'],
+ '{"columns":["event","total"],"hasMore":false,"results":[["$pageview",70],["signup",null]]}\n',
+ ],
+ ])('run: %s', async (_name, tty, flags, expected) => {
+ const result = await runHog(['query', 'run', 'select 1', ...flags], {
+ env: TEST_CREDENTIALS,
+ stdoutIsTTY: tty,
+ respond: () => ({ status: 200, body: ROWS }),
+ })
+ expect(result.exitCode).toBe(0)
+ expect(result.stdout).toEndWith(expected)
+ expect(result.requests).toEqual([
+ {
+ method: 'POST',
+ url: 'https://ph.example.com/api/environments/7/query',
+ body: { query: { kind: 'HogQLQuery', query: 'select 1' }, refresh: 'blocking' },
+ },
+ ])
+ })
+
+ test.each([
+ [
+ 'a pipe keeps integers beyond the safe range exact',
+ false,
+ '{"columns":["n"],"results":[[18446744073709551615, 1.5]]}',
+ '[18446744073709551615,1.5]\n',
+ ],
+ [
+ 'a table keeps integers beyond the safe range exact',
+ true,
+ '{"columns":["n"],"results":[[18446744073709551615]]}',
+ '│ 18446744073709551615 │',
+ ],
+ [
+ 'a table escapes terminal control characters in cells and headers',
+ true,
+ { columns: ['a\u001b[2J'], results: [['\u001b]52;c;eA==\u0007']] },
+ '│ \\x1b]52;c;eA==\\x07 │',
+ ],
+ ])('run: %s', async (_name, tty, body, expected) => {
+ const result = await runHog(['query', 'run', 'select 1'], {
+ env: TEST_CREDENTIALS,
+ stdoutIsTTY: tty,
+ respond: () => ({ status: 200, body }),
+ })
+ expect(result.stdout).toContain(expected)
+ expect(result.stdout).not.toContain('\u001b')
+ })
+
+ const tenColumns = Array.from({ length: 10 }, (_, index) => `column_${index}`)
+ test.each([
+ [
+ 'a long value',
+ 40,
+ { columns: ['event', 'properties'], results: [['$pageview', 'x'.repeat(200)]] },
+ '│ $pageview │ xxx',
+ ],
+ [
+ 'more columns than fit at the minimum width',
+ 80,
+ { columns: tenColumns, results: [tenColumns.map((name) => `${name}_value`)] },
+ '│ c',
+ ],
+ ])('run fits the table to a narrow terminal: %s', async (_name, columns, body, expected) => {
+ const result = await runHog(['query', 'run', 'select 1'], {
+ env: TEST_CREDENTIALS,
+ stdoutIsTTY: true,
+ columns,
+ respond: () => ({ status: 200, body }),
+ })
+ const widths = result.stdout
+ .trimEnd()
+ .split('\n')
+ .map((line) => Bun.stringWidth(line))
+ expect(Math.max(...widths)).toBeLessThanOrEqual(columns)
+ expect(result.stdout).toContain(expected)
+ })
+
+ test('run colors values by their ClickHouse type', async () => {
+ const typed = {
+ columns: ['day', 'total'],
+ types: [
+ ['day', 'Nullable(DateTime64(6))'],
+ ['total', 'UInt64'],
+ ],
+ results: [['2026-10-27 00:00:00', 70]],
+ }
+ const result = await runHog(['query', 'run', 'select 1'], {
+ env: { ...TEST_CREDENTIALS, NO_COLOR: undefined },
+ stdoutIsTTY: true,
+ respond: () => ({ status: 200, body: typed }),
+ })
+ expect(result.stdout).toContain(styleText('magenta', '2026-10-27 00:00:00', { validateStream: false }))
+ expect(result.stdout).toContain(styleText('cyan', '70', { validateStream: false }))
+ })
+
+ test('run reads the query from stdin when it is -', async () => {
+ const result = await runHog(['query', 'run', '-'], {
+ env: TEST_CREDENTIALS,
+ stdin: 'select 2',
+ respond: () => ({ status: 200, body: ROWS }),
+ })
+ expect(result.exitCode).toBe(0)
+ expect(result.requests[0]?.body).toMatchObject({ query: { query: 'select 2' } })
+ })
+
+ test.each([
+ [
+ 'a validation error points to query check',
+ 400,
+ { type: 'validation_error', code: 'hogql_query_error', detail: 'Unable to resolve field: nope' },
+ {
+ code: 'hogql_query_error',
+ message: 'Unable to resolve field: nope',
+ hint: expect.stringContaining('hog query check'),
+ },
+ ],
+ [
+ 'a 403 names the scope the command needs',
+ 403,
+ { type: 'authentication_error', code: 'permission_denied', detail: 'No access' },
+ { code: 'permission_denied', hint: expect.stringContaining('query:read') },
+ ],
+ ])('run: %s', async (_name, status, body, error) => {
+ const result = await runHog(['query', 'run', 'select nope from events'], {
+ env: TEST_CREDENTIALS,
+ respond: () => ({ status, body }),
+ })
+ expect(result.exitCode).toBe(1)
+ expect(result.error()).toMatchObject(error)
+ })
+
+ test.each([
+ [
+ 'a valid query exits 0',
+ 'select from',
+ { isValid: true, errors: [], warnings: [], notices: [] },
+ 0,
+ 'Query is valid',
+ ],
+ [
+ 'a query with errors exits 1 and points at the error',
+ 'select from',
+ { isValid: false, errors: [{ message: 'expected ), got Ident', start: 7, end: 11 }] },
+ 1,
+ ' 1 | select from\n ^^^^',
+ ],
+ [
+ 'offsets count code points, so an emoji earlier on does not shift the error',
+ "select '😀',\nnope",
+ { isValid: false, errors: [{ message: 'Unable to resolve field: nope', start: 12, end: 16 }] },
+ 1,
+ ' 2 | nope\n ^^^^',
+ ],
+ [
+ 'an error at the very start of a multiline query points at line 1',
+ 'nope\nselect 1',
+ { isValid: false, errors: [{ message: 'Unable to resolve field: nope', start: 0, end: 4 }] },
+ 1,
+ ' --> line 1, column 1\n 1 | nope\n ^^^^',
+ ],
+ [
+ 'a diagnostic without a location prints no source line',
+ 'select 1',
+ { isValid: false, errors: [{ message: 'Query is too complex', start: null, end: null }] },
+ 1,
+ 'error: Query is too complex\n1 error',
+ ],
+ [
+ 'terminal escapes in the source and the message are printed escaped',
+ 'select \u001b]52;c;eA==\u0007',
+ { isValid: false, errors: [{ message: 'bad \u001b[2J', start: 7, end: 8 }] },
+ 1,
+ 'error: bad \\x1b[2J\n --> line 1, column 8\n 1 | select \\x1b]52;c;eA==\\x07\n ^^^^',
+ ],
+ ])('check: %s', async (_name, query, body, exitCode, expected) => {
+ const result = await runHog(['query', 'check', query, '-o', 'text'], {
+ env: TEST_CREDENTIALS,
+ stdoutIsTTY: true,
+ respond: () => ({ status: 200, body }),
+ })
+ expect(result.exitCode).toBe(exitCode)
+ expect(result.stdout).toContain(expected)
+ })
+})
diff --git a/hog/src/commands/query/run.ts b/hog/src/commands/query/run.ts
new file mode 100644
index 000000000000..4d101b7666e5
--- /dev/null
+++ b/hog/src/commands/query/run.ts
@@ -0,0 +1,67 @@
+import { defineCommand } from '@/core/command'
+import type { ColumnKind } from '@/core/output'
+import { plural } from '@/core/text'
+import { ApiError } from '@/posthog/api'
+
+interface QueryResponse {
+ columns?: string[] | null
+ results?: unknown[][] | null
+ types?: [string, string][] | null
+ hasMore?: boolean | null
+}
+
+// ClickHouse returns 64-bit integers as JSON numbers and dates as strings, so the declared type
+// colors a column better than its values do.
+function kindOf(clickhouseType: string | undefined): ColumnKind | undefined {
+ // Only the prefix matters, so wrappers like LowCardinality(Nullable(String)) drop their opening half.
+ const base = clickhouseType?.replace(/^((Nullable|LowCardinality)\()+/, '')
+ if (!base) {
+ return undefined
+ }
+ const kinds: [RegExp, ColumnKind][] = [
+ [/^(U?Int|Float|Decimal)/, 'number'],
+ [/^Date/, 'date'],
+ [/^Bool/, 'boolean'],
+ [/^(Array|Map|Tuple|JSON|Object)/, 'json'],
+ ]
+ return kinds.find(([pattern]) => pattern.test(base))?.[1] ?? 'string'
+}
+
+export default defineCommand({
+ description: 'Run a HogQL query and print the results',
+ args: {
+ query: { description: 'The HogQL query to run, or - to read it from stdin', stdin: true },
+ },
+ scopes: ['query:read'],
+ notes: 'Prints a table in a terminal, and one JSON array per row for agents and pipes. --raw prints the full response.',
+ examples: ['hog query run "select event, count() from events group by event"', 'cat query.sql | hog query run -'],
+
+ async run({ args, ctx }) {
+ const api = await ctx.posthog()
+ try {
+ return await api.post<QueryResponse>('query', {
+ query: { kind: 'HogQLQuery', query: args.query },
+ refresh: 'blocking',
+ })
+ } catch (error) {
+ if (error instanceof ApiError && error.type === 'validation_error') {
+ throw error.withHint('Run `hog query check` on the query to see where it fails.')
+ }
+ throw error
+ }
+ },
+
+ human({ result, out }) {
+ const rows = result.results ?? []
+ out.table(
+ (result.columns ?? []).map((name, index) => ({ name, kind: kindOf(result.types?.[index]?.[1]) })),
+ rows
+ )
+ const count = plural(rows.length, 'row')
+ out.line(out.style(result.hasMore ? `${count}, more available` : count, 'dim'))
+ },
+
+ agent({ result, out }) {
+ out.jsonLines(result.results ?? [])
+ },
+})
diff --git a/hog/src/core/agent.test.ts b/hog/src/core/agent.test.ts
new file mode 100644
index 000000000000..b917cc6a68d1
--- /dev/null
+++ b/hog/src/core/agent.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, test } from 'bun:test'
+
+import { resolveMode, type OutputFormat, type Terminal } from './agent'
+
+const TERMINALS: Record<string, Terminal> = {
+ tty: { isTTY: true, hasColors: true, columns: 80 },
+ pipe: { isTTY: false, hasColors: false, columns: undefined },
+ dumb: { isTTY: true, hasColors: false, columns: 80 },
+}
+
+describe('resolveMode', () => {
+ test.each([
+ ['a person at a terminal gets text with color', {}, 'tty', undefined, undefined, 'text', true],
+ ['a pipe gets json', {}, 'pipe', undefined, undefined, 'json', false],
+ ['Claude Code gets json without color', { CLAUDECODE: '1' }, 'tty', undefined, 'claude-code', 'json', false],
+ [
+ 'Codex is detected by its sandbox variable',
+ { CODEX_SANDBOX: 'seatbelt' },
+ 'tty',
+ undefined,
+ 'codex',
+ 'json',
+ false,
+ ],
+ ['AI_AGENT names the agent', { AI_AGENT: 'v0' }, 'tty', undefined, 'v0', 'json', false],
+ [
+ 'HOG_AGENT=0 overrides detection',
+ { CLAUDECODE: '1', HOG_AGENT: '0' },
+ 'tty',
+ undefined,
+ undefined,
+ 'text',
+ true,
+ ],
+ ['HOG_AGENT=1 forces agent mode', { HOG_AGENT: '1' }, 'tty', undefined, 'unknown', 'json', false],
+ [
+ "Cursor's own terminal is not an agent",
+ { CURSOR_TRACE_ID: 'abc' },
+ 'tty',
+ undefined,
+ undefined,
+ 'text',
+ true,
+ ],
+ ['--output json wins at a terminal', {}, 'tty', 'json', undefined, 'json', false],
+ [
+ '--output text for an agent stays uncolored',
+ { CLAUDECODE: '1' },
+ 'tty',
+ 'text',
+ 'claude-code',
+ 'text',
+ false,
+ ],
+ ['NO_COLOR turns color off', { NO_COLOR: '1' }, 'tty', undefined, undefined, 'text', false],
+ [
+ 'a terminal without color support, like TERM=dumb, gets plain text',
+ {},
+ 'dumb',
+ undefined,
+ undefined,
+ 'text',
+ false,
+ ],
+ ] as const)('%s', (_name, env, terminal, requested, agent, format, color) => {
+ const mode = resolveMode(env, TERMINALS[terminal]!, requested as OutputFormat | undefined)
+ expect(mode).toMatchObject({ agent, format, color })
+ })
+})
diff --git a/hog/src/core/agent.ts b/hog/src/core/agent.ts
new file mode 100644
index 000000000000..e16f4faed9e2
--- /dev/null
+++ b/hog/src/core/agent.ts
@@ -0,0 +1,77 @@
+import type { Env } from './runtime'
+
+// Env vars that coding agents set for the commands they run, checked in order.
+// Sources: the env vars @vercel/detect-agent and the Gauge CLI check. CURSOR_TRACE_ID and
+// REPL_ID are left out on purpose, because people also see them in Cursor's and Replit's
+// own terminals.
+const AGENT_ENV_MARKERS: ReadonlyArray<readonly [envVar: string, agent: string]> = [
+ ['CLAUDECODE', 'claude-code'],
+ ['CLAUDE_CODE', 'claude-code'],
+ ['CODEX_SANDBOX', 'codex'],
+ ['CODEX_CI', 'codex'],
+ ['CODEX_THREAD_ID', 'codex'],
+ ['CURSOR_AGENT', 'cursor'],
+ ['GEMINI_CLI', 'gemini-cli'],
+ ['CLINE_ACTIVE', 'cline'],
+ ['OPENCODE', 'opencode'],
+ ['OPENCODE_CLIENT', 'opencode'],
+ ['AUGMENT_AGENT', 'augment'],
+ ['ANTIGRAVITY_AGENT', 'antigravity'],
+ ['COPILOT_MODEL', 'github-copilot'],
+ ['COPILOT_ALLOW_ALL', 'github-copilot'],
+]
+
+const TRUE_VALUES = new Set(['1', 'true', 'yes'])
+const FALSE_VALUES = new Set(['0', 'false', 'no'])
+
+export type OutputFormat = 'text' | 'json'
+
+// Who is calling hog, and how hog prints for them.
+export interface Mode {
+ // The agent running hog, or undefined for a person or a script.
+ agent: string | undefined
+ // Why hog decided the caller is or isn't an agent. `hog commands` reports it.
+ agentReason: string
+ format: OutputFormat
+ color: boolean
+ columns: number | undefined
+}
+
+export interface Terminal {
+ isTTY: boolean
+ hasColors: boolean
+ columns: number | undefined
+}
+
+function detectAgent(env: Env): { agent: string | undefined; reason: string } {
+ const override = env.HOG_AGENT?.trim().toLowerCase()
+ if (override !== undefined && FALSE_VALUES.has(override)) {
+ return { agent: undefined, reason: 'HOG_AGENT disables agent detection' }
+ }
+ if (override !== undefined && TRUE_VALUES.has(override)) {
+ return { agent: 'unknown', reason: 'HOG_AGENT forces agent mode' }
+ }
+
+ // AI_AGENT is the generic convention: its value names the agent.
+ const generic = env.AI_AGENT?.trim()
+ if (generic) {
+ return { agent: generic, reason: 'AI_AGENT is set' }
+ }
+
+ for (const [envVar, agent] of AGENT_ENV_MARKERS) {
+ if (env[envVar]) {
+ return { agent, reason: `${envVar} is set` }
+ }
+ }
+ return { agent: undefined, reason: 'no agent env var is set' }
+}
+
+export function resolveMode(env: Env, terminal: Terminal, requestedFormat: OutputFormat | undefined): Mode {
+ const { agent, reason } = detectAgent(env)
+ // Agents and pipes get JSON by default, people at a terminal get text.
+ const format = requestedFormat ?? (agent !== undefined || !terminal.isTTY ? 'json' : 'text')
+ const colorForced = env.FORCE_COLOR !== undefined && env.FORCE_COLOR !== '0'
+ const color =
+ colorForced || (format === 'text' && terminal.hasColors && agent === undefined && env.NO_COLOR === undefined)
+ return { agent, agentReason: reason, format, color, columns: terminal.columns }
+}
diff --git a/hog/src/core/command.ts b/hog/src/core/command.ts
new file mode 100644
index 000000000000..c3ac5845d943
--- /dev/null
+++ b/hog/src/core/command.ts
@@ -0,0 +1,111 @@
+import type { Context } from './context'
+import type { Output } from './output'
+import { kebabCase } from './text'
+
+export interface ArgumentSpec {
+ description: string
+ optional?: boolean
+ // `-` reads the value from stdin, and an empty value is an error.
+ stdin?: boolean
+}
+
+export type OptionSpec =
+ | { type: 'boolean'; description: string; short?: string }
+ | {
+ type: 'string'
+ description: string
+ short?: string
+ // The name shown in help, as in `--host <url>`. Defaults to the option name.
+ placeholder?: string
+ choices?: readonly string[]
+ }
+
+type ArgumentValues<Args> = {
+ [Name in keyof Args]: Args[Name] extends { optional: true } ? string | undefined : string
+}
+
+export type OptionValues<Options> = {
+ [Name in keyof Options]: Options[Name] extends { type: 'boolean' }
+ ? boolean | undefined
+ : (Options[Name] extends { choices: readonly (infer Choice)[] } ? Choice : string) | undefined
+}
+
+interface CommandInput<Args, Options> {
+ args: ArgumentValues<Args>
+ options: OptionValues<Options>
+}
+
+interface RenderInput<Args, Options, Result> extends CommandInput<Args, Options> {
+ result: Result
+ out: Output
+}
+
+interface CommandDefinition<Args, Options, Result> {
+ description: string
+ args?: Args
+ // The key becomes the flag: `dotenvFile` is `--dotenv-file`.
+ options?: Options
+ // Personal API key scopes the command needs. `hog commands` lists them, and a 403 names them.
+ scopes?: readonly string[]
+ notes?: string
+ examples?: readonly string[]
+ // Does the work and returns data. It never prints: `human` and `agent` decide how the data
+ // looks. Import heavy dependencies here with `await import()`, so other commands don't load them.
+ run(input: CommandInput<Args, Options> & { ctx: Context }): Promise<Result> | Result
+ // What a person at a terminal sees. Defaults to the result as indented JSON.
+ human?(input: RenderInput<Args, Options, Result>): void
+ // What agents, pipes and `-o json` see. Defaults to the result as one line of JSON.
+ agent?(input: RenderInput<Args, Options, Result>): void
+ // The exit code for a result. Defaults to 0. Failures throw a HogError instead.
+ exitCode?(result: Result): number
+}
+
+// Methods, not function properties, so a command with specific arguments still fits `Command`.
+export interface Command<
+ Args extends Record<string, ArgumentSpec> = Record<string, ArgumentSpec>,
+ Options extends Record<string, OptionSpec> = Record<string, OptionSpec>,
+ Result = unknown,
+> extends CommandDefinition<Args, Options, Result> {
+ kind: 'command'
+}
+
+export interface Group {
+ kind: 'group'
+ description: string
+ commands: CommandTree
+}
+
+// A command posthog-cli still owns. hog lists it and points the caller to `use`, with the same arguments.
+export interface Legacy {
+ kind: 'legacy'
+ description: string
+ use: string
+}
+
+export type CommandTree = Readonly<Record<string, Command | Group | Legacy>>
+
+export function defineCommand<
+ const Args extends Record<string, ArgumentSpec> = {},
+ const Options extends Record<string, OptionSpec> = {},
+ Result = void,
+>(definition: CommandDefinition<Args, Options, Result>): Command<Args, Options, Result> {
+ return { kind: 'command', ...definition }
+}
+
+export function defineGroup(definition: Omit<Group, 'kind'>): Group {
+ return { kind: 'group', ...definition }
+}
+
+export function defineLegacy(definition: Omit<Legacy, 'kind'>): Legacy {
+ return { kind: 'legacy', ...definition }
+}
+
+export function optionFlags(name: string, spec: OptionSpec): string {
+ const long = `--${kebabCase(name)}`
+ const flag = spec.type === 'string' ? `${long} <${spec.placeholder ?? kebabCase(name)}>` : long
+ return spec.short ? `-${spec.short}, ${flag}` : flag
+}
+
+export function argumentSyntax(name: string, spec: ArgumentSpec): string {
+ return spec.optional ? `[${kebabCase(name)}]` : `<${kebabCase(name)}>`
+}
diff --git a/hog/src/core/context.ts b/hog/src/core/context.ts
new file mode 100644
index 000000000000..ab1f52953af1
--- /dev/null
+++ b/hog/src/core/context.ts
@@ -0,0 +1,55 @@
+import { PostHogApi } from '@/posthog/api'
+import { resolveCredentials } from '@/posthog/credentials'
+
+import type { Mode } from './agent'
+import type { CommandTree, OptionSpec, OptionValues } from './command'
+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 {
+ private api?: PostHogApi
+
+ constructor(
+ readonly runtime: Runtime,
+ readonly globals: GlobalOptions,
+ readonly mode: Mode,
+ readonly tree: CommandTree
+ ) {}
+
+ // The PostHog API client. Credentials resolve on first use, so commands that never call
+ // the API work without them.
+ async posthog(): Promise<PostHogApi> {
+ if (!this.api) {
+ const credentials = await resolveCredentials(this.runtime, this.globals)
+ this.api = new PostHogApi(credentials, this.runtime.fetch)
+ }
+ return this.api
+ }
+}
diff --git a/hog/src/core/diagnostics.ts b/hog/src/core/diagnostics.ts
new file mode 100644
index 000000000000..8137b3c819ca
--- /dev/null
+++ b/hog/src/core/diagnostics.ts
@@ -0,0 +1,71 @@
+import { escapeControls, type Output, type Style } from './output'
+import { plural } from './text'
+
+// One problem the server found in a piece of source text. The offsets count Unicode code points,
+// as Python strings do, and are null when the problem has no location.
+export interface Diagnostic {
+ message: string
+ start?: number | null
+ end?: number | null
+}
+
+export interface Diagnostics {
+ errors?: Diagnostic[] | null
+ warnings?: Diagnostic[] | null
+ notices?: Diagnostic[] | null
+}
+
+export function printDiagnostics(out: Output, source: string, diagnostics: Diagnostics): void {
+ const groups: { label: string; style: Style; items: Diagnostic[] }[] = [
+ { label: 'error', style: 'red', items: diagnostics.errors ?? [] },
+ { label: 'warning', style: 'yellow', items: diagnostics.warnings ?? [] },
+ { label: 'notice', style: 'cyan', items: diagnostics.notices ?? [] },
+ ]
+ const chars = Array.from(source)
+ for (const group of groups) {
+ for (const item of group.items) {
+ out.line(`${out.style(group.label, group.style, 'bold')}: ${escapeControls(item.message)}`)
+ if (item.start == null) {
+ continue
+ }
+ const { line, column, before, marked, after } = locate(chars, item.start, item.end ?? item.start + 1)
+ const gutter = `${line} | `
+ out.line(out.style(` --> line ${line}, column ${column}`, 'dim'))
+ out.line(` ${out.style(gutter, 'dim')}${printable(before + marked + after)}`)
+ const pad = ' '.repeat(gutter.length + Bun.stringWidth(printable(before)))
+ out.line(` ${pad}${out.style('^'.repeat(Math.max(1, Bun.stringWidth(printable(marked)))), group.style)}`)
+ }
+ }
+ const errors = diagnostics.errors?.length ?? 0
+ const summary = groups.map((group) => plural(group.items.length, group.label)).join(', ')
+ out.line(errors === 0 ? out.style(`Query is valid (${summary})`, 'green') : out.style(summary, 'red'))
+}
+
+// Tabs become spaces so the caret line stays aligned with the source line.
+function printable(text: string): string {
+ return escapeControls(text.replaceAll('\t', ' '))
+}
+
+function locate(
+ chars: string[],
+ start: number,
+ end: number
+): { line: number; column: number; before: string; marked: string; after: string } {
+ const offset = Math.min(Math.max(start, 0), chars.length)
+ // Unlike a string's, an array's lastIndexOf reads -1 as the last index.
+ const lineStart = offset === 0 ? 0 : chars.lastIndexOf('\n', offset - 1) + 1
+ const newline = chars.indexOf('\n', offset)
+ const lineEnd = newline === -1 ? chars.length : newline
+ const markEnd = Math.min(Math.max(end, offset), lineEnd)
+ let line = 1
+ for (let index = 0; index < lineStart; index++) {
+ line += chars[index] === '\n' ? 1 : 0
+ }
+ return {
+ line,
+ column: offset - lineStart + 1,
+ before: chars.slice(lineStart, offset).join(''),
+ marked: chars.slice(offset, markEnd).join(''),
+ after: chars.slice(markEnd, lineEnd).join(''),
+ }
+}
diff --git a/hog/src/core/errors.ts b/hog/src/core/errors.ts
new file mode 100644
index 000000000000..3cba8b4df60b
--- /dev/null
+++ b/hog/src/core/errors.ts
@@ -0,0 +1,20 @@
+export const EXIT_FAILURE = 1
+export const EXIT_USAGE = 2
+
+// A failure hog reports to the caller. `code` is stable and machine-readable, so agents and
+// scripts can branch on it; `message` and `hint` are for people.
+export class HogError extends Error {
+ constructor(
+ readonly code: string,
+ message: string,
+ readonly hint?: string,
+ readonly exitCode = EXIT_FAILURE
+ ) {
+ super(message)
+ this.name = 'HogError'
+ }
+
+ withHint(hint: string): HogError {
+ return new HogError(this.code, this.message, hint, this.exitCode)
+ }
+}
diff --git a/hog/src/core/manifest.ts b/hog/src/core/manifest.ts
new file mode 100644
index 000000000000..f05d17d94c21
--- /dev/null
+++ b/hog/src/core/manifest.ts
@@ -0,0 +1,64 @@
+import { optionFlags, type CommandTree, type OptionSpec } from './command'
+import { GLOBAL_OPTIONS } from './context'
+import { kebabCase } from './text'
+
+interface OptionEntry {
+ flags: string
+ description: string
+ takesValue: boolean
+ choices?: readonly string[]
+}
+
+export interface ManifestEntry {
+ name: string
+ description: string
+ available: boolean
+ arguments?: { name: string; description: string; required: boolean; stdin: boolean }[]
+ options?: OptionEntry[]
+ scopes?: readonly string[]
+ examples?: readonly string[]
+ // The posthog-cli command to run instead, for commands hog doesn't have yet.
+ use?: string
+}
+
+function describeOptions(options: Readonly<Record<string, OptionSpec>>): OptionEntry[] {
+ return Object.entries(options).map(([name, spec]) => ({
+ flags: optionFlags(name, spec),
+ description: spec.description,
+ takesValue: spec.type === 'string',
+ choices: spec.type === 'string' ? spec.choices : undefined,
+ }))
+}
+
+export function describeCommands(tree: CommandTree, prefix = ''): ManifestEntry[] {
+ return Object.entries(tree).flatMap(([name, node]): ManifestEntry[] => {
+ const path = prefix ? `${prefix} ${name}` : name
+ switch (node.kind) {
+ case 'group':
+ return describeCommands(node.commands, path)
+ case 'legacy':
+ return [{ name: path, description: node.description, available: false, use: node.use }]
+ case 'command':
+ return [
+ {
+ name: path,
+ description: node.description,
+ available: true,
+ arguments: Object.entries(node.args ?? {}).map(([argName, spec]) => ({
+ name: kebabCase(argName),
+ description: spec.description,
+ required: spec.optional !== true,
+ stdin: spec.stdin === true,
+ })),
+ options: describeOptions(node.options ?? {}),
+ scopes: node.scopes ?? [],
+ examples: node.examples ?? [],
+ },
+ ]
+ }
+ })
+}
+
+export function describeGlobalOptions(): OptionEntry[] {
+ return describeOptions(GLOBAL_OPTIONS)
+}
diff --git a/hog/src/core/output.ts b/hog/src/core/output.ts
new file mode 100644
index 000000000000..dd187b3cae00
--- /dev/null
+++ b/hog/src/core/output.ts
@@ -0,0 +1,196 @@
+import Table from 'cli-table3'
+import { styleText } from 'node:util'
+
+import type { Mode } from './agent'
+import type { HogError } from './errors'
+import type { Runtime } from './runtime'
+
+export type Style = 'bold' | 'dim' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan'
+
+export type ColumnKind = 'string' | 'number' | 'boolean' | 'date' | 'json'
+
+export interface TableColumn {
+ name: string
+ kind?: ColumnKind
+}
+
+const KIND_STYLES: Record<ColumnKind, Style[]> = {
+ string: [],
+ number: ['cyan'],
+ boolean: ['yellow'],
+ date: ['magenta'],
+ json: ['blue'],
+}
+
+const MAX_CELL_WIDTH = 48
+const MIN_CELL_WIDTH = 6
+const CELL_PADDING = 2
+// The border and padding around each cell in `│ a │ b │`: one bar per cell plus one, and a space on each side.
+const tableOverhead = (count: number): number => count * (CELL_PADDING + 1) + 1
+// C0 and C1 control characters, except tab and newline. Query results and API errors carry text
+// from event data, and a raw escape sequence there could rewrite the terminal or the clipboard.
+// oxlint-disable-next-line no-control-regex -- matching control characters is the point
+const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g
+
+export function escapeControls(text: string): string {
+ return text.replace(CONTROL, (char) => `\\x${char.charCodeAt(0).toString(16).padStart(2, '0')}`)
+}
+
+const ISO_DATE = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/
+
+export class Output {
+ constructor(
+ private readonly runtime: Runtime,
+ private readonly mode: Mode
+ ) {}
+
+ style(text: string, ...styles: Style[]): string {
+ // hog decides about color itself, so styleText must not check the stream again.
+ return this.mode.color && styles.length > 0 ? styleText(styles, text, { validateStream: false }) : text
+ }
+
+ line(text = ''): void {
+ this.runtime.writeStdout(`${text}\n`)
+ }
+
+ json(value: unknown): void {
+ const sorted = sortKeys(value)
+ this.line(this.mode.format === 'json' ? JSON.stringify(sorted) : JSON.stringify(sorted, null, 2))
+ }
+
+ // One JSON value per line, so a caller can stream and parse the lines one at a time.
+ jsonLines(values: Iterable<unknown>): void {
+ for (const value of values) {
+ this.line(JSON.stringify(sortKeys(value)))
+ }
+ }
+
+ table(columns: readonly (string | TableColumn)[], rows: readonly unknown[][]): void {
+ const named = columns.map((column) => (typeof column === 'string' ? { name: column } : column))
+ const kinds = named.map((column, index) => column.kind ?? inferKind(rows.map((row) => row[index])))
+ const cells = rows.map((row) => named.map((_, index) => cellText(row[index])))
+ const widths = fitWidths(
+ named.map((column, index) =>
+ Math.min(
+ MAX_CELL_WIDTH,
+ Math.max(Bun.stringWidth(column.name), ...cells.map((row) => Bun.stringWidth(row[index] ?? '')))
+ )
+ ),
+ this.mode.columns
+ )
+
+ const bar = this.style('│', 'dim')
+ const table = new Table({
+ head: named.map((column) => this.style(escapeControls(column.name), 'bold')),
+ colWidths: widths.map((width) => width + CELL_PADDING),
+ colAligns: kinds.map((kind) => (kind === 'number' ? 'right' : 'left')),
+ style: { head: [], border: [] },
+ // Empty row separators keep one line per row. The rule under the header goes back in below.
+ chars: { left: bar, middle: bar, right: bar, mid: '', 'left-mid': '', 'mid-mid': '', 'right-mid': '' },
+ })
+ table.push(
+ ...cells.map((row, rowIndex) =>
+ row.map((text, index) => {
+ const value = rows[rowIndex]?.[index]
+ return value == null
+ ? this.style(text, 'dim')
+ : this.style(text, ...KIND_STYLES[kinds[index] ?? 'string'])
+ })
+ )
+ )
+
+ // The top and bottom borders are whole lines, so they take one style each instead of one per character.
+ const [top = '', header = '', ...body] = table.toString().split('\n')
+ const bottom = body.pop() ?? ''
+ const rule = `├${widths.map((width) => '─'.repeat(width + CELL_PADDING)).join('┼')}┤`
+ for (const line of [
+ this.style(top, 'dim'),
+ header,
+ this.style(rule, 'dim'),
+ ...body,
+ this.style(bottom, 'dim'),
+ ]) {
+ this.line(line)
+ }
+ }
+
+ error(error: HogError): void {
+ if (this.mode.format === 'json') {
+ const payload = { error: { code: error.code, message: error.message, hint: error.hint } }
+ this.runtime.writeStderr(`${JSON.stringify(payload)}\n`)
+ return
+ }
+ this.runtime.writeStderr(`${this.style('Error:', 'red', 'bold')} ${escapeControls(error.message)}\n`)
+ if (error.hint) {
+ this.runtime.writeStderr(`${this.style(escapeControls(error.hint), 'dim')}\n`)
+ }
+ }
+}
+
+// posthog-cli prints JSON through serde_json without `preserve_order`, so object keys come
+// out sorted. Sorting here keeps hog's JSON the same for nested objects.
+function sortKeys(value: unknown): unknown {
+ // Integers too large for a JS number stay as their source text (see parseLossless).
+ if (JSON.isRawJSON(value)) {
+ return value
+ }
+ if (Array.isArray(value)) {
+ return value.map(sortKeys)
+ }
+ if (value !== null && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.keys(value)
+ .sort()
+ .map((key) => [key, sortKeys((value as Record<string, unknown>)[key])])
+ )
+ }
+ return value
+}
+
+function cellText(value: unknown): string {
+ if (value == null) {
+ return 'null'
+ }
+ const text = typeof value === 'string' ? value : JSON.stringify(sortKeys(value))
+ return escapeControls(text.replace(/\s+/g, ' '))
+}
+
+function inferKind(values: readonly unknown[]): ColumnKind {
+ const present = values.filter((value) => value != null)
+ if (present.length === 0) {
+ return 'string'
+ }
+ if (present.every((value) => typeof value === 'number' || typeof value === 'bigint' || JSON.isRawJSON(value))) {
+ return 'number'
+ }
+ if (present.every((value) => typeof value === 'boolean')) {
+ return 'boolean'
+ }
+ if (present.every((value) => typeof value === 'object')) {
+ return 'json'
+ }
+ if (present.every((value) => typeof value === 'string' && ISO_DATE.test(value))) {
+ return 'date'
+ }
+ return 'string'
+}
+
+function fitWidths(widths: readonly number[], terminalColumns: number | undefined): number[] {
+ const fitted = [...widths]
+ if (terminalColumns === undefined) {
+ return fitted
+ }
+ const budget = terminalColumns - tableOverhead(fitted.length)
+ let total = fitted.reduce((sum, width) => sum + width, 0)
+ for (const floor of [MIN_CELL_WIDTH, 1]) {
+ while (total > budget) {
+ const widest = fitted.indexOf(Math.max(...fitted))
+ if ((fitted[widest] ?? 0) <= floor) {
+ break
+ }
+ fitted[widest] = (fitted[widest] ?? 0) - 1
+ total -= 1
+ }
+ }
+ return fitted
+}
diff --git a/hog/src/core/raw-json.ts b/hog/src/core/raw-json.ts
new file mode 100644
index 000000000000..0b24e27a5d0b
--- /dev/null
+++ b/hog/src/core/raw-json.ts
@@ -0,0 +1,9 @@
+// Parses JSON and keeps integers beyond JavaScript's safe range as their source text, so a
+// ClickHouse UInt64 survives the round trip to output unchanged, as it does in posthog-cli.
+export function parseLossless(text: string): unknown {
+ return JSON.parse(text, (_key, value, context) =>
+ typeof value === 'number' && !Number.isSafeInteger(value) && context.source && /^-?\d+$/.test(context.source)
+ ? JSON.rawJSON(context.source)
+ : value
+ )
+}
diff --git a/hog/src/core/runtime.ts b/hog/src/core/runtime.ts
new file mode 100644
index 000000000000..7bfd8f07239f
--- /dev/null
+++ b/hog/src/core/runtime.ts
@@ -0,0 +1,44 @@
+import { readFile } from 'node:fs/promises'
+import { homedir } from 'node:os'
+
+export type Env = Readonly<Record<string, string | undefined>>
+
+// 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 {
+ env: Env
+ stdoutIsTTY: boolean
+ stdoutHasColors: boolean
+ stdoutColumns: number | undefined
+ writeStdout: (text: string) => void
+ writeStderr: (text: string) => void
+ fetch: typeof fetch
+ homeDir: () => string | undefined
+ readFile: (path: string) => Promise<string>
+ readStdin: () => Promise<string>
+}
+
+export function processRuntime(): Runtime {
+ return {
+ env: process.env,
+ stdoutIsTTY: process.stdout.isTTY === true,
+ stdoutHasColors: process.stdout.isTTY === true && process.stdout.hasColors(),
+ stdoutColumns: process.stdout.columns || undefined,
+ writeStdout: (text) => {
+ process.stdout.write(text)
+ },
+ writeStderr: (text) => {
+ process.stderr.write(text)
+ },
+ fetch: globalThis.fetch,
+ homeDir: () => {
+ try {
+ return homedir()
+ } catch {
+ return undefined
+ }
+ },
+ readFile: (path) => readFile(path, 'utf8'),
+ readStdin: () => new Response(Bun.stdin.stream()).text(),
+ }
+}
diff --git a/hog/src/core/text.ts b/hog/src/core/text.ts
new file mode 100644
index 000000000000..d23d7f4be75b
--- /dev/null
+++ b/hog/src/core/text.ts
@@ -0,0 +1,7 @@
+export function kebabCase(name: string): string {
+ return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)
+}
+
+export function plural(count: number, noun: string, pluralNoun = `${noun}s`): string {
+ return `${count} ${count === 1 ? noun : pluralNoun}`
+}
diff --git a/hog/src/index.ts b/hog/src/index.ts
index 2e651ae01499..5dcb9913469a 100644
--- a/hog/src/index.ts
+++ b/hog/src/index.ts
@@ -1,11 +1,9 @@
-#!/usr/bin/env bun
+#!/usr/bin/env -S bun --no-env-file
+import { processRuntime } from '@/core/runtime'
+
import { run } from './cli'
-process.exitCode = run(process.argv.slice(2), {
- stdout: (text) => {
- process.stdout.write(`${text}\n`)
- },
- stderr: (text) => {
- process.stderr.write(`${text}\n`)
- },
+// A promise chain rather than top-level await, which `bun build --bytecode` does not support.
+void run(process.argv.slice(2), processRuntime()).then((code) => {
+ process.exitCode = code
})
diff --git a/hog/src/posthog/api.ts b/hog/src/posthog/api.ts
new file mode 100644
index 000000000000..c237bb04f966
--- /dev/null
+++ b/hog/src/posthog/api.ts
@@ -0,0 +1,107 @@
+import { HogError } from '@/core/errors'
+import { parseLossless } from '@/core/raw-json'
+import { VERSION } from '@/version'
+
+import type { Credentials } from './credentials'
+
+const USER_AGENT = `hog/${VERSION}`
+// Generous, because a HogQL query can run for minutes. It only stops a connection that hangs.
+const REQUEST_TIMEOUT_MS = 10 * 60 * 1000
+
+type Method = 'GET' | 'POST' | 'PATCH' | 'DELETE'
+
+// A non-2xx answer from PostHog. `type` is the DRF error type, such as `validation_error`.
+export class ApiError extends HogError {
+ constructor(
+ readonly status: number,
+ readonly type: string | undefined,
+ code: string,
+ message: string,
+ hint?: string
+ ) {
+ super(code, message, hint)
+ }
+}
+
+export class PostHogApi {
+ constructor(
+ private readonly credentials: Credentials,
+ private readonly fetchFn: typeof fetch
+ ) {}
+
+ // Paths are relative to the project, so `query` is /api/environments/<project id>/query.
+ private environmentUrl(path: string): URL {
+ return new URL(path, new URL(`api/environments/${this.credentials.projectId}/`, this.credentials.host))
+ }
+
+ get<T>(path: string): Promise<T> {
+ return this.request<T>('GET', path)
+ }
+
+ post<T>(path: string, body: unknown): Promise<T> {
+ return this.request<T>('POST', path, body)
+ }
+
+ patch<T>(path: string, body: unknown): Promise<T> {
+ return this.request<T>('PATCH', path, body)
+ }
+
+ delete<T>(path: string): Promise<T> {
+ return this.request<T>('DELETE', path)
+ }
+
+ private async request<T>(method: Method, path: string, body?: unknown): Promise<T> {
+ let response: Response
+ let text: string
+ try {
+ response = await this.fetchFn(this.environmentUrl(path), {
+ method,
+ headers: {
+ Authorization: `Bearer ${this.credentials.apiKey}`,
+ 'Content-Type': 'application/json',
+ 'User-Agent': USER_AGENT,
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ })
+ text = await response.text()
+ } catch (error) {
+ throw new HogError(
+ 'network_error',
+ `hog couldn't reach ${this.credentials.host}: ${error instanceof Error ? error.message : String(error)}`,
+ 'Check the host and your network connection.'
+ )
+ }
+
+ let parsed: unknown
+ try {
+ parsed = text ? parseLossless(text) : undefined
+ } catch {
+ throw new HogError(
+ 'unexpected_response',
+ `PostHog answered with HTTP ${response.status} and a body that isn't JSON.`,
+ response.status === 404 ? 'Check the host and the project ID.' : undefined
+ )
+ }
+ if (!response.ok) {
+ throw this.failure(response.status, parsed)
+ }
+ return parsed as T
+ }
+
+ private failure(status: number, body: unknown): ApiError {
+ const error = (body ?? {}) as { type?: string; code?: string; detail?: string }
+ const hints: Record<number, string> = {
+ 401: 'Check that the personal API key is valid.',
+ 403: 'Check that the personal API key has access to this project.',
+ 404: 'Check the host and the project ID.',
+ }
+ return new ApiError(
+ status,
+ error.type,
+ error.code ?? `http_${status}`,
+ error.detail ?? `PostHog answered with HTTP ${status}.`,
+ hints[status]
+ )
+ }
+}
diff --git a/hog/src/posthog/credentials.test.ts b/hog/src/posthog/credentials.test.ts
new file mode 100644
index 000000000000..d29a73210a04
--- /dev/null
+++ b/hog/src/posthog/credentials.test.ts
@@ -0,0 +1,136 @@
+import { describe, expect, test } from 'bun:test'
+
+import { HogError } from '@/core/errors'
+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 STORED = JSON.stringify({ token: 'phx_stored', env_id: '3', host: 'https://stored.example.com' })
+
+describe('resolveCredentials', () => {
+ test.each([
+ [
+ 'the process env comes first',
+ ENV,
+ { '/x/.env': DOTENV },
+ '/x/.env',
+ undefined,
+ 'phx_env',
+ '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',
+ {},
+ { '/x/.env': DOTENV, '/home/test/.posthog/credentials.json': STORED },
+ '/x/.env',
+ undefined,
+ 'phx_dotenv',
+ '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',
+ {},
+ { '/home/test/.posthog/credentials.json': STORED },
+ '/x/missing.env',
+ undefined,
+ 'phx_stored',
+ '3',
+ 'https://stored.example.com',
+ ],
+ [
+ 'the credentials file is last',
+ {},
+ { '/home/test/.posthog/credentials.json': STORED },
+ undefined,
+ undefined,
+ 'phx_stored',
+ '3',
+ 'https://stored.example.com',
+ ],
+ [
+ 'POSTHOG_HOME moves the credentials file',
+ { POSTHOG_HOME: '/custom' },
+ { '/custom/credentials.json': STORED },
+ undefined,
+ undefined,
+ 'phx_stored',
+ '3',
+ 'https://stored.example.com',
+ ],
+ [
+ '--host overrides the stored host',
+ {},
+ { '/home/test/.posthog/credentials.json': STORED },
+ undefined,
+ 'https://flag.example.com',
+ 'phx_stored',
+ '3',
+ 'https://flag.example.com',
+ ],
+ ] as const)('%s', async (_name, env, files, dotenvFile, host, apiKey, projectId, expectedHost) => {
+ const credentials = await resolveCredentials(fakeRuntime({ env, files }), { dotenvFile, host })
+ expect(credentials).toMatchObject({ apiKey, projectId, host: expectedHost })
+ })
+
+ test.each([
+ ['nothing configured', {}, 'not_authenticated', {}],
+ [
+ 'a key without the phx_ prefix',
+ { POSTHOG_CLI_API_KEY: 'abc', POSTHOG_CLI_PROJECT_ID: '1' },
+ 'invalid_credentials',
+ {},
+ ],
+ [
+ 'a project ID that is not a number',
+ { POSTHOG_CLI_API_KEY: 'phx_a', POSTHOG_CLI_PROJECT_ID: 'two' },
+ 'invalid_credentials',
+ {},
+ ],
+ [
+ '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 },
+ ],
+ ] as const)('fails on %s', async (_name, env, code, files: Record<string, string>) => {
+ const error = await resolveCredentials(fakeRuntime({ env, files }), {}).catch((caught: unknown) => caught)
+ expect(error).toBeInstanceOf(HogError)
+ expect((error as HogError).code).toBe(code)
+ })
+
+ test('fails on a dotenv file it cannot read, instead of falling back', async () => {
+ const runtime = fakeRuntime({ files: { '/home/test/.posthog/credentials.json': STORED } })
+ runtime.readFile = async (path) => {
+ if (path === '/x/.env') {
+ throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' })
+ }
+ return STORED
+ }
+ const error = await resolveCredentials(runtime, { dotenvFile: '/x/.env' }).catch((caught: unknown) => caught)
+ expect((error as HogError).code).toBe('invalid_dotenv_file')
+ })
+})
diff --git a/hog/src/posthog/credentials.ts b/hog/src/posthog/credentials.ts
new file mode 100644
index 000000000000..450122cbc38c
--- /dev/null
+++ b/hog/src/posthog/credentials.ts
@@ -0,0 +1,159 @@
+import { join } from 'node:path'
+
+import { 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.
+export const DEFAULT_HOST = 'https://us.i.posthog.com'
+
+export interface Credentials {
+ apiKey: string
+ projectId: string
+ host: string
+}
+
+interface RawCredentials {
+ apiKey: string
+ projectId: string
+ host: string | undefined
+}
+
+// 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.
+function fromLookup(lookup: (name: string) => string | undefined): RawCredentials | undefined {
+ const apiKey = lookup('POSTHOG_CLI_API_KEY') ?? lookup('POSTHOG_CLI_TOKEN')
+ const projectId = lookup('POSTHOG_CLI_PROJECT_ID') ?? lookup('POSTHOG_CLI_ENV_ID')
+ if (!apiKey || !projectId) {
+ return undefined
+ }
+ return { apiKey, projectId, host: lookup('POSTHOG_CLI_HOST') || undefined }
+}
+
+function parseDotenv(contents: string, path: string): Map<string, string> {
+ const values = new Map<string, string>()
+ contents.split(/\r?\n/).forEach((raw, index) => {
+ const line = raw.trim()
+ if (!line || line.startsWith('#')) {
+ return
+ }
+ const separator = line.indexOf('=')
+ const key = separator === -1 ? '' : line.slice(0, separator).trim()
+ if (!key) {
+ throw new HogError(
+ 'invalid_dotenv_file',
+ `Line ${index + 1} of ${path} is not KEY=VALUE.`,
+ 'Fix the line, or remove --dotenv-file.'
+ )
+ }
+ let value = line.slice(separator + 1).trim()
+ const quote = value[0]
+ if (value.length >= 2 && (quote === '"' || quote === "'") && value.at(-1) === quote) {
+ value = value.slice(1, -1)
+ }
+ values.set(key, value)
+ })
+ return values
+}
+
+// A missing file only warns, as in posthog-cli, so a shared build script still works on a machine
+// that logged in instead. Any other read failure stops the command.
+async function readDotenv(runtime: Runtime, path: string): Promise<string | undefined> {
+ try {
+ return await runtime.readFile(path)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ throw new HogError(
+ 'invalid_dotenv_file',
+ `hog couldn't read ${path}: ${error instanceof Error ? error.message : String(error)}`,
+ 'Check that the file is readable, or remove --dotenv-file.'
+ )
+ }
+ runtime.writeStderr(`Warning: ${path} doesn't exist, so hog uses your other credentials.\n`)
+ return undefined
+ }
+}
+
+function posthogHomeDir(env: Env, homeDir: string | undefined): string | undefined {
+ if (env.POSTHOG_HOME) {
+ return env.POSTHOG_HOME
+ }
+ return homeDir === undefined ? undefined : join(homeDir, '.posthog')
+}
+
+function validate(raw: RawCredentials, host: string): Credentials {
+ if (!raw.apiKey.startsWith('phx_')) {
+ throw new HogError(
+ 'invalid_credentials',
+ "The personal API key doesn't look right: it must start with 'phx_'.",
+ 'Create a personal API key in PostHog under Settings > Personal API keys.'
+ )
+ }
+ if (!/^\d+$/.test(raw.projectId)) {
+ throw new HogError(
+ 'invalid_credentials',
+ `The project ID must be a number, but it is "${raw.projectId}".`,
+ 'Use the number in your project URL, like the 2 in https://us.posthog.com/project/2.'
+ )
+ }
+ try {
+ new URL(host)
+ } catch {
+ throw new HogError('invalid_credentials', `The host must be a valid URL, but it is "${host}".`)
+ }
+ return { apiKey: raw.apiKey, projectId: raw.projectId, host }
+}
+
+// Lookup order matches posthog-cli: process env, then --dotenv-file, then the credentials
+// file `posthog-cli login` writes. --host overrides whichever host the source carried.
+export async function resolveCredentials(
+ runtime: Runtime,
+ options: { host?: string; dotenvFile?: string }
+): Promise<Credentials> {
+ const withHost = (raw: RawCredentials): Credentials => validate(raw, options.host ?? raw.host ?? DEFAULT_HOST)
+
+ const fromEnv = fromLookup((name) => runtime.env[name] || undefined)
+ if (fromEnv) {
+ return withHost(fromEnv)
+ }
+
+ const dotenvFile = options.dotenvFile ?? (runtime.env.POSTHOG_CLI_DOTENV_FILE || undefined)
+ if (dotenvFile) {
+ const contents = await readDotenv(runtime, dotenvFile)
+ if (contents !== undefined) {
+ const values = parseDotenv(contents, dotenvFile)
+ const fromFile = fromLookup((name) => values.get(name) || undefined)
+ 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}.`,
+ 'Add both variables to the file, or remove --dotenv-file.'
+ )
+ }
+ return withHost(fromFile)
+ }
+ }
+
+ const home = posthogHomeDir(runtime.env, runtime.homeDir())
+ if (home !== undefined) {
+ let stored: { token?: unknown; env_id?: unknown; host?: unknown } | undefined
+ try {
+ stored = JSON.parse(await runtime.readFile(join(home, 'credentials.json')))
+ } catch {
+ stored = undefined
+ }
+ if (stored && typeof stored.token === 'string' && stored.env_id !== undefined) {
+ const raw = {
+ apiKey: stored.token,
+ projectId: String(stored.env_id),
+ host: typeof stored.host === 'string' ? stored.host : undefined,
+ }
+ return withHost(raw)
+ }
+ }
+
+ throw new HogError(
+ 'not_authenticated',
+ "hog couldn't find PostHog credentials.",
+ 'Run `posthog-cli login`, or set POSTHOG_CLI_API_KEY and POSTHOG_CLI_PROJECT_ID.'
+ )
+}
diff --git a/hog/src/testing.ts b/hog/src/testing.ts
new file mode 100644
index 000000000000..fdee24d80116
--- /dev/null
+++ b/hog/src/testing.ts
@@ -0,0 +1,89 @@
+import type { Env, Runtime } from '@/core/runtime'
+
+import { run } from './cli'
+
+export interface FakeRuntimeOptions {
+ env?: Env
+ stdoutIsTTY?: boolean
+ columns?: number
+ files?: Record<string, string>
+ stdin?: string
+ // Answers every API request. Without it, requests fail with HTTP 500. A string body is sent
+ // as is, for JSON that JSON.stringify can't produce.
+ respond?: (url: string, body: unknown) => { status: number; body: unknown }
+}
+
+export interface FakeRuntime extends Runtime {
+ stdout: () => string
+ stderr: () => string
+ requests: { method: string; url: string; body: unknown }[]
+}
+
+export function fakeRuntime(options: FakeRuntimeOptions = {}): FakeRuntime {
+ let stdout = ''
+ let stderr = ''
+ const requests: FakeRuntime['requests'] = []
+ const files = options.files ?? {}
+ return {
+ env: options.env ?? {},
+ stdoutIsTTY: options.stdoutIsTTY ?? false,
+ stdoutHasColors: options.stdoutIsTTY ?? false,
+ stdoutColumns: options.columns,
+ writeStdout: (text) => {
+ stdout += text
+ },
+ writeStderr: (text) => {
+ stderr += text
+ },
+ fetch: (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input)
+ const body = init?.body === undefined ? undefined : JSON.parse(String(init.body))
+ requests.push({ method: init?.method ?? 'GET', url, body })
+ const reply = options.respond?.(url, body) ?? { status: 500, body: { detail: 'no fake response' } }
+ const text = typeof reply.body === 'string' ? reply.body : JSON.stringify(reply.body)
+ return new Response(text, { status: reply.status })
+ }) as typeof fetch,
+ homeDir: () => '/home/test',
+ readFile: async (path) => {
+ const contents = files[path]
+ if (contents === undefined) {
+ throw Object.assign(new Error(`ENOENT: no such file or directory, open '${path}'`), { code: 'ENOENT' })
+ }
+ return contents
+ },
+ readStdin: async () => options.stdin ?? '',
+ stdout: () => stdout,
+ stderr: () => stderr,
+ requests,
+ }
+}
+
+// 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',
+ NO_COLOR: '1',
+}
+
+export interface HogRun {
+ exitCode: number
+ stdout: string
+ stderr: string
+ requests: FakeRuntime['requests']
+ json: () => any
+ error: () => any
+}
+
+export async function runHog(argv: string[], options: FakeRuntimeOptions = {}): Promise<HogRun> {
+ const runtime = fakeRuntime(options)
+ const exitCode = await run(argv, runtime)
+ return {
+ exitCode,
+ stdout: runtime.stdout(),
+ stderr: runtime.stderr(),
+ requests: runtime.requests,
+ json: () => JSON.parse(runtime.stdout()),
+ error: () => JSON.parse(runtime.stderr()).error,
+ }
+}
diff --git a/hog/src/types/json-raw.d.ts b/hog/src/types/json-raw.d.ts
new file mode 100644
index 000000000000..48322486fab5
--- /dev/null
+++ b/hog/src/types/json-raw.d.ts
@@ -0,0 +1,17 @@
+// TC39 JSON.parse source text access. Bun supports it, and TypeScript's lib doesn't declare it yet.
+interface RawJSON {
+ readonly rawJSON: string
+}
+
+interface JSONReviverContext {
+ readonly source?: string
+}
+
+interface JSON {
+ parse(
+ text: string,
+ reviver: (this: unknown, key: string, value: unknown, context: JSONReviverContext) => unknown
+ ): unknown
+ rawJSON(text: string): RawJSON
+ isRawJSON(value: unknown): value is RawJSON
+}
diff --git a/hog/src/version.ts b/hog/src/version.ts
new file mode 100644
index 000000000000..fc94e9e673a5
--- /dev/null
+++ b/hog/src/version.ts
@@ -0,0 +1,3 @@
+import pkg from '../package.json' with { type: 'json' }
+
+export const VERSION = pkg.version
diff --git a/hog/tsconfig.json b/hog/tsconfig.json
index 2113cfc00e2c..3dc843e43b65 100644
--- a/hog/tsconfig.json
+++ b/hog/tsconfig.json
@@ -9,7 +9,10 @@
"resolveJsonModule": true,
"skipLibCheck": true,
"noEmit": true,
- "types": ["bun"]
+ "types": ["bun"],
+ "paths": {
+ "@/*": ["./src/*"]
+ }
},
"include": ["src"]
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 35da12ef43d8..d9e52736abd3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1519,6 +1519,13 @@ importers:
version: 2.3.3
hog:
+ dependencies:
+ cli-table3:
+ specifier: 0.6.5
+ version: 0.6.5
+ commander:
+ specifier: 15.0.0
+ version: 15.0.0
devDependencies:
'@types/bun':
specifier: 1.3.14
@@ -7563,6 +7570,10 @@ packages:
'@code-inspector/[email protected]':
resolution: {integrity: sha512-sauXo+GD6QIlqSymNtDTQOyrQid8er71Kr3Jh07viUKd1+U10//EML/tb/IpOzutwauizJeQslKqAvDV+Nqc9w==}
+ '@colors/[email protected]':
+ resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}
+ engines: {node: '>=0.1.90'}
+
'@commander-js/[email protected]':
resolution: {integrity: sha512-hIn0ncNaJRLkZrxBIp5AsW/eXEHNKYQBh0aPdoUqNgD+Io3NIykQqpKFyKcuasZhicGaEZJX/JBSIkZ4e5x8Dg==}
peerDependencies:
@@ -15403,6 +15414,10 @@ packages:
resolution: {integrity: sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==}
+ engines: {node: 10.* || >= 12.*}
+
resolution: {integrity: sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==}
engines: {node: '>=18'}
@@ -15495,6 +15510,10 @@ packages:
resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==}
engines: {node: '>=20'}
+ resolution: {integrity: sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==}
+ engines: {node: '>=22.12.0'}
+
resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==}
@@ -26712,6 +26731,9 @@ snapshots:
- supports-color
- utf-8-validate
+ '@colors/[email protected]':
+ optional: true
+
dependencies:
commander: 14.0.3
@@ -35652,6 +35674,12 @@ snapshots:
dependencies:
restore-cursor: 5.1.0
+ dependencies:
+ string-width: 4.2.3
+ optionalDependencies:
+ '@colors/colors': 1.5.0
+
dependencies:
slice-ansi: 5.0.0
@@ -35750,6 +35778,8 @@ snapshots:
+