feat: emit run summary on stderr for agent/observability by pipeline1987 · Pull Request #197 · algolia/cli
Summary
When ALGOLIA_CLI_NON_INTERACTIVE=1 or ALGOLIA_CLI_OBSERVABILITY=1 is set, the CLI writes a single JSON line to stderr at the end of every run (success or error).
- New behavior: After the command finishes, a line like the following is written to stderr:
- Success:
{"event":"cli_run","invocation_id":"...","command":"algolia indices list","status":"ok","duration_ms":123} - Error: same fields plus
"status":"error" and "error":"..."(message truncated to 500 chars).
- Success:
- Implementation: In
pkg/cmd/root/root.go:runSummarystruct for the JSON payload(event, invocation_id, command, status, duration_ms, optional error).shouldEmitRunSummary()checks the two env vars.emitRunSummary(stderr, ctx, cmd, runErr, duration)builds and encodes the JSON line.- In
Execute(): record start time beforeExecuteContextC, then callemitRunSummarywhen the env vars are set (after the command runs, before existing error handling). Uses existing telemetry metadata forinvocation_idand command path; falls back tocmd.CommandPath()when metadata is not set.
Stdout is unchanged so scripts and agents can keep using -o json on stdout without mixing in this metadata.
Why
- Observability: Operators and automation can see what command ran, whether it succeeded, how long it took, and a unique invocation_id without parsing stdout.
- Agent/CI-friendly: One machine-readable line per run makes it easy to log, monitor, or correlate with backend telemetry.
Non-invasive: Only active when the env vars are set; default behavior is unchanged.
Test
- Build and run
go build -o algolia ./cmd/algolia
- Success path — run summary on stderr
ALGOLIA_CLI_OBSERVABILITY=1 ./algolia --help 2>/tmp/stderr.txt
tail -1 /tmp/stderr.txt
Expect one JSON line with "event":"cli_run", "status":"ok", invocation_id, command, duration_ms.
- Error path — run summary with error
ALGOLIA_CLI_NON_INTERACTIVE=1 ./algolia unknown-cmd 2>/tmp/stderr.txt
tail -1 /tmp/stderr.txt
Expect one JSON line with "status":"error" and an "error" field.
- No env var — no run summary
./algolia --help 2>/tmp/stderr.txt
tail -1 /tmp/stderr.txt
Last line of stderr should not be a cli_run JSON object (e.g. empty or other CLI output).