From 8c64415de5435ce88f9f52b15e34a3004e5ccd89 Mon Sep 17 00:00:00 2001 From: Hermes Frangoudis Date: Fri, 20 Nov 2026 12:19:59 -0500 Subject: [PATCH 1/9] refactor(telemetry): pass analytics operation explicitly 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 --- internal/cli/analytics.go | 18 +++++++++++------- internal/cli/init.go | 13 +++---------- internal/cli/mcp.go | 2 +- internal/cli/projects.go | 8 ++++---- internal/cli/quickstart.go | 5 ++--- internal/cli/recipes.go | 9 +-------- 6 files changed, 22 insertions(+), 33 deletions(-) diff --git a/internal/cli/analytics.go b/internal/cli/analytics.go index dc625ad..19ff0f3 100644 --- a/internal/cli/analytics.go +++ b/internal/cli/analytics.go @@ -333,13 +333,6 @@ func (a *App) instrumentAnalytics(cmd *cobra.Command, command string) { } } -func firstAnalytics(ops []*analyticsOperation) *analyticsOperation { - if len(ops) > 0 { - return ops[0] - } - return nil -} - func (op *analyticsOperation) setInitSourceType(recipe, template string) { if op == nil { return @@ -373,6 +366,17 @@ func (op *analyticsOperation) setAppID(id string) { op.properties["app_id"] = id } +// setProjectAction records whether init created a project or reused one. +func (op *analyticsOperation) setProjectAction(action string) { + if op == nil { + return + } + op.properties["project_action"] = "reused" + if action == "created" { + op.properties["project_action"] = "created" + } +} + func (op *analyticsOperation) projectCreated(id string, started time.Time, err error) { if op == nil { return diff --git a/internal/cli/init.go b/internal/cli/init.go index 2f2183f..264bdaa 100644 --- a/internal/cli/init.go +++ b/internal/cli/init.go @@ -365,8 +365,7 @@ type initProjectResolution struct { createdRTMDataCenter string } -func (a *App) initProject(name, targetDir string, template quickstartTemplate, existingProject string, features []string, rtmDataCenter string, newProject bool, promptForReuse bool, promptOut io.Writer, promptIn io.Reader, progress progressEmitter, operations ...*analyticsOperation) (map[string]any, error) { - op := firstAnalytics(operations) +func (a *App) initProject(name, targetDir string, template quickstartTemplate, existingProject string, features []string, rtmDataCenter string, newProject bool, promptForReuse bool, promptOut io.Writer, promptIn io.Reader, progress progressEmitter, op *analyticsOperation) (map[string]any, error) { op.source("quickstart", template.ID) if !template.Available || !template.SupportsInit { return nil, &cliError{Message: fmt.Sprintf("Quickstart template %q is not supported by `agora init`. Use `agora quickstart create` instead.", template.ID), Code: "QUICKSTART_TEMPLATE_UNAVAILABLE"} @@ -390,12 +389,6 @@ func (a *App) initProject(name, targetDir string, template quickstartTemplate, e return nil, err } target := resolution.target - if op != nil { - op.properties["project_action"] = "reused" - if resolution.projectAction == "created" { - op.properties["project_action"] = "created" - } - } quickstartResult, err := a.quickstartCreate(template, targetDir, target.project.ProjectID, false, false, promptOut, promptIn, "", progress, op) if err != nil { @@ -437,8 +430,7 @@ func (a *App) initProject(name, targetDir string, template quickstartTemplate, e return result, nil } -func (a *App) resolveInitProjectForScaffold(name string, createFeatures []string, existingProject string, rtmDataCenter string, newProject bool, promptForReuse bool, promptOut io.Writer, promptIn io.Reader, progress progressEmitter, operations ...*analyticsOperation) (initProjectResolution, error) { - op := firstAnalytics(operations) +func (a *App) resolveInitProjectForScaffold(name string, createFeatures []string, existingProject string, rtmDataCenter string, newProject bool, promptForReuse bool, promptOut io.Writer, promptIn io.Reader, progress progressEmitter, op *analyticsOperation) (initProjectResolution, error) { var target projectTarget projectAction := "existing" projectSelectionReason := "explicit_project" @@ -535,6 +527,7 @@ func (a *App) resolveInitProjectForScaffold(name string, createFeatures []string } op.setAppID(target.project.AppID) + op.setProjectAction(projectAction) return initProjectResolution{ target: target, projectAction: projectAction, diff --git a/internal/cli/mcp.go b/internal/cli/mcp.go index 6db329a..49dafbe 100644 --- a/internal/cli/mcp.go +++ b/internal/cli/mcp.go @@ -563,7 +563,7 @@ func (a *App) dispatchMCPTool(name string, args map[string]any, progress progres if target == "" { return nil, errors.New("name or dir is required") } - return a.quickstartCreate(template, target, stringArg(args, "project"), boolArg(args, "templateOnly", false), false, io.Discard, bytes.NewReader(nil), stringArg(args, "ref"), progress) + return a.quickstartCreate(template, target, stringArg(args, "project"), boolArg(args, "templateOnly", false), false, io.Discard, bytes.NewReader(nil), stringArg(args, "ref"), progress, nil) case "agora.quickstart.env_write": return a.quickstartEnvWrite(defaultString(stringArg(args, "dir"), "."), stringArg(args, "template"), stringArg(args, "scenario"), stringArg(args, "project")) diff --git a/internal/cli/projects.go b/internal/cli/projects.go index 8ff78c2..e02c364 100644 --- a/internal/cli/projects.go +++ b/internal/cli/projects.go @@ -29,7 +29,7 @@ func (a *App) refreshProjectListCache() error { return err } -func (a *App) createProject(name, idempotencyKey string, operations ...*analyticsOperation) (projectDetail, error) { +func (a *App) createProject(name, idempotencyKey string, op *analyticsOperation) (projectDetail, error) { started := time.Now() var out projectDetail body := map[string]any{"name": name, "projectType": "paas"} @@ -37,7 +37,7 @@ func (a *App) createProject(name, idempotencyKey string, operations ...*analytic body["idempotencyKey"] = strings.TrimSpace(idempotencyKey) } err := a.apiRequest("POST", "/api/cli/v1/projects", nil, body, &out) - firstAnalytics(operations).projectCreated(out.AppID, started, err) + op.projectCreated(out.AppID, started, err) return out, err } @@ -286,7 +286,7 @@ func (a *App) enableProjectFeature(feature string, project projectDetail, region } } -func (a *App) projectCreate(name, template string, features []string, rtmDataCenter string, idempotencyKey string, operations ...*analyticsOperation) (map[string]any, error) { +func (a *App) projectCreate(name, template string, features []string, rtmDataCenter string, idempotencyKey string, op *analyticsOperation) (map[string]any, error) { ctx, err := loadContext(a.env) if err != nil { return nil, err @@ -300,7 +300,7 @@ func (a *App) projectCreate(name, template string, features []string, rtmDataCen if err != nil { return nil, err } - project, err := a.createProject(name, idempotencyKey, operations...) + project, err := a.createProject(name, idempotencyKey, op) if err != nil { return nil, err } diff --git a/internal/cli/quickstart.go b/internal/cli/quickstart.go index 0b2ccd8..cced287 100644 --- a/internal/cli/quickstart.go +++ b/internal/cli/quickstart.go @@ -397,7 +397,7 @@ If a current project context exists, or if --project is passed, the CLI also wri !isCIEnvironment(a.osEnv) && isTTY(os.Stdin) progress := jsonProgressFor(a, cmd, "quickstart create") - result, err := a.quickstartCreate(template, targetDir, project, templateOnly, promptForProject, cmd.ErrOrStderr(), os.Stdin, ref, progress) + result, err := a.quickstartCreate(template, targetDir, project, templateOnly, promptForProject, cmd.ErrOrStderr(), os.Stdin, ref, progress, nil) if err != nil { return err } @@ -541,8 +541,7 @@ Python and Go quickstarts receive backend AGORA_APP_ID and AGORA_APP_CERTIFICATE return cmd } -func (a *App) quickstartCreate(template quickstartTemplate, targetDir, explicitProject string, templateOnly, promptForProject bool, promptOut io.Writer, promptIn io.Reader, ref string, progress progressEmitter, operations ...*analyticsOperation) (map[string]any, error) { - op := firstAnalytics(operations) +func (a *App) quickstartCreate(template quickstartTemplate, targetDir, explicitProject string, templateOnly, promptForProject bool, promptOut io.Writer, promptIn io.Reader, ref string, progress progressEmitter, op *analyticsOperation) (map[string]any, error) { if !template.Available || strings.TrimSpace(template.RepoURL) == "" { return nil, &cliError{Message: fmt.Sprintf("Quickstart template %q is not available yet.", template.ID), Code: "QUICKSTART_TEMPLATE_UNAVAILABLE"} } diff --git a/internal/cli/recipes.go b/internal/cli/recipes.go index 1d9a200..1647b49 100644 --- a/internal/cli/recipes.go +++ b/internal/cli/recipes.go @@ -219,8 +219,7 @@ func (a *App) getRecipe(slug string) (recipeDetail, error) { return response.Recipe, nil } -func (a *App) initRecipeProject(name, targetDir string, recipe recipeDetail, existingProject string, features []string, rtmDataCenter string, newProject bool, promptForReuse bool, promptOut io.Writer, promptIn io.Reader, progress progressEmitter, operations ...*analyticsOperation) (map[string]any, error) { - op := firstAnalytics(operations) +func (a *App) initRecipeProject(name, targetDir string, recipe recipeDetail, existingProject string, features []string, rtmDataCenter string, newProject bool, promptForReuse bool, promptOut io.Writer, promptIn io.Reader, progress progressEmitter, op *analyticsOperation) (map[string]any, error) { op.source("recipe", recipe.Slug) if err := validateRecipeCLIConfig(recipe.CLI); err != nil { return nil, err @@ -241,12 +240,6 @@ func (a *App) initRecipeProject(name, targetDir string, recipe recipeDetail, exi if err != nil { return nil, err } - if op != nil { - op.properties["project_action"] = "reused" - if resolution.projectAction == "created" { - op.properties["project_action"] = "created" - } - } op.beginStage("clone") if err := cloneScaffoldRepo(recipe.MainRepoURL, absTarget, "", progress); err != nil { return nil, err From 0526973b75620c51e95ff51eea27c594a080a8ac Mon Sep 17 00:00:00 2001 From: Hermes Frangoudis Date: Fri, 20 Nov 2026 12:20:53 -0500 Subject: [PATCH 2/9] refactor(telemetry): share one telemetry opt-out gate 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 --- internal/cli/analytics.go | 22 ++-------- internal/cli/analytics_regression_test.go | 2 +- internal/cli/app.go | 2 +- internal/cli/mcp.go | 2 +- internal/cli/telemetry.go | 53 +++++++++++++++-------- 5 files changed, 43 insertions(+), 38 deletions(-) diff --git a/internal/cli/analytics.go b/internal/cli/analytics.go index 19ff0f3..de0edb4 100644 --- a/internal/cli/analytics.go +++ b/internal/cli/analytics.go @@ -65,24 +65,10 @@ func analyticsUUID() string { return h[:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:] } +// analyticsEnabled applies the shared telemetry gate to the startup +// preference. Shell commands use this snapshot for their whole run. func (a *App) analyticsEnabled() bool { - if a.analyticsOptedOut() { - return false - } - return a.cfg.TelemetryEnabled -} - -func (a *App) analyticsOptedOut() bool { - if a == nil || strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "" || a.env["AGORA_TELEMETRY_ENABLED"] == "0" { - return true - } - 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" + return a.telemetryAllowed(a.cfg.TelemetryEnabled) } func (a *App) currentTelemetryPreference() bool { @@ -173,7 +159,7 @@ func (a *App) beginAnalytics(command, channel string) *analyticsOperation { endpoint := a.analyticsURL() enabled := a.analyticsEnabled() if channel == "mcp" { - enabled = a.currentTelemetryPreference() && !a.analyticsOptedOut() + enabled = a.telemetryAllowed(a.currentTelemetryPreference()) } if !enabled || endpoint == "" { return nil diff --git a/internal/cli/analytics_regression_test.go b/internal/cli/analytics_regression_test.go index 54a0d2b..17ec7cf 100644 --- a/internal/cli/analytics_regression_test.go +++ b/internal/cli/analytics_regression_test.go @@ -138,7 +138,7 @@ func TestAnalyticsLiveConfigFailsClosedAndHonorsEnvironment(t *testing.T) { if err := writeSecureJSON(state.ConfigFilePath, cfg); err != nil { t.Fatal(err) } - if (a.currentTelemetryPreference() && !a.analyticsOptedOut()) != !explicit { + if a.telemetryAllowed(a.currentTelemetryPreference()) != !explicit { t.Fatal("persisted enable or explicit opt-out ignored") } if err := os.WriteFile(state.ConfigFilePath, []byte("{invalid"), 0o600); err != nil { diff --git a/internal/cli/app.go b/internal/cli/app.go index 25251a2..a43200e 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -184,7 +184,7 @@ func NewApp() (*App, error) { // telemetry is disabled, when DO_NOT_TRACK is set, or when the // Sentry DSN is empty (build without telemetry compiled in). Telemetry // must never block the CLI from starting. - a.telemetry = initTelemetry(a.cfg.TelemetryEnabled, a.env, versionInfo()) + a.telemetry = initTelemetry(a.telemetryAllowed(a.cfg.TelemetryEnabled), a.env, versionInfo()) return a, nil } diff --git a/internal/cli/mcp.go b/internal/cli/mcp.go index 49dafbe..5f94e2b 100644 --- a/internal/cli/mcp.go +++ b/internal/cli/mcp.go @@ -386,7 +386,7 @@ func (a *App) dispatchMCPTool(name string, args map[string]any, progress progres return map[string]any{ "action": "status", "transportConfigured": a.analyticsURL() != "", - "captureActive": a.currentTelemetryPreference() && !a.analyticsOptedOut() && a.analyticsURL() != "", + "captureActive": a.telemetryAllowed(a.currentTelemetryPreference()) && a.analyticsURL() != "", "configPath": path, "doNotTrack": strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "", "enabled": a.currentTelemetryPreference(), diff --git a/internal/cli/telemetry.go b/internal/cli/telemetry.go index 91beff2..eaaabff 100644 --- a/internal/cli/telemetry.go +++ b/internal/cli/telemetry.go @@ -6,10 +6,11 @@ import ( "time" ) -// telemetryClient is the diagnostics sink interface. Anonymous product -// analytics uses the separate bounded collector in analytics.go. It is intentionally minimal so the production sink can -// be swapped (e.g. for the Sentry SDK or a file sink in tests) without -// touching call sites in app.go / commands.go. +// telemetryClient is the diagnostics sink interface. Usage analytics uses +// the separate bounded collector in analytics.go; both share the +// telemetryAllowed gate below. The interface is intentionally minimal so the +// production sink can be swapped (e.g. for the Sentry SDK or a file sink in +// tests) without touching call sites in app.go / commands.go. // // Contract for all implementations: // - All methods MUST be safe to call from any goroutine. @@ -43,6 +44,31 @@ type telemetryClient interface { Flush(timeout time.Duration) bool } +// telemetryAllowed is the single gate for every telemetry sink (usage +// analytics and the diagnostics client). preference is the saved +// telemetryEnabled value: the startup snapshot for shell commands, or the +// freshly re-read config for long-lived MCP servers. +func (a *App) telemetryAllowed(preference bool) bool { + return preference && !a.telemetryOptedOut() +} + +// telemetryOptedOut reports a runtime opt-out that overrides the saved +// preference: DO_NOT_TRACK (any non-empty value), AGORA_TELEMETRY_ENABLED=0 +// or AGORA_SENTRY_ENABLED=0. +func (a *App) telemetryOptedOut() bool { + if a == nil || strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "" || a.env["AGORA_TELEMETRY_ENABLED"] == "0" { + return true + } + sentryOverride := a.env["AGORA_SENTRY_ENABLED"] + if a.cfgState.ConfigFilePath != "" { + // applyConfigToEnv also writes this key from the saved preference. + // Only an explicit OS override should mask a preference changed + // since this (possibly long-lived MCP) process started. + sentryOverride = a.osEnv["AGORA_SENTRY_ENABLED"] + } + return sentryOverride == "0" +} + // agoraSentryDSN is the Sentry project DSN that the CLI ships with. // Empty string disables Sentry transport entirely (the default until the // Sentry SDK is wired in for the next release). When set, events go to the @@ -52,22 +78,15 @@ const agoraSentryDSN = "" // initTelemetry returns the telemetry client appropriate for the current // runtime. Decision order: // -// 1. DO_NOT_TRACK is set → noop (Console-style hard opt-out). -// 2. config.telemetryEnabled is false → noop. -// 3. AGORA_SENTRY_ENABLED=0 in the environment → noop. -// 4. agoraSentryDSN is empty (default in the current build) → noop. -// 5. Otherwise → Sentry-backed client (placeholder until SDK wired). +// 1. allowed is false (see App.telemetryAllowed: saved preference off, +// DO_NOT_TRACK, AGORA_TELEMETRY_ENABLED=0 or AGORA_SENTRY_ENABLED=0) → noop. +// 2. agoraSentryDSN is empty (default in the current build) → noop. +// 3. Otherwise → Sentry-backed client (placeholder until SDK wired). // // initTelemetry never returns nil; callers can rely on a usable // interface value without a nil check. -func initTelemetry(configEnabled bool, env map[string]string, _ versionInformation) telemetryClient { - if strings.TrimSpace(env["DO_NOT_TRACK"]) != "" { - return noopTelemetry{} - } - if !configEnabled { - return noopTelemetry{} - } - if strings.TrimSpace(env["AGORA_SENTRY_ENABLED"]) == "0" { +func initTelemetry(allowed bool, env map[string]string, _ versionInformation) telemetryClient { + if !allowed { return noopTelemetry{} } if agoraSentryDSN == "" { From b42fec2b880a34c370a23205fb562446f75d38c6 Mon Sep 17 00:00:00 2001 From: Hermes Frangoudis Date: Fri, 20 Nov 2026 12:22:27 -0500 Subject: [PATCH 3/9] refactor(telemetry): define status shape and allowlist values once 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 --- internal/cli/analytics.go | 62 ++++++++++++++++++++++++-------- internal/cli/analytics_sender.go | 9 ++--- internal/cli/commands.go | 19 ++-------- internal/cli/init.go | 10 +++--- internal/cli/mcp.go | 13 +++---- internal/cli/quickstart.go | 6 ++-- internal/cli/recipes.go | 12 +++---- internal/cli/telemetry_notice.go | 16 +++++++++ 8 files changed, 90 insertions(+), 57 deletions(-) diff --git a/internal/cli/analytics.go b/internal/cli/analytics.go index de0edb4..b27b959 100644 --- a/internal/cli/analytics.go +++ b/internal/cli/analytics.go @@ -12,6 +12,7 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "strings" "time" @@ -29,6 +30,42 @@ 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}$`) +// Init stage names. These and the agent value sets below are part of the +// collector allowlist: emit sites and validAnalyticsEvent share them so the +// two can never drift. +const ( + analyticsStageValidate = "validate" + analyticsStageSourceResolve = "source_resolve" + analyticsStageLocalValidate = "local_validate" + analyticsStageProjectResolve = "project_resolve" + analyticsStageClone = "clone" + analyticsStageEnvWrite = "env_write" + analyticsStageBindingWrite = "binding_write" + analyticsStageContextWrite = "context_write" + analyticsStageAgentRulesWrite = "agent_rules_write" +) + +var analyticsStages = []string{analyticsStageValidate, analyticsStageSourceResolve, analyticsStageLocalValidate, analyticsStageProjectResolve, analyticsStageClone, analyticsStageEnvWrite, analyticsStageBindingWrite, analyticsStageContextWrite, analyticsStageAgentRulesWrite} + +const ( + analyticsAgentCustom = "custom" + analyticsValueUnknown = "unknown" + + analyticsSurfaceDesktop = "desktop" + analyticsSurfaceCLI = "cli" + + analyticsDetectionExplicit = "explicit" + analyticsDetectionEnvironment = "environment" + analyticsDetectionNone = "none" +) + +// analyticsKnownAgentFamilies are agent labels reported as-is; any other +// detected label is reported as analyticsAgentCustom. +var analyticsKnownAgentFamilies = []string{"codex", "claude-code", "kiro", "cursor", "cline", "windsurf", "aider"} +var analyticsAgentFamilies = append(slices.Clone(analyticsKnownAgentFamilies), analyticsAgentCustom, analyticsValueUnknown) +var analyticsAgentSurfaces = []string{analyticsSurfaceDesktop, analyticsSurfaceCLI, analyticsValueUnknown} +var analyticsDetectionSources = []string{analyticsDetectionExplicit, analyticsDetectionEnvironment, analyticsDetectionNone} + type analyticsEvent struct { Event string `json:"event"` EventID string `json:"event_id"` @@ -180,44 +217,41 @@ func (a *App) beginAnalytics(command, channel string) *analyticsOperation { if command == "init" { event := op.newEvent("cli_init_started", nil) op.initStarted = &event - op.beginStage("validate") + op.beginStage(analyticsStageValidate) } return op } func analyticsAgent(env map[string]string) (family, surface, source string) { - surface, source = "unknown", "none" + family, surface, source = analyticsValueUnknown, analyticsValueUnknown, analyticsDetectionNone label := agentLabelFromOSEnv(env) - family = "unknown" if label == "" { return } - source = "environment" + source = analyticsDetectionEnvironment if strings.TrimSpace(env["AGORA_AGENT"]) != "" { - source = "explicit" + source = analyticsDetectionExplicit } - switch label { - case "codex", "claude-code", "kiro", "cursor", "cline", "windsurf", "aider": + family = analyticsAgentCustom + if slices.Contains(analyticsKnownAgentFamilies, label) { family = label - default: - family = "custom" } if family == "claude-code" { switch env["CLAUDE_CODE_ENTRYPOINT"] { case "cli": - surface = "cli" + surface = analyticsSurfaceCLI case "claude-desktop": - surface = "desktop" + surface = analyticsSurfaceDesktop } } if family == "codex" && env["CODEX_INTERNAL_ORIGINATOR_OVERRIDE"] == "Codex Desktop" { - surface = "desktop" + surface = analyticsSurfaceDesktop } if family == "kiro" { if env["AWS_SDK_UA_APP_ID"] == "kiro-ide" { - surface = "desktop" + surface = analyticsSurfaceDesktop } else if env["KIRO_CLI_ACP_CLIENT_NAME"] == "kiro-tui" { - surface = "cli" + surface = analyticsSurfaceCLI } } return diff --git a/internal/cli/analytics_sender.go b/internal/cli/analytics_sender.go index a7473e7..d11b523 100644 --- a/internal/cli/analytics_sender.go +++ b/internal/cli/analytics_sender.go @@ -7,6 +7,7 @@ import ( "net/http" "os" "os/exec" + "slices" "strings" "time" ) @@ -217,15 +218,15 @@ func validAnalyticsEvent(e analyticsEvent) bool { return false } case "agent_family": - if !oneOf(str, "codex", "claude-code", "kiro", "cursor", "cline", "windsurf", "aider", "custom", "unknown") { + if !slices.Contains(analyticsAgentFamilies, str) { return false } case "agent_surface": - if !oneOf(str, "desktop", "cli", "unknown") { + if !slices.Contains(analyticsAgentSurfaces, str) { return false } case "agent_detection_source": - if !oneOf(str, "explicit", "environment", "none") { + if !slices.Contains(analyticsDetectionSources, str) { return false } case "source_type": @@ -245,7 +246,7 @@ func validAnalyticsEvent(e analyticsEvent) bool { return false } case "stage", "failed_stage": - if !oneOf(str, "validate", "source_resolve", "local_validate", "project_resolve", "clone", "env_write", "binding_write", "context_write", "agent_rules_write") { + if !slices.Contains(analyticsStages, str) { return false } case "outcome": diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 219fe6a..3a1ba8d 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -228,14 +228,7 @@ func (a *App) renderTelemetry(cmd *cobra.Command) error { if err != nil { return err } - return renderResult(cmd, "telemetry", map[string]any{ - "action": "status", - "transportConfigured": a.analyticsURL() != "", - "captureActive": a.analyticsEnabled() && a.analyticsURL() != "", - "configPath": path, - "doNotTrack": strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "", - "enabled": a.cfg.TelemetryEnabled, - }) + return renderResult(cmd, "telemetry", a.telemetryStatus("status", path, a.cfg.TelemetryEnabled)) } func (a *App) setTelemetry(cmd *cobra.Command, enabled bool) error { @@ -249,14 +242,8 @@ func (a *App) setTelemetry(cmd *cobra.Command, enabled bool) error { if enabled { a.maybeShowTelemetryNotice(cmd) } - return renderResult(cmd, "telemetry", map[string]any{ - "action": map[bool]string{true: "enable", false: "disable"}[enabled], - "transportConfigured": a.analyticsURL() != "", - "captureActive": a.analyticsEnabled() && a.analyticsURL() != "", - "configPath": path, - "enabled": enabled, - "doNotTrack": strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "", - }) + // persistTelemetryChoice updated a.cfg, so the snapshot is the new choice. + return renderResult(cmd, "telemetry", a.telemetryStatus(map[bool]string{true: "enable", false: "disable"}[enabled], path, a.cfg.TelemetryEnabled)) } func (a *App) buildUpgradeCommand() *cobra.Command { diff --git a/internal/cli/init.go b/internal/cli/init.go index 264bdaa..de3a0e8 100644 --- a/internal/cli/init.go +++ b/internal/cli/init.go @@ -97,7 +97,7 @@ Use --feature to specify which features to enable on a newly created project (re isTTY(os.Stdin) progress := jsonProgressFor(a, cmd, "init") op := analyticsFor(cmd) - op.beginStage("source_resolve") + op.beginStage(analyticsStageSourceResolve) var result map[string]any var err error if strings.TrimSpace(recipeID) != "" { @@ -117,7 +117,7 @@ Use --feature to specify which features to enable on a newly created project (re return err } if len(agentRules) > 0 { - op.beginStage("agent_rules_write") + op.beginStage(analyticsStageAgentRulesWrite) written, err := writeAgentRules(asString(result["path"]), agentRules) if err != nil { return err @@ -370,7 +370,7 @@ func (a *App) initProject(name, targetDir string, template quickstartTemplate, e if !template.Available || !template.SupportsInit { return nil, &cliError{Message: fmt.Sprintf("Quickstart template %q is not supported by `agora init`. Use `agora quickstart create` instead.", template.ID), Code: "QUICKSTART_TEMPLATE_UNAVAILABLE"} } - op.beginStage("local_validate") + op.beginStage(analyticsStageLocalValidate) if _, err := resolveScaffoldTarget(targetDir); err != nil { return nil, err } @@ -383,7 +383,7 @@ func (a *App) initProject(name, targetDir string, template quickstartTemplate, e if err != nil { return nil, err } - op.beginStage("project_resolve") + op.beginStage(analyticsStageProjectResolve) resolution, err := a.resolveInitProjectForScaffold(name, createFeatures, existingProject, rtmDataCenter, newProject, promptForReuse, promptOut, promptIn, progress, op) if err != nil { return nil, err @@ -394,7 +394,7 @@ func (a *App) initProject(name, targetDir string, template quickstartTemplate, e if err != nil { return nil, err } - op.beginStage("context_write") + op.beginStage(analyticsStageContextWrite) if err := a.persistInitProjectContext(target); err != nil { return nil, err } diff --git a/internal/cli/mcp.go b/internal/cli/mcp.go index 5f94e2b..9ee1f7d 100644 --- a/internal/cli/mcp.go +++ b/internal/cli/mcp.go @@ -383,14 +383,9 @@ func (a *App) dispatchMCPTool(name string, args map[string]any, progress progres if err != nil { return nil, err } - return map[string]any{ - "action": "status", - "transportConfigured": a.analyticsURL() != "", - "captureActive": a.telemetryAllowed(a.currentTelemetryPreference()) && a.analyticsURL() != "", - "configPath": path, - "doNotTrack": strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "", - "enabled": a.currentTelemetryPreference(), - }, nil + // MCP is long-lived: re-read the saved preference so changes made + // by other processes since startup are reflected. + return a.telemetryStatus("status", path, a.currentTelemetryPreference()), nil case "agora.upgrade.check": return a.performSelfUpdate(true) @@ -613,7 +608,7 @@ func (a *App) dispatchMCPTool(name string, args map[string]any, progress progres // scribble onto the host's stderr. var promptOut bytes.Buffer targetDir := defaultString(stringArg(args, "dir"), name) - op.beginStage("source_resolve") + op.beginStage(analyticsStageSourceResolve) if recipeID != "" { recipe, err := a.getRecipe(recipeID) if err != nil { diff --git a/internal/cli/quickstart.go b/internal/cli/quickstart.go index cced287..05675f1 100644 --- a/internal/cli/quickstart.go +++ b/internal/cli/quickstart.go @@ -591,7 +591,7 @@ func (a *App) quickstartCreate(template quickstartTemplate, targetDir, explicitP if overrideKey != "" { progress.emit("clone:override", fmt.Sprintf("Using repo override from %s", overrideKey), map[string]any{"repoUrl": repoURL, "envVar": overrideKey}) } - op.beginStage("clone") + op.beginStage(analyticsStageClone) if err := cloneScaffoldRepo(repoURL, absTarget, ref, progress, &template); err != nil { return nil, err } @@ -604,7 +604,7 @@ func (a *App) quickstartCreate(template quickstartTemplate, targetDir, explicitP if !ok { return nil, &cliError{Message: fmt.Sprintf("Quickstart template %q does not define an env target yet.", template.ID), Code: "QUICKSTART_TEMPLATE_ENV_UNSUPPORTED"} } - op.beginStage("env_write") + op.beginStage(analyticsStageEnvWrite) writtenPath, _, err := seedQuickstartEnv(absTarget, template, layout, boundProject.project) if err != nil { if cleanupErr := os.RemoveAll(absTarget); cleanupErr != nil { @@ -612,7 +612,7 @@ func (a *App) quickstartCreate(template quickstartTemplate, targetDir, explicitP } return nil, fmt.Errorf("failed to configure quickstart env after clone: %v; removed %s", err, absTarget) } - op.beginStage("binding_write") + op.beginStage(analyticsStageBindingWrite) if err := writeLocalProjectBinding(absTarget, localProjectBinding{ ProjectID: boundProject.project.ProjectID, ProjectName: boundProject.project.Name, diff --git a/internal/cli/recipes.go b/internal/cli/recipes.go index 1647b49..04254af 100644 --- a/internal/cli/recipes.go +++ b/internal/cli/recipes.go @@ -224,7 +224,7 @@ func (a *App) initRecipeProject(name, targetDir string, recipe recipeDetail, exi if err := validateRecipeCLIConfig(recipe.CLI); err != nil { return nil, err } - op.beginStage("local_validate") + op.beginStage(analyticsStageLocalValidate) absTarget, err := resolveScaffoldTarget(targetDir) if err != nil { return nil, err @@ -235,12 +235,12 @@ func (a *App) initRecipeProject(name, targetDir string, recipe recipeDetail, exi if err != nil { return nil, err } - op.beginStage("project_resolve") + op.beginStage(analyticsStageProjectResolve) resolution, err := a.resolveInitProjectForScaffold(name, createFeatures, existingProject, rtmDataCenter, newProject, promptForReuse, promptOut, promptIn, progress, op) if err != nil { return nil, err } - op.beginStage("clone") + op.beginStage(analyticsStageClone) if err := cloneScaffoldRepo(recipe.MainRepoURL, absTarget, "", progress); err != nil { return nil, err } @@ -254,7 +254,7 @@ func (a *App) initRecipeProject(name, targetDir string, recipe recipeDetail, exi Recipe: recipe.Slug, } envPath := filepath.ToSlash(filepath.Clean(recipe.CLI.Env.TargetPath)) - op.beginStage("env_write") + op.beginStage(analyticsStageEnvWrite) writtenEnv, err := writeCredentialEnv(credentialEnvTarget{ Path: filepath.Join(absTarget, filepath.FromSlash(recipe.CLI.Env.TargetPath)), ExamplePath: filepath.Join(absTarget, filepath.FromSlash(recipe.CLI.Env.ExamplePath)), @@ -273,12 +273,12 @@ func (a *App) initRecipeProject(name, targetDir string, recipe recipeDetail, exi if recipe.CLI.RunCommand != "" { nextSteps = append(nextSteps, recipe.CLI.RunCommand) } - op.beginStage("binding_write") + op.beginStage(analyticsStageBindingWrite) if err := writeLocalProjectBinding(absTarget, binding); err != nil { return nil, cleanupFailedScaffold(absTarget, "write .agora project metadata", err) } sort.Strings(written) - op.beginStage("context_write") + op.beginStage(analyticsStageContextWrite) if err := a.persistInitProjectContext(target); err != nil { return nil, err } diff --git a/internal/cli/telemetry_notice.go b/internal/cli/telemetry_notice.go index ef00fbd..30edacb 100644 --- a/internal/cli/telemetry_notice.go +++ b/internal/cli/telemetry_notice.go @@ -6,6 +6,7 @@ import ( "io" "os" "path/filepath" + "strings" ) const telemetryDisclosure = `Agora CLI collects usage statistics by default when a collector is configured: @@ -35,6 +36,21 @@ func (a *App) persistTelemetryChoice(enabled bool) error { return nil } +// telemetryStatus is the shared result for `agora telemetry status|enable|disable` +// and the agora.telemetry.status MCP tool. preference is the saved +// telemetryEnabled value the caller considers current. +func (a *App) telemetryStatus(action, configPath string, preference bool) map[string]any { + transport := a.analyticsURL() != "" + return map[string]any{ + "action": action, + "transportConfigured": transport, + "captureActive": a.telemetryAllowed(preference) && transport, + "configPath": configPath, + "doNotTrack": strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "", + "enabled": preference, + } +} + func (a *App) maybeShowTelemetryNotice(cmd *cobra.Command) { a.showTelemetryNotice(cmd.ErrOrStderr(), a.analyticsEnabled()) } From 28ef1b89acee5929c762c741b00f432c2491f04d Mon Sep 17 00:00:00 2001 From: Hermes Frangoudis Date: Fri, 20 Nov 2026 12:27:57 -0500 Subject: [PATCH 4/9] refactor(telemetry): send MCP usage batches in process 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 --- docs/telemetry.md | 24 ++++++---- internal/cli/analytics.go | 3 +- internal/cli/analytics_send_test.go | 42 ++++++++++++++++++ internal/cli/analytics_sender.go | 68 ++++++++++++++++++++++++++--- internal/cli/mcp.go | 3 ++ 5 files changed, 125 insertions(+), 15 deletions(-) diff --git a/docs/telemetry.md b/docs/telemetry.md index 90e7fb7..7920c13 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -28,22 +28,28 @@ Each instrumented shell command collects its events in memory and flushes them when the operation finishes. MCP flushes after each instrumented tool call, independently of other calls and without waiting for the MCP server to exit. -The CLI passes one JSON batch through stdin to a detached sender subprocess. -The sender makes one HTTP request with a ten-second timeout. The business -command waits only for a local handoff of at most 100 ms, not for the network -response. Telemetry failures do not change business output or exit codes. +A shell command passes one JSON batch through stdin to a detached sender +subprocess, which outlives the command. The business command waits only for a +local handoff of at most 100 ms, not for the network response. Because +`agora mcp serve` is long-lived, it sends each tool call's batch from a +background goroutine in the same process instead of spawning a subprocess; the +tool response never waits for it. When the MCP host closes stdin, the server +waits at most one second for in-flight batches before exiting. Both paths +apply the same validation and make one HTTP request with a ten-second timeout. +Telemetry failures do not change business output or exit codes. The complete request is limited to 64 KiB. There is no separate event-count or per-event size cap. If an operation exceeds the request limit, its entire batch is dropped. There is no disk queue or retry. A crash or forced termination before -handoff can lose all events for that operation; long-running operations are not -visible in telemetry until they finish. Successful delivery is best effort and -does not prove that PostHog has made the events available for queries. +handoff (or, for MCP, before the request completes) can lose all events for +that operation; long-running operations are not visible in telemetry until they +finish. Successful delivery is best effort and does not prove that PostHog has +made the events available for queries. The sender honors `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and their lowercase forms, as the business HTTP client does. It also preserves `SSL_CERT_FILE` and -`SSL_CERT_DIR` for custom certificate authorities. Other parent environment -variables are not inherited. Business authorization headers are not attached to +`SSL_CERT_DIR` for custom certificate authorities. The shell sender subprocess +does not inherit other parent environment variables. Business authorization headers are not attached to telemetry requests, and redirects are not followed. ## Inspect or change the setting diff --git a/internal/cli/analytics.go b/internal/cli/analytics.go index b27b959..0b94071 100644 --- a/internal/cli/analytics.go +++ b/internal/cli/analytics.go @@ -77,6 +77,7 @@ type analyticsEvent struct { type analyticsOperation struct { command string + channel string id string distinctID string properties map[string]any @@ -213,7 +214,7 @@ func (a *App) beginAnalytics(command, channel string) *analyticsOperation { if id == "" { return nil } - op := &analyticsOperation{command: command, id: analyticsUUID(), distinctID: id, properties: props, started: time.Now(), endpoint: endpoint} + op := &analyticsOperation{command: command, channel: channel, id: analyticsUUID(), distinctID: id, properties: props, started: time.Now(), endpoint: endpoint} if command == "init" { event := op.newEvent("cli_init_started", nil) op.initStarted = &event diff --git a/internal/cli/analytics_send_test.go b/internal/cli/analytics_send_test.go index 3672ce4..7ff3ba9 100644 --- a/internal/cli/analytics_send_test.go +++ b/internal/cli/analytics_send_test.go @@ -203,3 +203,45 @@ func TestAnalyticsStalledTLSBoundsShellAndMCPCompletion(t *testing.T) { }) } } + +func TestAnalyticsMCPSendsInProcessWithoutBlocking(t *testing.T) { + received := make(chan analyticsBatch, 1) + release := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "" { + t.Error("MCP sender attached business authorization") + } + var batch analyticsBatch + if err := json.NewDecoder(r.Body).Decode(&batch); err != nil { + t.Error(err) + } + received <- batch + <-release + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + a := analyticsTestApp(t, server.URL) + started := time.Now() + if _, err := a.callMCPTool("agora.recipes.list", map[string]any{"type": "invalid"}, nil); err == nil { + t.Fatal("invalid type must fail") + } + if time.Since(started) > 500*time.Millisecond { + t.Fatal("MCP tool call waited for telemetry delivery") + } + select { + case batch := <-received: + if len(batch.Events) != 1 || batch.Events[0].Properties["invocation_channel"] != "mcp" { + t.Fatalf("unexpected MCP batch: %+v", batch) + } + case <-time.After(2 * time.Second): + t.Fatal("MCP batch not delivered") + } + // The request is still open in this process, so the drain must time out. + if drainAnalyticsSends(50 * time.Millisecond) { + t.Fatal("MCP delivery did not run in process") + } + close(release) + if !drainAnalyticsSends(2 * time.Second) { + t.Fatal("in-process MCP delivery did not finish") + } +} diff --git a/internal/cli/analytics_sender.go b/internal/cli/analytics_sender.go index d11b523..a0ca1d2 100644 --- a/internal/cli/analytics_sender.go +++ b/internal/cli/analytics_sender.go @@ -9,6 +9,7 @@ import ( "os/exec" "slices" "strings" + "sync" "time" ) @@ -16,6 +17,10 @@ const analyticsSenderCommand = "__telemetry-send" const analyticsRequestLimit = 64 * 1024 const analyticsHandoffTimeout = 100 * time.Millisecond +// analyticsMCPDrainTimeout bounds how long `mcp serve` waits for in-flight +// usage batches after the host closes stdin. +const analyticsMCPDrainTimeout = time.Second + type analyticsBatch struct { Events []analyticsEvent `json:"events"` } @@ -45,10 +50,29 @@ func (op *analyticsOperation) submit(event analyticsEvent) { op.events = append(op.events, json.RawMessage(body)) } +// flush hands the finished operation's batch to a sender. Shell commands +// exit right after finishing, so they hand off to a detached subprocess that +// outlives them. `mcp serve` is long-lived, so it sends from a goroutine in +// process instead of spawning one subprocess per tool call. Both paths use +// sendAnalyticsBatch, so validation, limits and the HTTP client are shared. func (op *analyticsOperation) flush() { - if len(op.events) == 0 { + body := op.batchBody() + if body == nil { + return + } + if op.channel == "mcp" { + sendAnalyticsInBackground(body, op.endpoint) return } + spawnAnalyticsSender(body, op.endpoint) +} + +// batchBody returns the serialized batch for the finished operation, or nil +// when there is nothing valid to send. It clears the buffered events. +func (op *analyticsOperation) batchBody() []byte { + if len(op.events) == 0 { + return nil + } events := op.events if start := op.initStarted; start != nil { // The start keeps its original timestamp. Only source attribution can @@ -59,11 +83,13 @@ func (op *analyticsOperation) flush() { } } if !validAnalyticsEvent(*start) { - return + op.events = nil + return nil } first, err := json.Marshal(start) if err != nil { - return + op.events = nil + return nil } events = append([]json.RawMessage{first}, events...) } @@ -72,13 +98,45 @@ func (op *analyticsOperation) flush() { }{Events: events}) op.events = nil if err != nil || len(body) > analyticsRequestLimit { - return + return nil } + return body +} + +// analyticsInFlight tracks in-process MCP sends so `mcp serve` can give them +// a short, bounded chance to finish when the host closes stdin. +var analyticsInFlight sync.WaitGroup + +func sendAnalyticsInBackground(body []byte, endpoint string) { + analyticsInFlight.Add(1) + go func() { + defer analyticsInFlight.Done() + sendAnalyticsBatch(bytes.NewReader(body), endpoint) + }() +} + +// drainAnalyticsSends waits up to timeout for in-process sends to finish and +// reports whether they all did. Requests still running are abandoned when the +// process exits. +func drainAnalyticsSends(timeout time.Duration) bool { + done := make(chan struct{}) + go func() { analyticsInFlight.Wait(); close(done) }() + timer := time.NewTimer(timeout) + defer timer.Stop() + select { + case <-done: + return true + case <-timer.C: + return false + } +} + +func spawnAnalyticsSender(body []byte, endpoint string) { executable, err := os.Executable() if err != nil { return } - cmd := exec.Command(executable, analyticsSenderCommand, op.endpoint) + cmd := exec.Command(executable, analyticsSenderCommand, endpoint) detachAnalyticsProcess(cmd) cmd.Env = analyticsSenderEnv() pipe, err := cmd.StdinPipe() diff --git a/internal/cli/mcp.go b/internal/cli/mcp.go index 9ee1f7d..14a13a7 100644 --- a/internal/cli/mcp.go +++ b/internal/cli/mcp.go @@ -95,6 +95,9 @@ Notes for agents: } func (a *App) serveMCP(in io.Reader, out io.Writer) error { + // Usage batches are sent in process for MCP; give the last ones a short, + // bounded chance to complete once the host closes the transport. + defer drainAnalyticsSends(analyticsMCPDrainTimeout) scanner := bufio.NewScanner(in) // Default Scanner has a 64 KiB line cap. Larger payloads (a quickstart // create with custom args, a doctor result echoed back to the client) From fd50bc3c06330ed212dfff4a7d8f3486c9ddfbe4 Mon Sep 17 00:00:00 2001 From: Hermes Frangoudis Date: Fri, 20 Nov 2026 12:30:22 -0500 Subject: [PATCH 5/9] fix(telemetry): report project create failures before the API call 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 --- internal/cli/analytics.go | 9 +++++- internal/cli/analytics_test.go | 58 ++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/internal/cli/analytics.go b/internal/cli/analytics.go index 0b94071..13466a8 100644 --- a/internal/cli/analytics.go +++ b/internal/cli/analytics.go @@ -88,6 +88,9 @@ type analyticsOperation struct { events []json.RawMessage batchBytes int endpoint string + // projectCreateReported is set once the createProject API boundary has + // emitted cli_project_create_completed for this operation. + projectCreateReported bool } type analyticsContextKey struct{} @@ -323,7 +326,10 @@ func (op *analyticsOperation) finish(err error) { if op.command == "init" && failedStage != "" { fields["failed_stage"] = failedStage } - if op.command != "project create" { + // `project create` normally reports at the API boundary (projectCreated) + // so its timing excludes later feature work. A failure before that call + // (not logged in, unreadable context, invalid flags) reports here instead. + if op.command != "project create" || !op.projectCreateReported { op.emit(event, fields) } op.flush() @@ -411,4 +417,5 @@ func (op *analyticsOperation) projectCreated(id string, started time.Time, err e exit = exitCodeForError(err) } op.emit("cli_project_create_completed", map[string]any{"outcome": outcome, "error_code": code, "duration_ms": time.Since(started).Milliseconds(), "exit_code": exit}) + op.projectCreateReported = true } diff --git a/internal/cli/analytics_test.go b/internal/cli/analytics_test.go index cbf467f..47178f2 100644 --- a/internal/cli/analytics_test.go +++ b/internal/cli/analytics_test.go @@ -330,3 +330,61 @@ func TestAnalyticsWebIdentityInputsRemoved(t *testing.T) { } } } + +func TestAnalyticsProjectCreateFailureBeforeAPIIsReported(t *testing.T) { + for _, tc := range []struct { + name string + channel string + args []string + mcpArgs map[string]any + setup func(t *testing.T, a *App) + }{ + {name: "invalid feature", channel: "shell", args: []string{"project", "create", "demo", "--feature", "bogus", "--json"}}, + {name: "invalid rtm data center", channel: "shell", args: []string{"project", "create", "demo", "--rtm-data-center", "XX", "--json"}}, + {name: "unreadable context", channel: "shell", args: []string{"project", "create", "demo", "--json"}, setup: func(t *testing.T, a *App) { + path, err := resolveContextFilePath(a.env) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("{invalid"), 0o600); err != nil { + t.Fatal(err) + } + }}, + {name: "missing name", channel: "mcp", mcpArgs: map[string]any{}}, + } { + t.Run(tc.channel+"/"+tc.name, func(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + if tc.setup != nil { + tc.setup(t, a) + } + var err error + if tc.channel == "shell" { + a.root = a.buildRoot() + a.root.SetOut(io.Discard) + a.root.SetErr(io.Discard) + a.root.SetArgs(tc.args) + err = a.root.Execute() + } else { + _, err = a.callMCPTool("agora.project.create", tc.mcpArgs, nil) + } + if err == nil { + t.Fatal("fixture must fail before the create API call") + } + events := waitAnalyticsEvents(t, read, 1) + // Give a duplicate a chance to arrive before asserting exactly one. + time.Sleep(50 * time.Millisecond) + events = read() + if len(events) != 1 { + t.Fatalf("want exactly one event, got %+v", events) + } + p := events[0].Properties + if events[0].Event != "cli_project_create_completed" || p["outcome"] != "failure" || p["error_code"] == "" || p["exit_code"] == float64(0) || p["invocation_channel"] != tc.channel || p["app_id"] != nil { + t.Fatalf("unexpected pre-API failure event: %+v", events[0]) + } + }) + } +} From 68c430bbb7b184e727469d43ea4d55667682447e Mon Sep 17 00:00:00 2001 From: Hermes Frangoudis Date: Fri, 20 Nov 2026 12:30:29 -0500 Subject: [PATCH 6/9] fix(telemetry): reserve init start event in batch size accounting 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 --- internal/cli/analytics.go | 8 +++++ internal/cli/analytics_send_test.go | 47 +++++++++++++++++++++++++++++ internal/cli/analytics_sender.go | 12 ++++++-- 3 files changed, 64 insertions(+), 3 deletions(-) diff --git a/internal/cli/analytics.go b/internal/cli/analytics.go index 13466a8..980bc29 100644 --- a/internal/cli/analytics.go +++ b/internal/cli/analytics.go @@ -218,9 +218,17 @@ func (a *App) beginAnalytics(command, channel string) *analyticsOperation { return nil } op := &analyticsOperation{command: command, channel: channel, id: analyticsUUID(), distinctID: id, properties: props, started: time.Now(), endpoint: endpoint} + op.batchBytes = len(analyticsBatchEnvelope) if command == "init" { event := op.newEvent("cli_init_started", nil) + start, err := json.Marshal(event) + if err != nil { + return nil + } op.initStarted = &event + // flush prepends this event after copying source attribution onto it, + // so reserve its worst-case size (plus the separating comma) up front. + op.batchBytes += len(start) + analyticsStartAttributionReserve + 1 op.beginStage(analyticsStageValidate) } return op diff --git a/internal/cli/analytics_send_test.go b/internal/cli/analytics_send_test.go index 7ff3ba9..5d22898 100644 --- a/internal/cli/analytics_send_test.go +++ b/internal/cli/analytics_send_test.go @@ -204,6 +204,53 @@ func TestAnalyticsStalledTLSBoundsShellAndMCPCompletion(t *testing.T) { } } +func TestAnalyticsBatchAccountingIncludesInitStart(t *testing.T) { + received := make(chan int, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var batch analyticsBatch + if err := json.NewDecoder(r.Body).Decode(&batch); err != nil { + t.Error(err) + } + received <- len(batch.Events) + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + a := analyticsTestApp(t, server.URL) + op := a.beginAnalytics("init", "mcp") + // Attribution is copied onto cli_init_started only at flush; use the + // longest allowed values so the start grows as much as possible. + op.source("recipe", strings.Repeat("a", 100)) + op.stage = "" + accepted := 0 + for { + event := op.newEvent("cli_init_stage_completed", map[string]any{"stage": analyticsStageClone, "outcome": "success", "error_code": "", "duration_ms": 1}) + body, err := json.Marshal(event) + if err != nil { + t.Fatal(err) + } + if op.batchBytes+1+len(body) > analyticsRequestLimit { + break + } + op.submit(event) + accepted++ + } + if len(op.events) != accepted || op.batchBytes > analyticsRequestLimit { + t.Fatalf("accounting rejected an event below the limit: accepted=%d kept=%d bytes=%d", accepted, len(op.events), op.batchBytes) + } + op.flush() + select { + case n := <-received: + if n != accepted+1 { + t.Fatalf("want start plus %d events, got %d", accepted, n) + } + case <-time.After(2 * time.Second): + t.Fatal("batch accepted by accounting was dropped at flush") + } + if !drainAnalyticsSends(2 * time.Second) { + t.Fatal("send did not finish") + } +} + func TestAnalyticsMCPSendsInProcessWithoutBlocking(t *testing.T) { received := make(chan analyticsBatch, 1) release := make(chan struct{}) diff --git a/internal/cli/analytics_sender.go b/internal/cli/analytics_sender.go index a0ca1d2..bf33290 100644 --- a/internal/cli/analytics_sender.go +++ b/internal/cli/analytics_sender.go @@ -21,6 +21,13 @@ const analyticsHandoffTimeout = 100 * time.Millisecond // usage batches after the host closes stdin. const analyticsMCPDrainTimeout = time.Second +const analyticsBatchEnvelope = `{"events":[]}` + +// analyticsStartAttributionReserve is the largest JSON growth of +// cli_init_started when flush copies source attribution onto it: the longest +// source_type value plus source_id and recipe_id at their 100-byte maximum. +var analyticsStartAttributionReserve = len(`,"source_type":"quickstart","source_id":"` + strings.Repeat("x", 100) + `","recipe_id":"` + strings.Repeat("x", 100) + `"`) + type analyticsBatch struct { Events []analyticsEvent `json:"events"` } @@ -33,10 +40,9 @@ func (op *analyticsOperation) submit(event analyticsEvent) { if err != nil { return } + // batchBytes starts at the envelope plus any reserved cli_init_started + // event, so an accepted event always fits once flush prepends the start. size := op.batchBytes - if size == 0 { - size = len(`{"events":[]}`) - } if len(op.events) > 0 { size++ // comma between events } From 32f4494af70956b3490bd4dc8c16f8564bb37658 Mon Sep 17 00:00:00 2001 From: Hermes Frangoudis Date: Fri, 20 Nov 2026 12:30:29 -0500 Subject: [PATCH 7/9] docs(telemetry): state project create reporting semantics Co-Authored-By: Claude Opus 5.5 --- docs/telemetry.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/telemetry.md b/docs/telemetry.md index 7920c13..0b03fc4 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -22,6 +22,14 @@ fails. Only attempts with a confirmed public catalog entry include a Recipe ID. When reporting per-Recipe results, show unconfirmed attempts separately. An existing target directory is reported as a local validation failure. +Project creation (`agora project create`, and the project step of `agora init`) +is reported when the create API call returns, and its duration covers only that +call. A project that is created successfully is recorded as a success even if a +later step, such as enabling features, fails; the outer command result still +reports that failure. A `project create` that fails before reaching the API +(for example, invalid flags or an unreadable local context) is reported as a +failure when the command finishes. + ## Delivery Each instrumented shell command collects its events in memory and flushes them From df5254a5d66b5a04177c44b780df8f3a6c0a4e4b Mon Sep 17 00:00:00 2001 From: Hermes Frangoudis Date: Fri, 20 Nov 2026 12:32:01 -0500 Subject: [PATCH 8/9] test(telemetry): consolidate analytics tests by concern 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 --- internal/cli/analytics_final_test.go | 416 ---------------------- internal/cli/analytics_regression_test.go | 152 -------- internal/cli/analytics_send_test.go | 232 ++++++++++++ internal/cli/analytics_test.go | 333 +++++++++++++++++ 4 files changed, 565 insertions(+), 568 deletions(-) delete mode 100644 internal/cli/analytics_final_test.go delete mode 100644 internal/cli/analytics_regression_test.go diff --git a/internal/cli/analytics_final_test.go b/internal/cli/analytics_final_test.go deleted file mode 100644 index 051b0b4..0000000 --- a/internal/cli/analytics_final_test.go +++ /dev/null @@ -1,416 +0,0 @@ -package cli - -import ( - "bytes" - "context" - "encoding/json" - "io" - "net/http" - "net/http/httptest" - "os" - "os/exec" - "path/filepath" - "strings" - "sync/atomic" - "testing" - "time" -) - -const testTelemetryAppID = "0123456789abcdef0123456789abcdef" - -func TestAnalyticsCreationSurvivesLaterFailure(t *testing.T) { - for _, channel := range []string{"shell", "mcp"} { - for _, source := range []string{"project create", "quickstart", "recipe"} { - for _, failure := range []string{"features", "query"} { - t.Run(channel+"/"+source+"/"+failure, func(t *testing.T) { - collector, read := analyticsRecorder(t) - a := analyticsTestApp(t, collector.URL) - var creates atomic.Int32 - backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method == "POST" && r.URL.Path == "/api/cli/v1/projects" { - creates.Add(1) - time.Sleep(25 * time.Millisecond) - _ = json.NewEncoder(w).Encode(projectDetail{AppID: testTelemetryAppID, ProjectID: "prj_created", Name: "private-project"}) - return - } - if failure == "features" { - time.Sleep(120 * time.Millisecond) - } - w.WriteHeader(http.StatusServiceUnavailable) - _, _ = w.Write([]byte(`{"message":"private failure"}`)) - })) - defer backend.Close() - a.env["AGORA_API_BASE_URL"] = backend.URL - a.osEnv["AGORA_API_BASE_URL"] = backend.URL - if err := saveSession(a.env, session{AccessToken: "secret", TokenType: "Bearer", ExpiresAt: time.Now().Add(time.Hour).Format(time.RFC3339)}); err != nil { - t.Fatal(err) - } - command := "init" - if source == "project create" { - command = source - } - op := a.beginAnalytics(command, channel) - features := []string{"rtc"} - if failure == "features" { - features = []string{"rtm"} - } - var err error - if command == "project create" { - _, err = a.projectCreate("private-project", "", features, "", "", op) - } else { - target := filepath.Join(t.TempDir(), "demo") - if source == "quickstart" { - template, selectErr := selectQuickstartDefinition("nextjs", "video-call") - if selectErr != nil { - t.Fatal(selectErr) - } - _, err = a.initProject("private-project", target, template, "", features, "", true, false, io.Discard, strings.NewReader(""), nil, op) - } else { - recipe := recipeDetail{recipeSummary: recipeSummary{Slug: "test-source"}, CLI: &recipeCLIConfig{ProjectType: "python", Env: recipeCLIEnv{ExamplePath: ".env.example", TargetPath: ".env", AppIDKey: "AGORA_APP_ID", AppCertificateKey: "AGORA_APP_CERTIFICATE"}}} - _, err = a.initRecipeProject("private-project", target, recipe, "", features, "", true, false, io.Discard, strings.NewReader(""), nil, op) - } - } - if command == "init" && err == nil { - t.Fatal("fixture must fail after creation") - } - op.finish(err) - events := waitAnalyticsEvents(t, read, 1) - var creation *analyticsEvent - for i := range events { - e := &events[i] - if e.Event == "cli_project_create_completed" { - if creation != nil { - t.Fatal("duplicate creation") - } - creation = e - } - if e.Event == "cli_init_started" && e.Properties["app_id"] != nil { - t.Fatal("backfilled early event") - } - if e.Event == "cli_init_completed" && (e.Properties["outcome"] != "failure" || e.Properties["app_id"] != testTelemetryAppID) { - t.Fatalf("lost outer failure/App ID: %+v", e) - } - } - if creates.Load() != 1 || creation == nil || creation.Properties["outcome"] != "success" || creation.Properties["exit_code"] != float64(0) || creation.Properties["app_id"] != testTelemetryAppID { - t.Fatalf("wrong creation %+v", events) - } - duration := creation.Properties["duration_ms"].(float64) - if duration < 20 || duration > 115 { - t.Fatalf("creation timing includes later feature work: %v", duration) - } - }) - } - } - } -} - -func TestAnalyticsCreationAuthFailureAndInvalidAppID(t *testing.T) { - collector, read := analyticsRecorder(t) - a := analyticsTestApp(t, collector.URL) - a.env["AGORA_OUTPUT"] = "json" - op := a.beginAnalytics("project create", "mcp") - if _, err := a.createProject("private", "", op); err == nil { - t.Fatal("expected auth failure") - } - op.finish(nil) - events := waitAnalyticsEvents(t, read, 1) - if len(events) != 1 || events[0].Properties["outcome"] != "failure" || events[0].Properties["app_id"] != nil { - t.Fatal(events) - } - for _, id := range []string{"private name", "app_0001", "", "secret-token"} { - op.setAppID(id) - } - if op.properties["app_id"] != nil { - t.Fatal("accepted free text app ID") - } -} - -func TestAnalyticsBatchIsDeferredUntilFinish(t *testing.T) { - var calls atomic.Int32 - received := make(chan []analyticsEvent, 1) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var batch analyticsBatch - if err := json.NewDecoder(r.Body).Decode(&batch); err != nil { - t.Error(err) - return - } - calls.Add(1) - received <- batch.Events - // All lifecycle events arrive together, even with a slow acknowledgement. - time.Sleep(600 * time.Millisecond) - w.WriteHeader(http.StatusAccepted) - })) - defer server.Close() - a := analyticsTestApp(t, server.URL) - op := a.beginAnalytics("init", "shell") - for _, stage := range []string{"source_resolve", "project_resolve", "clone", "env_write", "binding_write", "context_write"} { - op.beginStage(stage) - } - if calls.Load() != 0 { - t.Fatal("sent before operation finished") - } - started := time.Now() - op.finish(nil) - if time.Since(started) > 500*time.Millisecond { - t.Fatal("finish waited for network") - } - select { - case events := <-received: - if len(events) != 9 || events[0].Event != "cli_init_started" || events[len(events)-1].Event != "cli_init_completed" { - t.Fatalf("missing batch lifecycle: %+v", events) - } - case <-time.After(2 * time.Second): - t.Fatal("batch missing") - } - if calls.Load() != 1 { - t.Fatal("operation sent multiple requests") - } -} - -func TestAnalyticsBatchHandoffAndSizeBound(t *testing.T) { - reader, writer := io.Pipe() - defer func() { _ = reader.Close() }() - started := time.Now() - handoffAnalyticsBatch(writer, []byte(`{"events":[]}`)) - if time.Since(started) > 500*time.Millisecond { - t.Fatal("blocked on non-reading pipe") - } - if _, err := writer.Write([]byte("x")); err == nil { - t.Fatal("timed-out pipe remained open") - } - - server, read := analyticsRecorder(t) - a := analyticsTestApp(t, server.URL) - op := a.beginAnalytics("recipes list", "shell") - for range 1000 { - op.emit("cli_recipes_list_completed", nil) - } - if op.batchBytes <= analyticsRequestLimit || len(op.events) != 0 { - t.Fatal("oversized batch was retained") - } - op.finish(nil) - if len(read()) != 0 { - t.Fatal("sent a partial oversized operation") - } -} - -func TestAnalyticsBatchRejectsMalformedOrPrivateInput(t *testing.T) { - server, read := analyticsRecorder(t) - a := analyticsTestApp(t, server.URL) - op := a.beginAnalytics("recipes list", "shell") - event := analyticsEvent{Event: "cli_recipes_list_completed", EventID: analyticsUUID(), OperationID: op.id, DistinctID: op.distinctID, Timestamp: time.Now().UTC(), Properties: op.properties} - body, _ := json.Marshal(analyticsBatch{Events: []analyticsEvent{event}}) - private := bytes.Replace(body, []byte(`"properties":{`), []byte(`"properties":{"token":"private",`), 1) - for _, input := range [][]byte{private, append(bytes.Clone(body), []byte(` {}`)...), []byte(`{"events":[]}`), []byte(`{"events":null}`), []byte(`{"unknown":true,"events":[]}`), []byte(strings.Repeat(" ", analyticsRequestLimit+1)), body[:len(body)-1]} { - sendAnalyticsBatch(bytes.NewReader(input), server.URL) - } - if len(read()) != 0 { - t.Fatal("invalid batch was sent") - } - events := make([]analyticsEvent, 21) - for i := range events { - events[i] = event - events[i].EventID = analyticsUUID() - } - body, _ = json.Marshal(analyticsBatch{Events: events}) - sendAnalyticsBatch(bytes.NewReader(append([]byte(strings.Repeat(" ", 5000)), body...)), server.URL) - if len(read()) != 21 { - t.Fatalf("valid batch was not sent: %d", len(read())) - } -} - -func TestAnalyticsMCPBatchesDoNotDropWhileOtherSendersWait(t *testing.T) { - received := make(chan string, 3) - release := make(chan struct{}) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var batch analyticsBatch - if err := json.NewDecoder(r.Body).Decode(&batch); err != nil { - t.Error(err) - return - } - if len(batch.Events) != 3 { - t.Errorf("unexpected lifecycle length: %d", len(batch.Events)) - } - received <- batch.Events[0].OperationID - <-release - w.WriteHeader(http.StatusAccepted) - })) - defer server.Close() - defer close(release) - a := analyticsTestApp(t, server.URL) - for range 3 { - if _, err := a.callMCPTool("agora.init", map[string]any{}, nil); err == nil { - t.Fatal("missing name must fail") - } - } - ids := map[string]bool{} - for range 3 { - select { - case id := <-received: - ids[id] = true - case <-time.After(2 * time.Second): - t.Fatal("MCP batch dropped while previous senders were waiting") - } - } - if len(ids) != 3 { - t.Fatal("MCP operation identities were shared") - } -} - -func TestAnalyticsSenderSurvivesParentExit(t *testing.T) { - received := make(chan analyticsEvent, 4) - allowResponse := make(chan struct{}, 1) - var calls atomic.Int32 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var body struct { - Events []analyticsEvent `json:"events"` - } - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - t.Error(err) - return - } - for _, e := range body.Events { - received <- e - } - if calls.Add(1) == 1 { - <-allowResponse - } - w.WriteHeader(http.StatusAccepted) - })) - defer server.Close() - defer func() { - select { - case allowResponse <- struct{}{}: - default: - } - }() - home := t.TempDir() - executable, err := os.Executable() - if err != nil { - t.Fatal(err) - } - cmd := exec.Command(executable) - cmd.Env = append(os.Environ(), "GO_WANT_CLI_HELPER_PROCESS=1", `GO_CLI_HELPER_ARGS_JSON=["init","local-only","--template","invalid","--json"]`, "AGORA_HOME="+home, "AGORA_TELEMETRY_URL="+server.URL, "AGORA_SENTRY_ENABLED=1", "AGORA_TELEMETRY_ENABLED=1", "DO_NOT_TRACK=") - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - defer cancel() - done := make(chan error, 1) - go func() { _, err := cmd.CombinedOutput(); done <- err }() - select { - case <-done: - case <-ctx.Done(): - if cmd.Process != nil { - _ = cmd.Process.Kill() - } - t.Fatal("child retained output handles") - } - // The parent exits while the child waits for the batch response. - allowResponse <- struct{}{} - events := make([]analyticsEvent, 0, 4) - for range 4 { - select { - case e := <-received: - events = append(events, e) - case <-time.After(2 * time.Second): - t.Fatal("child did not finish after parent exit") - } - } - if events[0].Event != "cli_init_started" || events[3].Event != "cli_init_completed" { - t.Fatalf("missing detached lifecycle: %+v", events) - } - if _, err := os.Stat(filepath.Join(home, "telemetry-notice-shown")); err != nil { - t.Fatal(err) - } -} - -func TestAnalyticsCreationTimingIncludesRefreshAndRetry(t *testing.T) { - collector, read := analyticsRecorder(t) - a := analyticsTestApp(t, collector.URL) - var requests, refreshes atomic.Int32 - backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - time.Sleep(30 * time.Millisecond) - if r.URL.Path == "/api/v0/oauth/token" { - refreshes.Add(1) - _, _ = w.Write([]byte(`{"access_token":"local","token_type":"Bearer","expires_in":3600,"refresh_token":"local","scope":"basic_info,console"}`)) - return - } - if requests.Add(1) == 1 { - w.WriteHeader(http.StatusUnauthorized) - return - } - _ = json.NewEncoder(w).Encode(projectDetail{AppID: testTelemetryAppID}) - })) - defer backend.Close() - a.osEnv["AGORA_API_BASE_URL"] = backend.URL - a.osEnv["AGORA_OAUTH_BASE_URL"] = backend.URL - if err := saveSession(a.env, session{AccessToken: "local", RefreshToken: "local", TokenType: "Bearer", ExpiresAt: time.Now().Add(-time.Hour).Format(time.RFC3339)}); err != nil { - t.Fatal(err) - } - op := a.beginAnalytics("project create", "shell") - _, err := a.createProject("local", "", op) - op.finish(err) - if err != nil { - t.Fatal(err) - } - events := waitAnalyticsEvents(t, read, 1) - if len(events) != 1 || requests.Load() != 2 || refreshes.Load() != 2 || events[0].Properties["duration_ms"].(float64) < 110 { - t.Fatalf("refresh/retry not in shared boundary: %+v requests=%d refreshes=%d", events, requests.Load(), refreshes.Load()) - } -} - -func TestAnalyticsCLIStartupAndMCPReadFailure(t *testing.T) { - for _, invalid := range []string{"{invalid", "null", `{"telemetryEnabled":null}`, `{"telemetryEnabled":"true"}`} { - t.Run(invalid, func(t *testing.T) { - server, read := analyticsRecorder(t) - a := analyticsTestApp(t, server.URL) - state, err := ensureAppConfigState(a.env) - if err != nil { - t.Fatal(err) - } - a.cfgState = state - if err := os.WriteFile(state.ConfigFilePath, []byte(invalid), 0o600); err != nil { - t.Fatal(err) - } - if op := a.beginAnalytics("recipes list", "mcp"); op != nil { - op.finish(nil) - t.Fatal("MCP used unreadable preference") - } - // Normal CLI deliberately retains the startup policy despite later edits. - op := a.beginAnalytics("recipes list", "shell") - if op == nil { - t.Fatal("CLI re-read startup preference") - } - op.finish(nil) - waitAnalyticsEvents(t, read, 1) - }) - } -} - -func TestAnalyticsBatchRequestTimeout(t *testing.T) { - received := make(chan struct{}) - release := make(chan struct{}) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _, _ = io.Copy(io.Discard, r.Body) - close(received) - <-release - })) - defer server.Close() - defer close(release) - event := analyticsEvent{Event: "cli_recipes_list_completed", EventID: analyticsUUID(), OperationID: analyticsUUID(), DistinctID: "cli:" + analyticsUUID(), Timestamp: time.Now().UTC(), Properties: map[string]any{"command": "recipes list"}} - body, _ := json.Marshal(analyticsBatch{Events: []analyticsEvent{event}}) - done := make(chan struct{}) - started := time.Now() - go func() { sendAnalyticsBatch(bytes.NewReader(body), server.URL); close(done) }() - select { - case <-received: - case <-time.After(2 * time.Second): - t.Fatal("batch request missing") - } - select { - case <-done: - case <-time.After(12 * time.Second): - t.Fatal("request exceeded ten-second timeout") - } - if time.Since(started) < 9*time.Second { - t.Fatal("request timed out before the configured ten-second budget") - } -} diff --git a/internal/cli/analytics_regression_test.go b/internal/cli/analytics_regression_test.go deleted file mode 100644 index 17ec7cf..0000000 --- a/internal/cli/analytics_regression_test.go +++ /dev/null @@ -1,152 +0,0 @@ -package cli - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/http/httptest" - "net/url" - "os" - "strconv" - "testing" -) - -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(waitAnalyticsEvents(t, read, 3)) - 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 TestAnalyticsPolicySnapshotForRunningOperation(t *testing.T) { - server, read := analyticsRecorder(t) - a := analyticsTestApp(t, server.URL) - state, err := ensureAppConfigState(a.env) - if err != nil { - t.Fatal(err) - } - op := a.beginAnalytics("init", "mcp") - cfg := state.Config - cfg.TelemetryEnabled = false - if err := writeSecureJSON(state.ConfigFilePath, cfg); err != nil { - t.Fatal(err) - } - op.beginStage("clone") - op.finish(nil) - events := waitAnalyticsEvents(t, read, 4) - if len(events) != 4 { - t.Fatalf("running operation changed snapshot: %+v", events) - } -} - -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 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 := waitAnalyticsEvents(t, read, 1) - 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 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.telemetryAllowed(a.currentTelemetryPreference()) != !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.beginAnalytics("recipes list", "mcp") != nil { - t.Fatal("unreadable preference must fail closed") - } - }) - } -} diff --git a/internal/cli/analytics_send_test.go b/internal/cli/analytics_send_test.go index 5d22898..33a046a 100644 --- a/internal/cli/analytics_send_test.go +++ b/internal/cli/analytics_send_test.go @@ -1,12 +1,17 @@ package cli import ( + "bytes" + "context" "encoding/json" "errors" "io" "net" "net/http" "net/http/httptest" + "os" + "os/exec" + "path/filepath" "runtime" "strings" "sync/atomic" @@ -292,3 +297,230 @@ func TestAnalyticsMCPSendsInProcessWithoutBlocking(t *testing.T) { t.Fatal("in-process MCP delivery did not finish") } } + +func TestAnalyticsBatchIsDeferredUntilFinish(t *testing.T) { + var calls atomic.Int32 + received := make(chan []analyticsEvent, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var batch analyticsBatch + if err := json.NewDecoder(r.Body).Decode(&batch); err != nil { + t.Error(err) + return + } + calls.Add(1) + received <- batch.Events + // All lifecycle events arrive together, even with a slow acknowledgement. + time.Sleep(600 * time.Millisecond) + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + a := analyticsTestApp(t, server.URL) + op := a.beginAnalytics("init", "shell") + for _, stage := range []string{"source_resolve", "project_resolve", "clone", "env_write", "binding_write", "context_write"} { + op.beginStage(stage) + } + if calls.Load() != 0 { + t.Fatal("sent before operation finished") + } + started := time.Now() + op.finish(nil) + if time.Since(started) > 500*time.Millisecond { + t.Fatal("finish waited for network") + } + select { + case events := <-received: + if len(events) != 9 || events[0].Event != "cli_init_started" || events[len(events)-1].Event != "cli_init_completed" { + t.Fatalf("missing batch lifecycle: %+v", events) + } + case <-time.After(2 * time.Second): + t.Fatal("batch missing") + } + if calls.Load() != 1 { + t.Fatal("operation sent multiple requests") + } +} + +func TestAnalyticsBatchHandoffAndSizeBound(t *testing.T) { + reader, writer := io.Pipe() + defer func() { _ = reader.Close() }() + started := time.Now() + handoffAnalyticsBatch(writer, []byte(`{"events":[]}`)) + if time.Since(started) > 500*time.Millisecond { + t.Fatal("blocked on non-reading pipe") + } + if _, err := writer.Write([]byte("x")); err == nil { + t.Fatal("timed-out pipe remained open") + } + + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + op := a.beginAnalytics("recipes list", "shell") + for range 1000 { + op.emit("cli_recipes_list_completed", nil) + } + if op.batchBytes <= analyticsRequestLimit || len(op.events) != 0 { + t.Fatal("oversized batch was retained") + } + op.finish(nil) + if len(read()) != 0 { + t.Fatal("sent a partial oversized operation") + } +} + +func TestAnalyticsBatchRejectsMalformedOrPrivateInput(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + op := a.beginAnalytics("recipes list", "shell") + event := analyticsEvent{Event: "cli_recipes_list_completed", EventID: analyticsUUID(), OperationID: op.id, DistinctID: op.distinctID, Timestamp: time.Now().UTC(), Properties: op.properties} + body, _ := json.Marshal(analyticsBatch{Events: []analyticsEvent{event}}) + private := bytes.Replace(body, []byte(`"properties":{`), []byte(`"properties":{"token":"private",`), 1) + for _, input := range [][]byte{private, append(bytes.Clone(body), []byte(` {}`)...), []byte(`{"events":[]}`), []byte(`{"events":null}`), []byte(`{"unknown":true,"events":[]}`), []byte(strings.Repeat(" ", analyticsRequestLimit+1)), body[:len(body)-1]} { + sendAnalyticsBatch(bytes.NewReader(input), server.URL) + } + if len(read()) != 0 { + t.Fatal("invalid batch was sent") + } + events := make([]analyticsEvent, 21) + for i := range events { + events[i] = event + events[i].EventID = analyticsUUID() + } + body, _ = json.Marshal(analyticsBatch{Events: events}) + sendAnalyticsBatch(bytes.NewReader(append([]byte(strings.Repeat(" ", 5000)), body...)), server.URL) + if len(read()) != 21 { + t.Fatalf("valid batch was not sent: %d", len(read())) + } +} + +func TestAnalyticsMCPBatchesDoNotDropWhileOtherSendersWait(t *testing.T) { + received := make(chan string, 3) + release := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var batch analyticsBatch + if err := json.NewDecoder(r.Body).Decode(&batch); err != nil { + t.Error(err) + return + } + if len(batch.Events) != 3 { + t.Errorf("unexpected lifecycle length: %d", len(batch.Events)) + } + received <- batch.Events[0].OperationID + <-release + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + defer close(release) + a := analyticsTestApp(t, server.URL) + for range 3 { + if _, err := a.callMCPTool("agora.init", map[string]any{}, nil); err == nil { + t.Fatal("missing name must fail") + } + } + ids := map[string]bool{} + for range 3 { + select { + case id := <-received: + ids[id] = true + case <-time.After(2 * time.Second): + t.Fatal("MCP batch dropped while previous senders were waiting") + } + } + if len(ids) != 3 { + t.Fatal("MCP operation identities were shared") + } +} + +func TestAnalyticsSenderSurvivesParentExit(t *testing.T) { + received := make(chan analyticsEvent, 4) + allowResponse := make(chan struct{}, 1) + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body struct { + Events []analyticsEvent `json:"events"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + return + } + for _, e := range body.Events { + received <- e + } + if calls.Add(1) == 1 { + <-allowResponse + } + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + defer func() { + select { + case allowResponse <- struct{}{}: + default: + } + }() + home := t.TempDir() + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(executable) + cmd.Env = append(os.Environ(), "GO_WANT_CLI_HELPER_PROCESS=1", `GO_CLI_HELPER_ARGS_JSON=["init","local-only","--template","invalid","--json"]`, "AGORA_HOME="+home, "AGORA_TELEMETRY_URL="+server.URL, "AGORA_SENTRY_ENABLED=1", "AGORA_TELEMETRY_ENABLED=1", "DO_NOT_TRACK=") + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { _, err := cmd.CombinedOutput(); done <- err }() + select { + case <-done: + case <-ctx.Done(): + if cmd.Process != nil { + _ = cmd.Process.Kill() + } + t.Fatal("child retained output handles") + } + // The parent exits while the child waits for the batch response. + allowResponse <- struct{}{} + events := make([]analyticsEvent, 0, 4) + for range 4 { + select { + case e := <-received: + events = append(events, e) + case <-time.After(2 * time.Second): + t.Fatal("child did not finish after parent exit") + } + } + if events[0].Event != "cli_init_started" || events[3].Event != "cli_init_completed" { + t.Fatalf("missing detached lifecycle: %+v", events) + } + if _, err := os.Stat(filepath.Join(home, "telemetry-notice-shown")); err != nil { + t.Fatal(err) + } +} + +func TestAnalyticsBatchRequestTimeout(t *testing.T) { + received := make(chan struct{}) + release := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + close(received) + <-release + })) + defer server.Close() + defer close(release) + event := analyticsEvent{Event: "cli_recipes_list_completed", EventID: analyticsUUID(), OperationID: analyticsUUID(), DistinctID: "cli:" + analyticsUUID(), Timestamp: time.Now().UTC(), Properties: map[string]any{"command": "recipes list"}} + body, _ := json.Marshal(analyticsBatch{Events: []analyticsEvent{event}}) + done := make(chan struct{}) + started := time.Now() + go func() { sendAnalyticsBatch(bytes.NewReader(body), server.URL); close(done) }() + select { + case <-received: + case <-time.After(2 * time.Second): + t.Fatal("batch request missing") + } + select { + case <-done: + case <-time.After(12 * time.Second): + t.Fatal("request exceeded ten-second timeout") + } + if time.Since(started) < 9*time.Second { + t.Fatal("request timed out before the configured ten-second budget") + } +} diff --git a/internal/cli/analytics_test.go b/internal/cli/analytics_test.go index 47178f2..2132d11 100644 --- a/internal/cli/analytics_test.go +++ b/internal/cli/analytics_test.go @@ -2,17 +2,22 @@ package cli import ( "bytes" + "context" "encoding/json" "errors" + "fmt" "io" "net/http" "net/http/httptest" + "net/url" "os" "path/filepath" "runtime" "slices" + "strconv" "strings" "sync" + "sync/atomic" "testing" "time" ) @@ -388,3 +393,331 @@ func TestAnalyticsProjectCreateFailureBeforeAPIIsReported(t *testing.T) { }) } } + +const testTelemetryAppID = "0123456789abcdef0123456789abcdef" + +func TestAnalyticsCreationSurvivesLaterFailure(t *testing.T) { + for _, channel := range []string{"shell", "mcp"} { + for _, source := range []string{"project create", "quickstart", "recipe"} { + for _, failure := range []string{"features", "query"} { + t.Run(channel+"/"+source+"/"+failure, func(t *testing.T) { + collector, read := analyticsRecorder(t) + a := analyticsTestApp(t, collector.URL) + var creates atomic.Int32 + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == "POST" && r.URL.Path == "/api/cli/v1/projects" { + creates.Add(1) + time.Sleep(25 * time.Millisecond) + _ = json.NewEncoder(w).Encode(projectDetail{AppID: testTelemetryAppID, ProjectID: "prj_created", Name: "private-project"}) + return + } + if failure == "features" { + time.Sleep(120 * time.Millisecond) + } + w.WriteHeader(http.StatusServiceUnavailable) + _, _ = w.Write([]byte(`{"message":"private failure"}`)) + })) + defer backend.Close() + a.env["AGORA_API_BASE_URL"] = backend.URL + a.osEnv["AGORA_API_BASE_URL"] = backend.URL + if err := saveSession(a.env, session{AccessToken: "secret", TokenType: "Bearer", ExpiresAt: time.Now().Add(time.Hour).Format(time.RFC3339)}); err != nil { + t.Fatal(err) + } + command := "init" + if source == "project create" { + command = source + } + op := a.beginAnalytics(command, channel) + features := []string{"rtc"} + if failure == "features" { + features = []string{"rtm"} + } + var err error + if command == "project create" { + _, err = a.projectCreate("private-project", "", features, "", "", op) + } else { + target := filepath.Join(t.TempDir(), "demo") + if source == "quickstart" { + template, selectErr := selectQuickstartDefinition("nextjs", "video-call") + if selectErr != nil { + t.Fatal(selectErr) + } + _, err = a.initProject("private-project", target, template, "", features, "", true, false, io.Discard, strings.NewReader(""), nil, op) + } else { + recipe := recipeDetail{recipeSummary: recipeSummary{Slug: "test-source"}, CLI: &recipeCLIConfig{ProjectType: "python", Env: recipeCLIEnv{ExamplePath: ".env.example", TargetPath: ".env", AppIDKey: "AGORA_APP_ID", AppCertificateKey: "AGORA_APP_CERTIFICATE"}}} + _, err = a.initRecipeProject("private-project", target, recipe, "", features, "", true, false, io.Discard, strings.NewReader(""), nil, op) + } + } + if command == "init" && err == nil { + t.Fatal("fixture must fail after creation") + } + op.finish(err) + events := waitAnalyticsEvents(t, read, 1) + var creation *analyticsEvent + for i := range events { + e := &events[i] + if e.Event == "cli_project_create_completed" { + if creation != nil { + t.Fatal("duplicate creation") + } + creation = e + } + if e.Event == "cli_init_started" && e.Properties["app_id"] != nil { + t.Fatal("backfilled early event") + } + if e.Event == "cli_init_completed" && (e.Properties["outcome"] != "failure" || e.Properties["app_id"] != testTelemetryAppID) { + t.Fatalf("lost outer failure/App ID: %+v", e) + } + } + if creates.Load() != 1 || creation == nil || creation.Properties["outcome"] != "success" || creation.Properties["exit_code"] != float64(0) || creation.Properties["app_id"] != testTelemetryAppID { + t.Fatalf("wrong creation %+v", events) + } + duration := creation.Properties["duration_ms"].(float64) + if duration < 20 || duration > 115 { + t.Fatalf("creation timing includes later feature work: %v", duration) + } + }) + } + } + } +} + +func TestAnalyticsCreationAuthFailureAndInvalidAppID(t *testing.T) { + collector, read := analyticsRecorder(t) + a := analyticsTestApp(t, collector.URL) + a.env["AGORA_OUTPUT"] = "json" + op := a.beginAnalytics("project create", "mcp") + if _, err := a.createProject("private", "", op); err == nil { + t.Fatal("expected auth failure") + } + op.finish(nil) + events := waitAnalyticsEvents(t, read, 1) + if len(events) != 1 || events[0].Properties["outcome"] != "failure" || events[0].Properties["app_id"] != nil { + t.Fatal(events) + } + for _, id := range []string{"private name", "app_0001", "", "secret-token"} { + op.setAppID(id) + } + if op.properties["app_id"] != nil { + t.Fatal("accepted free text app ID") + } +} + +func TestAnalyticsCreationTimingIncludesRefreshAndRetry(t *testing.T) { + collector, read := analyticsRecorder(t) + a := analyticsTestApp(t, collector.URL) + var requests, refreshes atomic.Int32 + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + time.Sleep(30 * time.Millisecond) + if r.URL.Path == "/api/v0/oauth/token" { + refreshes.Add(1) + _, _ = w.Write([]byte(`{"access_token":"local","token_type":"Bearer","expires_in":3600,"refresh_token":"local","scope":"basic_info,console"}`)) + return + } + if requests.Add(1) == 1 { + w.WriteHeader(http.StatusUnauthorized) + return + } + _ = json.NewEncoder(w).Encode(projectDetail{AppID: testTelemetryAppID}) + })) + defer backend.Close() + a.osEnv["AGORA_API_BASE_URL"] = backend.URL + a.osEnv["AGORA_OAUTH_BASE_URL"] = backend.URL + if err := saveSession(a.env, session{AccessToken: "local", RefreshToken: "local", TokenType: "Bearer", ExpiresAt: time.Now().Add(-time.Hour).Format(time.RFC3339)}); err != nil { + t.Fatal(err) + } + op := a.beginAnalytics("project create", "shell") + _, err := a.createProject("local", "", op) + op.finish(err) + if err != nil { + t.Fatal(err) + } + events := waitAnalyticsEvents(t, read, 1) + if len(events) != 1 || requests.Load() != 2 || refreshes.Load() != 2 || events[0].Properties["duration_ms"].(float64) < 110 { + t.Fatalf("refresh/retry not in shared boundary: %+v requests=%d refreshes=%d", events, requests.Load(), refreshes.Load()) + } +} + +func TestAnalyticsCLIStartupAndMCPReadFailure(t *testing.T) { + for _, invalid := range []string{"{invalid", "null", `{"telemetryEnabled":null}`, `{"telemetryEnabled":"true"}`} { + t.Run(invalid, func(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + state, err := ensureAppConfigState(a.env) + if err != nil { + t.Fatal(err) + } + a.cfgState = state + if err := os.WriteFile(state.ConfigFilePath, []byte(invalid), 0o600); err != nil { + t.Fatal(err) + } + if op := a.beginAnalytics("recipes list", "mcp"); op != nil { + op.finish(nil) + t.Fatal("MCP used unreadable preference") + } + // Normal CLI deliberately retains the startup policy despite later edits. + op := a.beginAnalytics("recipes list", "shell") + if op == nil { + t.Fatal("CLI re-read startup preference") + } + op.finish(nil) + waitAnalyticsEvents(t, read, 1) + }) + } +} + +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(waitAnalyticsEvents(t, read, 3)) + 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 TestAnalyticsPolicySnapshotForRunningOperation(t *testing.T) { + server, read := analyticsRecorder(t) + a := analyticsTestApp(t, server.URL) + state, err := ensureAppConfigState(a.env) + if err != nil { + t.Fatal(err) + } + op := a.beginAnalytics("init", "mcp") + cfg := state.Config + cfg.TelemetryEnabled = false + if err := writeSecureJSON(state.ConfigFilePath, cfg); err != nil { + t.Fatal(err) + } + op.beginStage("clone") + op.finish(nil) + events := waitAnalyticsEvents(t, read, 4) + if len(events) != 4 { + t.Fatalf("running operation changed snapshot: %+v", events) + } +} + +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 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 := waitAnalyticsEvents(t, read, 1) + 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 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.telemetryAllowed(a.currentTelemetryPreference()) != !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.beginAnalytics("recipes list", "mcp") != nil { + t.Fatal("unreadable preference must fail closed") + } + }) + } +} + +// The collector allowlists these exact values; changing them is a wire +// format change that must be coordinated with the collector. +func TestAnalyticsAllowlistValuesArePinned(t *testing.T) { + for _, tc := range []struct { + name string + got, want []string + }{ + {"stages", analyticsStages, []string{"validate", "source_resolve", "local_validate", "project_resolve", "clone", "env_write", "binding_write", "context_write", "agent_rules_write"}}, + {"agent families", analyticsAgentFamilies, []string{"codex", "claude-code", "kiro", "cursor", "cline", "windsurf", "aider", "custom", "unknown"}}, + {"agent surfaces", analyticsAgentSurfaces, []string{"desktop", "cli", "unknown"}}, + {"detection sources", analyticsDetectionSources, []string{"explicit", "environment", "none"}}, + } { + if !slices.Equal(tc.got, tc.want) { + t.Errorf("%s changed: got %v, want %v", tc.name, tc.got, tc.want) + } + } +} From 163e7f2fa4170d9345a2675ab89e0c392de6087e Mon Sep 17 00:00:00 2001 From: Hermes Frangoudis Date: Fri, 20 Nov 2026 12:32:09 -0500 Subject: [PATCH 9/9] docs(agents): list analytics files in source layout Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index c152951..fac3dd4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,7 +46,11 @@ internal/cli/ install_doctor.go Top-level agora doctor — install self-test (PATH, network, auth, MCP host) env_help.go agora env-help — authoritative env-var catalog skills.go agora skills — curated workflow recipes (in-binary catalog) - telemetry.go telemetryClient interface + noop sink + Sentry placeholder (wire-up scheduled for next release) + telemetry.go Shared telemetry gate (telemetryAllowed / runtime opt-out) + diagnostics telemetryClient interface, noop sink and Sentry placeholder (no DSN shipped) + telemetry_notice.go Telemetry preference persistence, first-use disclosure, shared telemetry status result + analytics.go Usage analytics: operation lifecycle, installation ID, agent classification, init stages, allowlisted values + analytics_sender.go Usage analytics delivery: 64 KiB batching, allowlist validation, detached shell sender, in-process MCP sender + analytics_process_*.go Per-OS detach settings for the shell sender subprocess local_project.go .agora/project.json read/write; repo-local project binding runtime_support.go Template/runtime detection (nextjs, python, go), CI auto-detect, banner rules app_test.go Unit tests for app init and config