From cb8e313ed40471ef5350985058ca0ade1b1ae914 Mon Sep 17 00:00:00 2001 From: zhaoren Date: Fri, 13 Nov 2026 17:09:34 +0800 Subject: [PATCH 01/10] feat(telemetry): track recipes and init across shell and MCP Add anonymous core-flow events, optional webpage attribution, Agent classification and bounded collector delivery. Honor live MCP opt-out and Retry-After, classify EOF as failure, and emit each init validation stage once. Include privacy documentation and regression coverage. --- CHANGELOG.md | 13 + README.md | 6 + docs/automation.md | 19 + docs/commands.md | 9 +- docs/llms.txt | 6 +- docs/telemetry.md | 188 +++++---- internal/cli/agent_infer.go | 6 +- internal/cli/agent_infer_test.go | 13 +- internal/cli/analytics.go | 427 +++++++++++++++++++++ internal/cli/analytics_regression_test.go | 249 ++++++++++++ internal/cli/analytics_test.go | 193 ++++++++++ internal/cli/app.go | 3 + internal/cli/commands.go | 12 +- internal/cli/env_help.go | 2 + internal/cli/init.go | 23 +- internal/cli/integration_analytics_test.go | 89 +++++ internal/cli/integration_recipe_test.go | 16 + internal/cli/mcp.go | 68 +++- internal/cli/quickstart.go | 6 +- internal/cli/recipes.go | 26 +- internal/cli/telemetry.go | 4 +- 21 files changed, 1268 insertions(+), 110 deletions(-) create mode 100644 internal/cli/analytics.go create mode 100644 internal/cli/analytics_regression_test.go create mode 100644 internal/cli/analytics_test.go create mode 100644 internal/cli/integration_analytics_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c938e0..7dacfaa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -415,3 +415,16 @@ Set `AGORA_ALLOW_UPGRADE_IN_CI=1` only when a CI job intentionally needs to muta [0.1.6]: https://github.com/AgoraIO/cli/compare/v0.1.5...v0.1.6 [0.1.5]: https://github.com/AgoraIO/cli/compare/v0.1.4...v0.1.5 [0.1.4]: https://github.com/AgoraIO/cli/releases/tag/v0.1.4 + +### Unreleased — anonymous core-flow analytics + +- Add opt-out-aware recipes/init events for shell and MCP, optional one-call + anonymous webpage attribution, bounded capture and coarse Agent classification. +- This source build has no embedded collector URL; activation needs deployment + configuration and updated privacy/consent controls. Stable command JSON and + business exit codes are unchanged. Sentry transport remains a placeholder. + +- Fix live MCP analytics opt-out by checking persisted preferences before each + operation/batch; preserve explicit process opt-out and fail closed on invalid + configuration. Treat EOF as failure, honor 429 Retry-After across MCP calls, + and emit validate once per init attempt. diff --git a/README.md b/README.md index e88785d..a5548cf 100644 --- a/README.md +++ b/README.md @@ -422,3 +422,9 @@ Full guide with debug logging, CI tips, completion troubleshooting, and the `--d - Security policy: [SECURITY.md](SECURITY.md) - Support and contact channels: [SUPPORT.md](SUPPORT.md) - Contributor and agent guide: [AGENTS.md](AGENTS.md), plus [CONTRIBUTING.md](CONTRIBUTING.md) + +Recipes/init analytics supports optional `--source-distinct-id` and +`--source-session-id` for a single invocation. Core commands work without them. +Capture requires an approved configured collector and honors opt-out; see +[Telemetry](docs/telemetry.md). MCP uses the equivalent `sourceDistinctId` and +`sourceSessionId` arguments. diff --git a/docs/automation.md b/docs/automation.md index 4a86a01..5e2ece9 100644 --- a/docs/automation.md +++ b/docs/automation.md @@ -1308,3 +1308,22 @@ Recommended pattern: ./agora init my-go-demo --template go --json ./agora quickstart env write my-go-demo --json ``` + +## Anonymous recipes/init analytics + +Optional `--source-distinct-id` and `--source-session-id` flags on `init`, +`recipes list`, and `recipes show` attribute one command to the originating +Recipes browser/session. They never affect resource authorization or persist +into later commands. Omission or invalid context uses a local random CLI ID; +invalid shell context emits a fixed stderr notice. JSON stdout and business +exit codes remain unchanged. MCP equivalents are `sourceDistinctId` and +`sourceSessionId` on `agora.init`, `agora.recipes.list`, `agora.recipes.show`. + +Events use `source_session_id`, not the browser-managed PostHog `$session_id`. +Separate attempts have separate `operation_id` values; retries do not carry +web context implicitly. Opt-out or a missing collector URL means no capture. +See [Telemetry](telemetry.md) for the event, privacy and transport contract. + +Telemetry status adds `transportConfigured` (valid collector URL present) and +`captureActive` (transport configured and runtime opt-out permits capture). +The existing `enabled` preference field remains compatible. diff --git a/docs/commands.md b/docs/commands.md index b709ea0..4dc8a19 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -114,6 +114,8 @@ Create a project and initialize an official quickstart or recipe | `--recipe` | `string` | — | official Agora recipe slug (run agora recipes list to discover slugs) | | `--rtm-data-center` | `string` | — | RTM data center to configure when rtm is enabled on a newly created project (CN, NA, EU, or AP); defaults to NA | | `--scenario` | `string` | — | quickstart scenario; omitted selects the template default | +| `--source-distinct-id` | `string` | — | optional anonymous Recipes browser ID (paired with --source-session-id) | +| `--source-session-id` | `string` | — | optional source webpage session ID (paired with --source-distinct-id) | | `--template` | `string` | — | quickstart template ID to use | ### `agora introspect` @@ -375,13 +377,18 @@ List recipes from the Agora catalog | Flag | Type | Default | Description | |------|------|---------|-------------| +| `--source-distinct-id` | `string` | — | optional anonymous Recipes browser ID (paired with --source-session-id) | +| `--source-session-id` | `string` | — | optional source webpage session ID (paired with --source-distinct-id) | | `--type` | `string` | `all` | recipe type: all, ai, or rtc | ### `agora recipes show` Show one Agora recipe -_No local flags. Inherited parent and global flags still apply; run `agora --help` for the full flag set._ +| Flag | Type | Default | Description | +|------|------|---------|-------------| +| `--source-distinct-id` | `string` | — | optional anonymous Recipes browser ID (paired with --source-session-id) | +| `--source-session-id` | `string` | — | optional source webpage session ID (paired with --source-distinct-id) | ### `agora skills` diff --git a/docs/llms.txt b/docs/llms.txt index 0551621..a4aa5ee 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -141,7 +141,7 @@ Stable error codes: /cli/md/error-codes.md ## Telemetry -Telemetry is operational diagnostics only and never includes Agora App Certificates or OAuth tokens. Disable with any of: +Configured analytics reports anonymous recipes/init usage and never includes Agora App Certificates or OAuth tokens. This source build has no embedded collector URL; Sentry diagnostics remains a placeholder. Disable with any of: ``` agora telemetry disable agora config update --telemetry-enabled=false @@ -157,3 +157,7 @@ Full telemetry contract (events, fields, sinks): /cli/md/telemetry.md - Security disclosure: security@agora.io (see SECURITY.md) - Documentation: https://agoraio.github.io/cli/ - Agora Console: https://console.agora.io + +Optional analytics attribution: agora.init, agora.recipes.list and +agora.recipes.show accept sourceDistinctId and sourceSessionId, paired for a +single tool call. They are optional, never credentials, and never persisted. diff --git a/docs/telemetry.md b/docs/telemetry.md index c1604c8..dad7503 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -4,80 +4,124 @@ title: Telemetry # Telemetry -Agora CLI telemetry is limited to operational diagnostics such as command -failures and local log metadata. It **never** includes OAuth tokens, app -certificates, dotenv secrets, or project env values. Field redaction is -enforced by `redactTelemetryFields` in -[`internal/cli/telemetry.go`](https://github.com/AgoraIO/cli/blob/main/internal/cli/telemetry.go), -which matches the `token | secret | password | api[_-]?key | authorization` -key pattern (case-insensitive) and replaces the value with the literal -`[REDACTED]`. - -> **Status (current release):** the on/off contract below is fully -> wired. The transport (Sentry SDK) is not yet linked into the binary, -> so all telemetry calls are no-ops at runtime. The next release will -> wire Sentry; the surface and field schema will not change. - -## Inspect or change the setting - -Telemetry is enabled by default in the local config. - -```bash -agora telemetry status -agora telemetry disable -agora telemetry enable -``` - -For scripts, prefer JSON: - -```bash +Agora CLI can report anonymous usage of `recipes list`, `recipes show`, and +`init`, including shell commands and individual MCP tool calls. Events describe +command results, init stages, duration, stable error codes, CLI version, OS, +architecture and coarse Agent classification. Initialization success does not +prove that dependencies were installed or the application ran. + +## Activation and controls + +The local preference defaults to enabled, but this source build embeds **no +collector URL**: it sends nothing until an approved collector is configured. +A release can embed `internal/cli.analyticsEndpoint` with Go `-ldflags -X`. +For local verification, set `AGORA_TELEMETRY_URL` to the collector's full URL. +HTTPS is required except for loopback HTTP. The collector remains disabled +until its PostHog host and project token are configured separately. + +```sh +agora telemetry status --json agora telemetry disable --json +agora telemetry enable --json +DO_NOT_TRACK=1 agora recipes list --json +AGORA_TELEMETRY_ENABLED=0 agora init demo --template nextjs --json ``` -## Opt-out signals - -The CLI honors **all** of the following — any one of them disables -telemetry for the current process: - -| Signal | Notes | -|--------|-------| -| `DO_NOT_TRACK=` | Standard cross-tool convention. Also suppresses local file logs for that process. | -| `AGORA_SENTRY_ENABLED=0` | Hard env override. Wins over the config file. | -| `agora telemetry disable` | Persists `telemetryEnabled: false` to the config. | -| `agora config update --telemetry-enabled=false` | Equivalent to `agora telemetry disable`. | - -```bash -DO_NOT_TRACK=1 agora project list --json -AGORA_SENTRY_ENABLED=0 agora init my-app --template nextjs --json -``` - -## Field schema - -The wire-up plan documents the **exact** field set the Sentry-backed -sink will send. Until then the table below is forward-looking; treat it -as the specification, not the production behavior: - -| Field | Type | Example | Notes | -|-----------------|--------|------------------------------------|-------| -| `command` | string | `"project create"` | Stable label from `agora introspect --json`. | -| `exitCode` | int | `1` | Process exit code at failure. | -| `commitSha` | string | `"abc1234"` | Build-time injected. | -| `os` | string | `"darwin/arm64"` | Runtime, not host-specific. | -| `installMethod` | string | `"installer"` / `"npm"` / `"brew"` | From the install provenance receipt. | -| `agentLabel` | string | `"cursor"` | From `agent_infer.go`. | - -Explicitly **never** sent: - -- OAuth tokens or session refresh tokens. -- Agora App Certificate values. -- Project names or App IDs (use opaque hashes if needed in the future). -- Local file paths beyond the rotating log file path basename. - -## Where the config lives - -```bash -agora config path +Any non-empty `DO_NOT_TRACK`, config `telemetryEnabled=false`, +`AGORA_TELEMETRY_ENABLED=0`, or legacy `AGORA_SENTRY_ENABLED=0` disables capture. +Disabled capture creates no analytics identity and buffers no events. +Existing MCP processes re-read the persisted preference before each operation +and HTTP batch. Disabling capture also discards pending batches; requests already +sent cannot be recalled. Unreadable or invalid persisted configuration stops +capture. Explicit process-level opt-out continues to override file changes. +`telemetry status --json` exposes `transportConfigured` and `captureActive` +separately from the existing preference field `enabled`. +The Sentry diagnostics transport is still a placeholder; configuring analytics +does not enable raw exception reporting. + +## Anonymous identity and optional webpage attribution + +Without web context, the CLI uses a random ID in `analytics-id` under its private +config directory (file mode 0600). This identifies a CLI configuration directory, +not a verified person. Removing that file resets future local attribution. + +Recipes can pass its anonymous browser and source session IDs for one command: + +```sh +agora init demo --recipe hotel-reception \ + --source-distinct-id \ + --source-session-id --json ``` -The same directory holds the rotating log file (`agora-cli.log`) and -the project list cache used by shell completion. +The same optional flags are available on `recipes list` and `recipes show`. +MCP tools `agora.init`, `agora.recipes.list`, and `agora.recipes.show` accept +`sourceDistinctId` and `sourceSessionId`. The parameters are not persisted. +Missing/invalid paired values fall back to the CLI anonymous ID without blocking +the command. Invalid shell context produces a fixed stderr notice with no IDs. + +With valid source context, events use the browser distinct ID and store the +web session as `source_session_id`. They do **not** set PostHog `$session_id` +or pretend the browser remained active while CLI commands ran. Join webpage +`$session_id` to CLI `source_session_id`. Deduplicate repeated copies by +`(distinct_id, webpage session, recipe ID)`; use a defined conversion window +(recommended: seven days). `operation_id` identifies a command attempt and +changes on retry. `event_id` identifies an event for delivery deduplication. +A start event may precede recipe validation; join subsequent events by +`operation_id` to obtain the validated recipe identity. + +Web IDs can appear in copied prompts, AI conversations and shell history. +Forwarded prompts retain the original source. Neither these IDs nor inferred +Agent labels authenticate users, clients or resource ownership. The website +must not attach IDs when analytics is unavailable or opted out, and must only +add these flags once the installed CLI version supports them. Website copy +adaptation is a separate release from this CLI implementation. + +## Events + +| Event | Meaning | +| --- | --- | +| `cli_recipes_list_completed` | Catalog command ended, with outcome and result count on success | +| `cli_recipes_show_completed` | Detail command ended, with validated public recipe slug on success | +| `cli_init_started` | Init handler entered, before business validation | +| `cli_init_stage_completed` | One init stage ended, successfully or unsuccessfully | +| `cli_init_completed` | Init attempt ended, with outcome, total duration, exit code and failed stage | + +Stages: `validate`, `source_resolve`, `project_resolve`, `clone`, `env_write`, +`binding_write`, `context_write`, `agent_rules_write` (when requested). +`validate` covers entry argument checks once per attempt; `source_resolve` +includes validation of the selected source and scaffold target. +`outcome` is `success`, `failure`, or `cancelled`. EOF and unexpected EOF from +backend connections are failures; only explicit cancellation signals or an +`INIT_ABORTED` result are cancellations. Missing final events indicate +unobserved completion, not proven failure. Telemetry is best effort and may be +lost on process termination or network failure. + +## Safety and runtime behavior + +Only allowlisted properties are constructed. Events never include tokens, +certificates, dotenv contents, complete commands, local paths, project names, +App IDs, prompts, raw environment values, raw errors or request/response bodies. +Agent inference does not prove AI execution; unrecognized callers are `unknown`, +not human. Custom Agent labels are reduced to `custom`. + +CLI capture uses an in-memory bounded buffer, a dedicated unauthenticated HTTP +client with redirects disabled, and a total exit-flush budget of one second. +On HTTP 429 it discards remaining events for that operation. Later calls in +the same MCP process pause until `Retry-After` (seconds or HTTP date); missing +or invalid headers default to one minute. No sleeping/retrying delays the +business command, and cooldown is not persisted across separate CLI processes. +It has no disk queue, background daemon or unbounded retry. Capture errors do +not change command exit codes or the stdout JSON contract. + +The anonymous collector validates a strict shared schema, limits size/rate, +deduplicates event IDs, and constructs PostHog events with `app=cli`, explicit +environment, person profile processing disabled and GeoIP enrichment disabled. +It never forwards business authorization or client IP headers. Public project +tokens and browser IDs are not secrets or authentication. A shared PostHog +project still permits forged events through its public capture token. + +Before activation, configure the deployment's data region, IP-discard setting, +access control, retention (target 90 days), deletion procedure, edge quotas, +consent requirements and updated privacy notice. A default-enabled legacy +preference alone is not consent to expanded collection. Inspect actual PostHog +queries to verify ingestion; an HTTP acknowledgement alone is insufficient. diff --git a/internal/cli/agent_infer.go b/internal/cli/agent_infer.go index bffd71d..7f9e853 100644 --- a/internal/cli/agent_infer.go +++ b/internal/cli/agent_infer.go @@ -12,14 +12,16 @@ func agentLabelFromOSEnv(env map[string]string) string { switch { case nonEmptyEnv(env, "CURSOR_AGENT"): return "cursor" - case nonEmptyEnv(env, "CLAUDE_CODE"): + case nonEmptyEnv(env, "CLAUDE_CODE") || nonEmptyEnv(env, "CLAUDECODE"): return "claude-code" case hasEnvPrefix(env, "CLINE_"): return "cline" case hasEnvPrefix(env, "WINDSURF_"): return "windsurf" - case hasEnvPrefix(env, "OPENAI_CODEX_"): + case nonEmptyEnv(env, "CODEX_THREAD_ID") || hasEnvPrefix(env, "OPENAI_CODEX_"): return "codex" + case nonEmptyEnv(env, "KIRO_SESSION_ID"): + return "kiro" case hasEnvPrefix(env, "AIDER_"): return "aider" default: diff --git a/internal/cli/agent_infer_test.go b/internal/cli/agent_infer_test.go index 98cbdc4..d52b3f0 100644 --- a/internal/cli/agent_infer_test.go +++ b/internal/cli/agent_infer_test.go @@ -13,11 +13,15 @@ func TestAgentLabelFromOSEnv(t *testing.T) { }{ {name: "explicit wins", env: map[string]string{"AGORA_AGENT": "custom", "CURSOR_AGENT": "1"}, want: "custom"}, {name: "disabled", env: map[string]string{"AGORA_AGENT_DISABLE_INFER": "1", "CURSOR_AGENT": "1"}, want: ""}, + {name: "explicit wins over codex", env: map[string]string{"AGORA_AGENT": "custom", "CODEX_THREAD_ID": "thread-123"}, want: "custom"}, + {name: "disabled codex", env: map[string]string{"AGORA_AGENT_DISABLE_INFER": "1", "CODEX_THREAD_ID": "thread-123"}, want: ""}, {name: "cursor", env: map[string]string{"CURSOR_AGENT": "1"}, want: "cursor"}, {name: "claude code", env: map[string]string{"CLAUDE_CODE": "1"}, want: "claude-code"}, {name: "cline", env: map[string]string{"CLINE_SESSION": "abc"}, want: "cline"}, {name: "windsurf", env: map[string]string{"WINDSURF_SESSION": "abc"}, want: "windsurf"}, - {name: "codex", env: map[string]string{"OPENAI_CODEX_SESSION": "abc"}, want: "codex"}, + {name: "codex thread", env: map[string]string{"CODEX_THREAD_ID": "thread-123"}, want: "codex"}, + {name: "codex legacy", env: map[string]string{"OPENAI_CODEX_SESSION": "abc"}, want: "codex"}, + {name: "codex empty thread", env: map[string]string{"CODEX_THREAD_ID": ""}, want: ""}, {name: "aider", env: map[string]string{"AIDER_AUTO_COMMITS": "false"}, want: "aider"}, {name: "empty", env: map[string]string{}, want: ""}, } @@ -37,6 +41,13 @@ func TestAgoraUserAgentInfersCursorAgent(t *testing.T) { } } +func TestAgoraUserAgentInfersCodexThread(t *testing.T) { + got := agoraUserAgent(map[string]string{"CODEX_THREAD_ID": "thread-123"}) + if got != "agora-cli/"+version+" agent/codex" { + t.Fatalf("unexpected user agent: %q", got) + } +} + // TestDecideShouldPromptForLoginYesFlagDoesNotBypassGuards is the // regression test for the bug where `--yes` / AGORA_NO_INPUT used to // short-circuit the JSON/CI/non-TTY guards in shouldPromptForLogin and diff --git a/internal/cli/analytics.go b/internal/cli/analytics.go new file mode 100644 index 0000000..16dc450 --- /dev/null +++ b/internal/cli/analytics.go @@ -0,0 +1,427 @@ +package cli + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" + "time" + + "github.com/spf13/cobra" +) + +// Empty until an approved collector is deployed. Release builds may set this +// with -ldflags; local verification uses AGORA_TELEMETRY_URL. +var analyticsEndpoint = "" + +var analyticsIDPattern = regexp.MustCompile(`^[A-Za-z0-9_.$:-]{1,200}$`) +var analyticsSlugPattern = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`) +var analyticsVersionPattern = regexp.MustCompile(`^[A-Za-z0-9.+_-]{0,64}$`) +var analyticsCodePattern = regexp.MustCompile(`^[A-Z][A-Z0-9_]{0,63}$`) + +type analyticsEvent struct { + Event string `json:"event"` + EventID string `json:"event_id"` + OperationID string `json:"operation_id"` + DistinctID string `json:"distinct_id"` + Timestamp time.Time `json:"timestamp"` + Properties map[string]any `json:"properties"` +} + +type analyticsOperation struct { + app *App + command string + id string + distinctID string + properties map[string]any + started time.Time + stage string + stageStarted time.Time + events chan analyticsEvent + done chan struct{} + cancel context.CancelFunc +} + +type analyticsContextKey struct{} + +func analyticsUUID() string { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return "" + } + b[6] = (b[6] & 15) | 64 + b[8] = (b[8] & 63) | 128 + h := hex.EncodeToString(b[:]) + return h[:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:] +} + +func (a *App) analyticsEnabled() bool { + if a == nil || strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "" || a.env["AGORA_TELEMETRY_ENABLED"] == "0" { + return false + } + sentryOverride := a.env["AGORA_SENTRY_ENABLED"] + if a.cfgState.ConfigFilePath != "" { + // applyConfigToEnv also writes this key. Only an explicit OS override + // should mask a preference changed since this MCP process started. + sentryOverride = a.osEnv["AGORA_SENTRY_ENABLED"] + } + return sentryOverride != "0" && a.currentTelemetryPreference() +} + +func (a *App) currentTelemetryPreference() bool { + path, err := resolveConfigFilePath(a.env) + if err != nil { + return false + } + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) && a.cfgState.ConfigFilePath == "" { + return a.cfg.TelemetryEnabled // Apps constructed without a config store. + } + if err != nil { + return false + } + var config struct { + TelemetryEnabled *bool `json:"telemetryEnabled"` + } + if json.Unmarshal(data, &config) != nil { + return false + } + if config.TelemetryEnabled == nil { + return a.cfg.TelemetryEnabled + } + return *config.TelemetryEnabled +} + +func (a *App) analyticsRateLimited() bool { + a.analyticsMu.Lock() + defer a.analyticsMu.Unlock() + return time.Now().Before(a.analyticsRetryUntil) +} + +func (a *App) deferAnalytics(retryAfter string) { + now := time.Now() + until := now.Add(time.Minute) + if seconds, err := strconv.ParseUint(strings.TrimSpace(retryAfter), 10, 32); err == nil { + until = now.Add(time.Duration(seconds) * time.Second) + } else if date, err := http.ParseTime(retryAfter); err == nil { + until = date + } + a.analyticsMu.Lock() + defer a.analyticsMu.Unlock() + if until.After(a.analyticsRetryUntil) { + a.analyticsRetryUntil = until + } +} + +func (a *App) analyticsURL() string { + endpoint := strings.TrimSpace(a.env["AGORA_TELEMETRY_URL"]) + if endpoint == "" { + endpoint = analyticsEndpoint + } + u, err := url.Parse(endpoint) + if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" { + return "" + } + if u.Scheme != "https" && !(u.Scheme == "http" && (u.Hostname() == "127.0.0.1" || u.Hostname() == "localhost" || u.Hostname() == "::1")) { + return "" + } + return endpoint +} + +func (a *App) analyticsIdentity() string { + dir, err := resolveAgoraDirectory(a.env) + if err != nil { + return "" + } + path := filepath.Join(dir, "analytics-id") + if b, err := os.ReadFile(path); err == nil { + id := strings.TrimSpace(string(b)) + if len(id) == 36 && analyticsIDPattern.MatchString(id) { + return "cli:" + id + } + return "" + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return "" + } + id := analyticsUUID() + if id == "" { + return "" + } + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + if b, readErr := os.ReadFile(path); readErr == nil { + other := strings.TrimSpace(string(b)) + if len(other) == 36 && analyticsIDPattern.MatchString(other) { + return "cli:" + other + } + } + return "" + } + _, writeErr := f.WriteString(id) + closeErr := f.Close() + if writeErr != nil || closeErr != nil { + return "" + } + return "cli:" + id +} + +func (a *App) beginAnalytics(command, channel, distinct, session string) *analyticsOperation { + endpoint := a.analyticsURL() + if !a.analyticsEnabled() || endpoint == "" || a.analyticsRateLimited() { + return nil + } + id := "" + props := map[string]any{"command": command, "os": runtime.GOOS, "arch": runtime.GOARCH, "invocation_channel": channel} + version, _ := versionInfo()["version"].(string) + if !analyticsVersionPattern.MatchString(version) { + version = "custom" + } + props["cli_version"] = version + family, surface, source := analyticsAgent(a.osEnv) + props["agent_family"], props["agent_surface"], props["agent_detection_source"] = family, surface, source + if distinct != "" && session != "" && analyticsIDPattern.MatchString(distinct) && analyticsIDPattern.MatchString(session) { + id = distinct + props["source_session_id"] = session + } + if id == "" { + id = a.analyticsIdentity() + } + if id == "" { + return nil + } + ctx, cancel := context.WithCancel(context.Background()) + op := &analyticsOperation{app: a, command: command, id: analyticsUUID(), distinctID: id, properties: props, started: time.Now(), events: make(chan analyticsEvent, 64), done: make(chan struct{}), cancel: cancel} + go op.deliver(ctx, endpoint) + if command == "init" { + op.emit("cli_init_started", nil) + op.beginStage("validate") + } + return op +} + +func analyticsAgent(env map[string]string) (family, surface, source string) { + surface, source = "unknown", "none" + label := agentLabelFromOSEnv(env) + family = "unknown" + if label == "" { + return + } + source = "environment" + if strings.TrimSpace(env["AGORA_AGENT"]) != "" { + source = "explicit" + } + switch label { + case "codex", "claude-code", "kiro", "cursor", "cline", "windsurf", "aider": + family = label + default: + family = "custom" + } + if family == "claude-code" { + switch env["CLAUDE_CODE_ENTRYPOINT"] { + case "cli": + surface = "cli" + case "claude-desktop": + surface = "desktop" + } + } + if family == "codex" && env["CODEX_INTERNAL_ORIGINATOR_OVERRIDE"] == "Codex Desktop" { + surface = "desktop" + } + if family == "kiro" { + if env["AWS_SDK_UA_APP_ID"] == "kiro-ide" { + surface = "desktop" + } else if env["KIRO_CLI_ACP_CLIENT_NAME"] == "kiro-tui" { + surface = "cli" + } + } + return +} + +func (op *analyticsOperation) emit(name string, fields map[string]any) { + if op == nil { + return + } + props := make(map[string]any, len(op.properties)+len(fields)) + for k, v := range op.properties { + props[k] = v + } + for k, v := range fields { + props[k] = v + } + e := analyticsEvent{Event: name, EventID: analyticsUUID(), OperationID: op.id, DistinctID: op.distinctID, Timestamp: time.Now().UTC(), Properties: props} + select { + case op.events <- e: + default: + } +} + +func (op *analyticsOperation) beginStage(stage string) { + if op == nil || op.command != "init" { + return + } + if op.stage != "" { + op.completeStage(nil) + } + op.stage, op.stageStarted = stage, time.Now() +} + +func analyticsOutcome(err error) (string, string) { + if err == nil { + return "success", "" + } + var ce *cliError + code := "CLI_ERROR" + if errors.As(err, &ce) && analyticsCodePattern.MatchString(ce.Code) { + code = ce.Code + } + if errors.Is(err, context.Canceled) || code == "INIT_ABORTED" { + return "cancelled", code + } + return "failure", code +} + +func (op *analyticsOperation) completeStage(err error) { + if op == nil || op.stage == "" { + return + } + outcome, code := analyticsOutcome(err) + op.emit("cli_init_stage_completed", map[string]any{"stage": op.stage, "outcome": outcome, "error_code": code, "duration_ms": time.Since(op.stageStarted).Milliseconds()}) + op.stage = "" +} + +func (op *analyticsOperation) finish(err error) { + if op == nil { + return + } + failedStage := "" + if err != nil { + failedStage = op.stage + } + op.completeStage(err) + outcome, code := analyticsOutcome(err) + fields := map[string]any{"outcome": outcome, "error_code": code, "duration_ms": time.Since(op.started).Milliseconds(), "exit_code": 0} + if err != nil { + fields["exit_code"] = exitCodeForError(err) + } + event := "cli_" + strings.ReplaceAll(op.command, " ", "_") + "_completed" + if op.command == "init" && failedStage != "" { + fields["failed_stage"] = failedStage + } + op.emit(event, fields) + close(op.events) + timer := time.NewTimer(time.Second) + defer timer.Stop() + select { + case <-op.done: + case <-timer.C: + } + op.cancel() +} + +func (op *analyticsOperation) deliver(ctx context.Context, endpoint string) { + defer close(op.done) + client := &http.Client{Timeout: 750 * time.Millisecond, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }} + defer client.CloseIdleConnections() + for { + var first analyticsEvent + select { + case <-ctx.Done(): + return + case e, ok := <-op.events: + if !ok { + return + } + first = e + } + events := []analyticsEvent{first} + drain: + for len(events) < 20 { + select { + case e, ok := <-op.events: + if !ok { + break drain + } + events = append(events, e) + default: + break drain + } + } + if !op.app.analyticsEnabled() { + return // Discard this operation's remaining events after opt-out. + } + if op.app.analyticsRateLimited() { + return + } + body, err := json.Marshal(map[string]any{"events": events}) + if err != nil { + continue + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) + if err != nil { + continue + } + req.Header.Set("Content-Type", "application/json") + response, err := client.Do(req) + if err == nil { + if response.StatusCode == http.StatusTooManyRequests { + op.app.deferAnalytics(response.Header.Get("Retry-After")) + _ = response.Body.Close() + return + } + _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096)) + _ = response.Body.Close() + } + } +} + +func analyticsFor(cmd *cobra.Command) *analyticsOperation { + op, _ := cmd.Context().Value(analyticsContextKey{}).(*analyticsOperation) + return op +} + +func (a *App) instrumentAnalytics(cmd *cobra.Command, command string) { + var distinct, session string + cmd.Flags().StringVar(&distinct, "source-distinct-id", "", "optional anonymous Recipes browser ID (paired with --source-session-id)") + cmd.Flags().StringVar(&session, "source-session-id", "", "optional source webpage session ID (paired with --source-distinct-id)") + run := cmd.RunE + cmd.RunE = func(cmd *cobra.Command, args []string) (err error) { + if (distinct != "" || session != "") && !(distinct != "" && session != "" && analyticsIDPattern.MatchString(distinct) && analyticsIDPattern.MatchString(session)) { + fmt.Fprintln(cmd.ErrOrStderr(), "Ignoring invalid or incomplete analytics source context.") + } + op := a.beginAnalytics(command, "shell", distinct, session) + ctx := cmd.Context() + cmd.SetContext(context.WithValue(ctx, analyticsContextKey{}, op)) + defer func() { op.finish(err); cmd.SetContext(ctx) }() + return run(cmd, args) + } +} + +func firstAnalytics(ops []*analyticsOperation) *analyticsOperation { + if len(ops) > 0 { + return ops[0] + } + return nil +} + +func (op *analyticsOperation) source(kind, id string) { + if op == nil || len(id) > 100 || !analyticsSlugPattern.MatchString(id) { + return + } + op.properties["source_type"], op.properties["source_id"] = kind, id + if kind == "recipe" { + op.properties["recipe_id"] = id + } +} diff --git a/internal/cli/analytics_regression_test.go b/internal/cli/analytics_regression_test.go new file mode 100644 index 0000000..9be3dd1 --- /dev/null +++ b/internal/cli/analytics_regression_test.go @@ -0,0 +1,249 @@ +package cli + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "strconv" + "sync/atomic" + "testing" + "time" +) + +func TestAnalyticsLiveMCPPreference(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + state, err := ensureAppConfigState(a.env) + if err != nil { + t.Fatal(err) + } + a.cfg, a.cfgState = state.Config, state + a.applyConfigToEnv() + if _, err := a.callMCPTool("agora.init", map[string]any{}, nil); err == nil { + t.Fatal("missing name must fail") + } + before := len(read()) + if before == 0 { + t.Fatal("expected initial capture") + } + cfg := state.Config + cfg.TelemetryEnabled = false + if err := writeSecureJSON(state.ConfigFilePath, cfg); err != nil { + t.Fatal(err) + } + if _, err := a.callMCPTool("agora.init", map[string]any{}, nil); err == nil { + t.Fatal("business validation must still fail") + } + if len(read()) != before { + t.Fatal("existing MCP continued sending after persisted opt-out") + } + status, err := a.callMCPTool("agora.telemetry.status", nil, nil) + if err != nil { + t.Fatal(err) + } + if status.(map[string]any)["captureActive"] != false { + t.Fatal("MCP status uses stale preference") + } + cfg.TelemetryEnabled = true + if err := writeSecureJSON(state.ConfigFilePath, cfg); err != nil { + t.Fatal(err) + } + op := a.beginAnalytics("recipes list", "mcp", "", "") + if op == nil { + t.Fatal("persisted re-enable did not resume capture") + } + op.finish(nil) +} + +func TestAnalyticsOptOutBeforeNextBatch(t *testing.T) { + first := make(chan struct{}) + release := make(chan struct{}) + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + if calls.Add(1) == 1 { + close(first) + <-release + } + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + a := analyticsTestApp(t, server.URL) + state, err := ensureAppConfigState(a.env) + if err != nil { + t.Fatal(err) + } + op := a.beginAnalytics("init", "mcp", "", "") + select { + case <-first: + case <-time.After(time.Second): + t.Fatal("initial batch not sent") + } + cfg := state.Config + cfg.TelemetryEnabled = false + if err := writeSecureJSON(state.ConfigFilePath, cfg); err != nil { + t.Fatal(err) + } + op.beginStage("clone") + close(release) + op.finish(nil) + if calls.Load() != 1 { + t.Fatalf("queued batches sent after opt-out: %d", calls.Load()) + } +} + +func TestAnalyticsEOFIsFailure(t *testing.T) { + for _, err := range []error{io.EOF, io.ErrUnexpectedEOF, fmt.Errorf("API decode: %w", io.EOF), &url.Error{Op: "Get", URL: "https://example.invalid", Err: io.EOF}} { + outcome, _ := analyticsOutcome(err) + if outcome != "failure" { + t.Errorf("backend disconnect %T classified as %s", err, outcome) + } + } + for _, err := range []error{context.Canceled, fmt.Errorf("interrupted: %w", context.Canceled), &cliError{Code: "INIT_ABORTED"}} { + outcome, _ := analyticsOutcome(err) + if outcome != "cancelled" { + t.Errorf("explicit cancellation classified as %s", outcome) + } + } +} + +func TestAnalytics429StopsExistingMCP(t *testing.T) { + for _, retryAfter := range []string{"60", time.Now().Add(time.Minute).UTC().Format(http.TimeFormat), "invalid", ""} { + t.Run(retryAfter, func(t *testing.T) { + first := make(chan struct{}) + release := make(chan struct{}) + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + if calls.Add(1) == 1 { + close(first) + <-release + } + w.Header().Set("Retry-After", retryAfter) + w.WriteHeader(http.StatusTooManyRequests) + })) + defer server.Close() + a := analyticsTestApp(t, server.URL) + op := a.beginAnalytics("init", "mcp", "", "") + select { + case <-first: + case <-time.After(time.Second): + t.Fatal("initial batch not sent") + } + op.beginStage("clone") + close(release) + op.finish(errors.New("clone failed")) + _, _ = a.callMCPTool("agora.init", map[string]any{}, nil) + if calls.Load() != 1 { + t.Fatalf("continued capture after 429: %d requests", calls.Load()) + } + }) + } +} + +func TestAnalyticsBackendEOFRecordedAsFailure(t *testing.T) { + collector, read := analyticsRecorder(t) + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", strconv.Itoa(1000)) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"schemaVersion":`)) + })) + defer backend.Close() + a := analyticsTestApp(t, collector.URL) + a.env["AGORA_RECIPES_BASE_URL"] = backend.URL + _, err := a.callMCPTool("agora.recipes.list", map[string]any{}, nil) + if err == nil { + t.Fatal("truncated backend response must fail") + } + events := read() + if len(events) != 1 { + b, _ := json.Marshal(events) + t.Fatalf("unexpected events: %s", b) + } + if events[0].Properties["outcome"] != "failure" { + t.Fatalf("backend disconnect counted as %v", events[0].Properties["outcome"]) + } +} + +func TestAnalytics429CooldownCanExpire(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + a.deferAnalytics("60") + if a.beginAnalytics("recipes list", "mcp", "", "") != nil { + t.Fatal("capture started during cooldown") + } + a.analyticsMu.Lock() + a.analyticsRetryUntil = time.Now().Add(-time.Second) + a.analyticsMu.Unlock() + op := a.beginAnalytics("recipes list", "mcp", "", "") + if op == nil { + t.Fatal("capture did not resume after cooldown") + } + op.finish(nil) + if len(read()) != 1 { + t.Fatal("capture not delivered after cooldown") + } +} + +func TestAnalyticsLiveConfigFailsClosedAndHonorsEnvironment(t *testing.T) { + for _, explicit := range []bool{false, true} { + t.Run(strconv.FormatBool(explicit), func(t *testing.T) { + server, _ := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + state, err := ensureAppConfigState(a.env) + if err != nil { + t.Fatal(err) + } + a.cfgState = state + a.cfg.TelemetryEnabled = false + a.applyConfigToEnv() // Simulate starting MCP with disabled config. + if explicit { + a.osEnv["AGORA_SENTRY_ENABLED"] = "0" + } + cfg := state.Config + cfg.TelemetryEnabled = true + if err := writeSecureJSON(state.ConfigFilePath, cfg); err != nil { + t.Fatal(err) + } + if a.analyticsEnabled() != !explicit { + t.Fatal("persisted enable or explicit opt-out ignored") + } + if err := os.WriteFile(state.ConfigFilePath, []byte("{invalid"), 0o600); err != nil { + t.Fatal(err) + } + if a.analyticsEnabled() { + t.Fatal("unreadable preference must fail closed") + } + }) + } +} + +func TestAnalyticsRetryAfterDeadline(t *testing.T) { + now := time.Now() + for _, tc := range []struct { + name, header string + want time.Time + }{ + {"seconds", "60", now.Add(time.Minute)}, + {"http date", now.Add(2 * time.Minute).UTC().Format(http.TimeFormat), now.Add(2 * time.Minute)}, + {"past date", now.Add(-time.Minute).UTC().Format(http.TimeFormat), now.Add(-time.Minute)}, + {"zero seconds", "0", now}, + {"invalid", "not-a-delay", now.Add(time.Minute)}, + {"missing", "", now.Add(time.Minute)}, + } { + t.Run(tc.name, func(t *testing.T) { + a := &App{} + a.deferAnalytics(tc.header) + difference := a.analyticsRetryUntil.Sub(tc.want) + if difference < -time.Second || difference > time.Second { + t.Fatalf("wrong Retry-After deadline: got %v want %v", a.analyticsRetryUntil, tc.want) + } + }) + } +} diff --git a/internal/cli/analytics_test.go b/internal/cli/analytics_test.go new file mode 100644 index 0000000..25e6622 --- /dev/null +++ b/internal/cli/analytics_test.go @@ -0,0 +1,193 @@ +package cli + +import ( + "bytes" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +func analyticsRecorder(t *testing.T) (*httptest.Server, func() []analyticsEvent) { + t.Helper() + var mu sync.Mutex + var events []analyticsEvent + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "" || r.URL.RawQuery != "" { + t.Error("analytics leaked authentication or query parameters") + } + var body struct { + Events []analyticsEvent `json:"events"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + mu.Lock() + events = append(events, body.Events...) + mu.Unlock() + w.WriteHeader(http.StatusAccepted) + })) + t.Cleanup(server.Close) + return server, func() []analyticsEvent { mu.Lock(); defer mu.Unlock(); return append([]analyticsEvent(nil), events...) } +} + +func analyticsTestApp(t *testing.T, endpoint string) *App { + t.Helper() + return &App{env: map[string]string{"AGORA_HOME": t.TempDir(), "AGORA_TELEMETRY_URL": endpoint}, osEnv: map[string]string{}, cfg: defaultConfig(), httpClient: &http.Client{Timeout: time.Second}} +} + +func TestAnalyticsAttributionPrivacyAndStages(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + a.osEnv = map[string]string{"CLAUDECODE": "1", "CLAUDE_CODE_ENTRYPOINT": "cli", "ANTHROPIC_MODEL": "private-model", "SECRET_TOKEN": "private-token"} + op := a.beginAnalytics("init", "shell", "browser-123", "session-456") + op.source("recipe", "hotel-reception") + op.beginStage("clone") + op.finish(&cliError{Code: "RECIPE_NOT_FOUND", Message: "private-token /private/home/project"}) + events := read() + if len(events) != 4 { + t.Fatalf("want start, two stages, final; got %+v", events) + } + for _, e := range events { + if e.DistinctID != "browser-123" || e.OperationID != op.id || e.Properties["source_session_id"] != "session-456" { + t.Fatalf("bad attribution: %+v", e) + } + } + final := events[len(events)-1] + if final.Event != "cli_init_completed" || final.Properties["failed_stage"] != "clone" || final.Properties["outcome"] != "failure" || final.Properties["agent_family"] != "claude-code" { + t.Fatalf("bad final: %+v", final) + } + b, _ := json.Marshal(events) + if strings.Contains(string(b), "private-") || strings.Contains(string(b), "/private/home") { + t.Fatalf("sensitive data leaked: %s", b) + } + next := a.beginAnalytics("recipes list", "shell", "", "") + next.finish(nil) + all := read() + last := all[len(all)-1] + if !strings.HasPrefix(last.DistinctID, "cli:") || last.Properties["source_session_id"] != nil || last.OperationID == op.id { + t.Fatalf("web identity persisted: %+v", last) + } + info, err := os.Stat(filepath.Join(a.env["AGORA_HOME"], "analytics-id")) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm()&0o077 != 0 { + t.Fatal("anonymous ID is not private") + } +} + +func TestAnalyticsOptOutAndEndpointSafety(t *testing.T) { + for _, key := range []string{"DO_NOT_TRACK", "AGORA_SENTRY_ENABLED", "AGORA_TELEMETRY_ENABLED", "config", "no-endpoint", "unsafe-url"} { + t.Run(key, func(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + switch key { + case "config": + a.cfg.TelemetryEnabled = false + case "no-endpoint": + delete(a.env, "AGORA_TELEMETRY_URL") + case "unsafe-url": + a.env["AGORA_TELEMETRY_URL"] = "http://external.example/events" + case "DO_NOT_TRACK": + a.env[key] = "any-value" + default: + a.env[key] = "0" + } + op := a.beginAnalytics("init", "shell", "browser", "session") + if op != nil { + op.finish(nil) + t.Fatal("disabled transport created an operation") + } + if len(read()) != 0 { + t.Fatal("opt out emitted events") + } + if _, err := os.Stat(filepath.Join(a.env["AGORA_HOME"], "analytics-id")); !os.IsNotExist(err) { + t.Fatal("opt out created an identity") + } + }) + } +} + +func TestAnalyticsMCPIsolationAndInvalidSource(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + for _, args := range []map[string]any{{"sourceDistinctId": "browser", "sourceSessionId": "session"}, {"sourceDistinctId": "browser"}} { + if _, err := a.callMCPTool("agora.init", args, nil); err == nil { + t.Fatal("missing name should still fail") + } + } + events := read() + var finals []analyticsEvent + for _, e := range events { + if e.Event == "cli_init_completed" { + finals = append(finals, e) + } + } + if len(finals) != 2 || finals[0].OperationID == finals[1].OperationID || finals[0].DistinctID != "browser" || !strings.HasPrefix(finals[1].DistinctID, "cli:") { + t.Fatalf("bad MCP isolation: %+v", finals) + } + for _, e := range finals { + if e.Properties["invocation_channel"] != "mcp" { + t.Fatal("wrong MCP channel") + } + } +} + +func TestAnalyticsCommandWithoutWebContext(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + a.root = a.buildRoot() + var out, stderr bytes.Buffer + a.root.SetOut(&out) + a.root.SetErr(&stderr) + a.root.SetArgs([]string{"recipes", "list", "--type", "invalid", "--json"}) + if err := a.root.Execute(); err == nil { + t.Fatal("invalid type should fail") + } + events := read() + if len(events) != 1 || events[0].Event != "cli_recipes_list_completed" || events[0].Properties["error_code"] != "RECIPE_TYPE_INVALID" || !strings.HasPrefix(events[0].DistinctID, "cli:") { + t.Fatalf("bad standalone events: %+v", events) + } +} + +func TestAnalyticsNetworkFailureIsBounded(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-r.Context().Done(): + case <-time.After(1200 * time.Millisecond): + } + })) + defer server.Close() + a := analyticsTestApp(t, server.URL) + start := time.Now() + op := a.beginAnalytics("init", "shell", "", "") + op.finish(errors.New("private error")) + if time.Since(start) > 1500*time.Millisecond { + t.Fatal("analytics delayed command beyond bounded flush") + } +} + +func TestAnalyticsAgentClassification(t *testing.T) { + for _, tc := range []struct { + env map[string]string + family, surface, source string + }{ + {map[string]string{"CLAUDECODE": "1", "CLAUDE_CODE_ENTRYPOINT": "claude-desktop"}, "claude-code", "desktop", "environment"}, + {map[string]string{"KIRO_SESSION_ID": "private", "KIRO_CLI_ACP_CLIENT_NAME": "kiro-tui"}, "kiro", "cli", "environment"}, + {map[string]string{"CODEX_THREAD_ID": "private"}, "codex", "unknown", "environment"}, + {map[string]string{"CODEX_THREAD_ID": "private", "AGORA_AGENT_DISABLE_INFER": "1"}, "unknown", "unknown", "none"}, + {map[string]string{"AGORA_AGENT": "private custom value"}, "custom", "unknown", "explicit"}, + } { + family, surface, source := analyticsAgent(tc.env) + if family != tc.family || surface != tc.surface || source != tc.source { + t.Fatalf("classification: %s %s %s", family, surface, source) + } + } +} diff --git a/internal/cli/app.go b/internal/cli/app.go index 25251a2..8a7b50d 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -24,6 +24,7 @@ import ( "os" "os/signal" "strings" + "sync" "syscall" "time" @@ -151,6 +152,8 @@ type App struct { rootYes bool httpClient *http.Client telemetry telemetryClient + analyticsMu sync.Mutex + analyticsRetryUntil time.Time projectEnvProject string projectEnvFormat string projectEnvShell bool diff --git a/internal/cli/commands.go b/internal/cli/commands.go index f7879d2..77cde3f 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -175,7 +175,7 @@ func (a *App) buildTelemetryCommand() *cobra.Command { cmd := &cobra.Command{ Use: "telemetry", Short: "Inspect or update telemetry preferences", - Long: "Telemetry is limited to operational diagnostics and never includes tokens or app certificates. DO_NOT_TRACK=1 disables telemetry at runtime.", + Long: "Telemetry reports anonymous recipes/init usage when a collector is configured. It never includes tokens or app certificates. DO_NOT_TRACK=1 disables telemetry at runtime.", Example: example(` agora telemetry status agora telemetry disable @@ -228,10 +228,12 @@ func (a *App) renderTelemetry(cmd *cobra.Command) error { return err } return renderResult(cmd, "telemetry", map[string]any{ - "action": "status", - "configPath": path, - "doNotTrack": strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "", - "enabled": a.cfg.TelemetryEnabled && strings.TrimSpace(a.env["DO_NOT_TRACK"]) == "", + "action": "status", + "transportConfigured": a.analyticsURL() != "", + "captureActive": a.analyticsEnabled() && a.analyticsURL() != "", + "configPath": path, + "doNotTrack": strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "", + "enabled": a.currentTelemetryPreference() && strings.TrimSpace(a.env["DO_NOT_TRACK"]) == "", }) } diff --git a/internal/cli/env_help.go b/internal/cli/env_help.go index eda06cd..9891f0e 100644 --- a/internal/cli/env_help.go +++ b/internal/cli/env_help.go @@ -50,6 +50,8 @@ func agoraEnvCatalog() []agoraEnvVar { {Name: "AGORA_RECIPES_BASE_URL", Category: "endpoints", Description: "Override the versioned Agora recipes API base URL for staging and integration tests.", Default: "https://recipes.agora.io/api/v1"}, {Name: "AGORA_QUICKSTART_