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).
  • Implementation: In pkg/cmd/root/root.go:
    • runSummary struct 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 before ExecuteContextC, then call emitRunSummary when the env vars are set (after the command runs, before existing error handling). Uses existing telemetry metadata for invocation_id and command path; falls back to cmd.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

  1. Build and run
go build -o algolia ./cmd/algolia
  1. 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.

  1. 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.

  1. 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).