Skip to content

refactor(telemetry): simplify analytics plumbing and close reporting gaps - #78

Open
digitallysavvy wants to merge 9 commits into
codex/cli-analyticsfrom
chore/cli-analytics-simplify
Open

digitallysavvy wants to merge 9 commits into
codex/cli-analyticsfrom
chore/cli-analytics-simplify

Conversation

@digitallysavvy

Copy link
Copy Markdown
Contributor

Follow-up to #76. Applies the review recommendations on top of codex/cli-analytics. This PR changes no event names, property keys or allowed values. It also leaves business JSON output and exit codes as they were.

Simplifications

  • Explicit analytics parameter. initProject, initRecipeProject, resolveInitProjectForScaffold, quickstartCreate, projectCreate and createProject now take an explicit op *analyticsOperation instead of a hidden variadic operations ...*analyticsOperation. firstAnalytics is removed. Callers that are not instrumented (quickstart create in the shell and in MCP) pass nil. The operation methods are still nil-safe.
  • project_action is set once. The reused/created block that was copied into init.go and recipes.go is now op.setProjectAction(...), called in resolveInitProjectForScaffold next to op.setAppID. It still runs only when project resolution succeeds.
  • One telemetry status helper. telemetryStatus(action, configPath, preference) builds the result for telemetry status|enable|disable and for the agora.telemetry.status MCP tool. Each path produces the same keys and values as before:
    • Shell commands pass a.cfg.TelemetryEnabled. For enable and disable this is the value just saved.
    • MCP still passes currentTelemetryPreference(), which re-reads the config file, so a long-running server sees preference changes made after it started.
    • setTelemetry still resolves the config path before saving, so errors are returned in the same order.
  • Allowlisted values defined once. Init stage names are constants (analyticsStage*), and the agent family, surface and detection-source lists are defined once. Both the emit sites and validAnalyticsEvent use them. A new test, TestAnalyticsAllowlistValuesArePinned, checks the exact values so a change that would break the collector's allowlist fails CI.
  • One telemetry gate. telemetry.go now holds telemetryOptedOut() and telemetryAllowed(preference). Shell analytics, MCP analytics, the MCP status tool and initTelemetry (the Sentry placeholder) all use them. Usage-analytics opt-out works exactly as before:
    • DO_NOT_TRACK set to any non-empty value
    • AGORA_TELEMETRY_ENABLED=0
    • AGORA_SENTRY_ENABLED=0, read from a.env, or only from the OS environment once a config store is attached
  • MCP sends in process. mcp serve is long-lived, so MCP operations no longer start a detached subprocess for each tool call. They call the same sendAnalyticsBatch from a background goroutine. That function does the decoding and allowlist checks and uses the same HTTP client: 10s timeout, no redirects, 64 KiB limit, no auth headers. The bytes sent over the wire match the shell path because both re-marshal through analyticsBatch.
    • Tool responses never wait for delivery.
    • When the host closes stdin, serveMCP waits at most 1s (analyticsMCPDrainTimeout) for batches still in flight.
    • Shell commands keep the detached subprocess.
    • docs/telemetry.md Delivery section is updated.
  • Test files grouped by topic. analytics_final_test.go and analytics_regression_test.go are merged into analytics_test.go (collection, policy and validation) and analytics_send_test.go (batching and delivery). The suite had 32 test functions before; all of them are kept, and 4 new ones are added. The Windows ACL test, the integration test and the notice test files are unchanged.
  • AGENTS.md. The Source Layout now lists analytics.go, analytics_sender.go, analytics_process_*.go and telemetry_notice.go, and the telemetry.go description is corrected.

Gaps

  • Project create failures before the API call are reported. finish() skipped project create on the assumption that createProject had already sent its event. So a failure before the API call (invalid --feature or --rtm-data-center, an unreadable context file, a missing MCP name) sent nothing. The operation now records whether the API-boundary event was sent. If it was not, finish() sends cli_project_create_completed with the existing fields (outcome, error_code, duration_ms, exit_code). Test: TestAnalyticsProjectCreateFailureBeforeAPIIsReported (shell and MCP; fails without the fix).
  • Batch size accounting includes the init start event. beginAnalytics now reserves the size of cli_init_started up front. The reserve covers the worst case after flush copies source_type, source_id and recipe_id (each at its maximum length) onto it. Any event that submit() accepts therefore still fits when flush() adds the start event. The 64 KiB check in flush stays as a backstop. Test: TestAnalyticsBatchAccountingIncludesInitStart (fails without the fix).
  • Docs. docs/telemetry.md now says that a successful project creation is recorded as a success even if a later step such as enabling features fails, and that a project create failure before the API call is reported when the command finishes.

Wire format and business output

  • analyticsEvent and analyticsBatch are unchanged, and no event name, property key or allowed value was added, renamed or removed. TestAnalyticsAllowlistValuesArePinned checks the value sets.
  • The only new event emission is the project create gap fix. It is an existing event with its existing fields, sent in a case where nothing was sent before.
  • Business JSON shapes and exit codes are unchanged. The existing golden, integration and telemetry status tests ("enabled", "captureActive" and the other keys) pass without edits.

Chose not to do

  • No change to the telemetry enabled semantics, the "anonymous" wording or the consent notice, as scoped.
  • Sentry placeholder opt-out changed slightly. It now uses the shared gate, so it also honors AGORA_TELEMETRY_ENABLED=0 and compares AGORA_SENTRY_ENABLED without trimming whitespace, the same as analytics. No DSN is shipped and the client is a no-op, so nothing observable changes. I kept the analytics rules exact rather than the Sentry ones.
  • Kept a 1s exit drain for MCP. MCP hosts end a session by closing stdin and then usually allow a grace period before killing the server. A long-running server sending in process is safe for every tool call except possibly the last one. The bounded drain covers the common case. A host that kills the server immediately could lose the final tool call's batch, which the detached subprocess would have survived. docs/telemetry.md notes this.

Validation

  • go build ./... && go vet ./... && go test -count=1 ./...
  • GOOS=windows go vet ./... and GOOS=windows go test -c ./internal/cli/ (compiles the Windows-only ACL test)
  • go test -race -count=1 ./internal/cli/ -run 'Analytics|Telemetry|MCP'
  • go test -count=3 ./internal/cli/ -run 'Analytics|Telemetry|MCP' (flakiness check)
  • gofmt -l . (clean)
  • ./scripts/check-error-codes.sh
  • go run ./cmd/gendocs -check
  • golangci-lint was not run: it is not installed locally. CI runs it.

🤖 Generated with Claude Code

digitallysavvy and others added 9 commits November 20, 2026 12:19
Replace the hidden variadic operations parameter and firstAnalytics
helper with an explicit *analyticsOperation argument on initProject,
initRecipeProject, resolveInitProjectForScaffold, quickstartCreate,
projectCreate and createProject. Uninstrumented callers pass nil; the
operation methods stay nil-safe.

Record project_action once in resolveInitProjectForScaffold next to
setAppID instead of duplicating the block in init.go and recipes.go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Move the runtime opt-out check into telemetry.go as telemetryOptedOut and
add telemetryAllowed(preference) as the single gate used by usage
analytics (shell startup snapshot and MCP live preference), the MCP
telemetry status tool and the diagnostics client constructor.

Usage-analytics opt-out semantics are unchanged: DO_NOT_TRACK,
AGORA_TELEMETRY_ENABLED=0 and AGORA_SENTRY_ENABLED=0 (OS env only once a
config store is attached). The placeholder Sentry client now also honors
AGORA_TELEMETRY_ENABLED=0; it is a no-op without a DSN either way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Build the telemetry status result in one telemetryStatus helper shared by
telemetry status/enable/disable and the agora.telemetry.status MCP tool.
Shell paths pass the startup preference (already updated by enable and
disable); MCP still passes the freshly re-read config preference.

Define init stage names and the agent family/surface/detection-source
value sets once and use them at emit sites and in validAnalyticsEvent.
Wire values are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mcp serve is long-lived, so spawning a detached sender per tool call is
unnecessary. MCP operations now send from a background goroutine through
the same sendAnalyticsBatch path (validation, 64 KiB limit, ten-second
timeout, no redirects, no auth headers). Tool responses never wait for
delivery; serveMCP waits at most one second for in-flight batches after
the host closes stdin. Shell commands keep the detached subprocess.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
finish() skipped project create on the assumption that createProject had
already emitted cli_project_create_completed at the API boundary. A
failure before that call (invalid flags, unreadable context, missing MCP
name) therefore produced no event. Track whether the boundary event was
emitted and, if not, emit the same event with the existing fields from
finish().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
submit() accounted for the 64 KiB request limit without the
cli_init_started event that flush() prepends (after copying source
attribution onto it), so a near-limit batch could pass accounting and
then be dropped at flush. Reserve the start event's worst-case size,
including attribution, when the operation begins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Merge analytics_final_test.go and analytics_regression_test.go, which were
named after PR history, into analytics_test.go (collection, policy and
validation) and analytics_send_test.go (batching and delivery). No test
is dropped. Add a test pinning the collector-allowlisted stage and agent
value sets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant