From a001eced61f264b97a2009ad1a803c7108969112 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 21:30:45 -0800 Subject: [PATCH 01/63] fix: suppress all usage telemetry when opted out --- docs/docs/reference/security-faq.md | 3 +- docs/docs/reference/telemetry.md | 15 +- .../src/altimate/telemetry/config-state.ts | 43 +- .../opencode/src/altimate/telemetry/index.ts | 160 +----- .../src/altimate/telemetry/opt-out.ts | 111 ---- .../opencode/src/altimate/util/machine-id.ts | 18 - packages/opencode/src/cli/welcome.ts | 13 - .../test/altimate/telemetry/identity.test.ts | 17 + .../test/altimate/telemetry/opt-out.test.ts | 487 ++++-------------- .../skill/release-v0.12.9-adversarial.test.ts | 92 +--- 10 files changed, 196 insertions(+), 763 deletions(-) delete mode 100644 packages/opencode/src/altimate/telemetry/opt-out.ts diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index ab524c7ac4..02082c7ea9 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -183,8 +183,7 @@ No code, queries, file paths, or personal information is included. This event he The install scripts (`altimate.sh/install`, `install.ps1`), the npm postinstall, and the VS Code extension's installer send nothing themselves and contact no telemetry endpoint. They only record the version and installer name to a local file that the CLI reads on its next run, so the opt-out above decides whether anything is ever transmitted. -!!! warning "One caveat on the config-file opt-out" - The environment variables (`ALTIMATE_TELEMETRY_DISABLED`, `OPENCODE_DISABLE_TELEMETRY`) are always honoured. The `telemetry.disabled` **config key** is read from the config files at telemetry startup. If a config file cannot be read or parsed at that point, startup proceeds with telemetry enabled, so this event may still be transmitted. Use an environment variable if you need a guarantee. +The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED` or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If startup cannot determine the config setting, it suppresses telemetry. ## What happens when I authenticate via a well-known URL? diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index c5e1639caf..04aa0d5534 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -65,7 +65,6 @@ We collect the following categories of events: | `gateway_auth_completed` / `gateway_auth_failed` | Gateway sign-in outcome. `reason` is `timeout`, `denied`, or `error` — never the underlying message, which can contain the instance name. An unrecognised callback state does not reject the pending attempt, so a CSRF mismatch surfaces as `timeout`. | | `instance_connected` | Credentials received and saved. `time_to_connect_ms` runs from the start of the authorize call, so it includes the browser launch. The event names no instance itself; like every event sent after sign-in, it carries the account's `user_id` and `tenant` once they are resolved (see [User Identification](#new-user-identification)). | | `onboarding_completed` | A model is ready and chat is live. | -| `telemetry_opted_out` | The last event from a machine that turns telemetry off, sent once (see [Disabling Telemetry](#disabling-telemetry)). Contains `opt_out_source` (`env` for an environment variable, `config` for `telemetry.disabled`), the machine ID, the CLI version and the client. It carries no account (`user_id`, `tenant`), project, session or launch ID. | | `scan_gate_shown` / `scan_gate_choice` | The "scan your environment?" gate appeared, and what the user did — `scan`, `skip`, or `dismissed` (esc / click-away). | | `environment_scan_completed` | A `project_scan` finished during onboarding — `has_dbt`, `has_warehouse`, `is_repo`, `connections_found`, and a bounded list of short `degraded` detection keys. No paths, hostnames, or connection details. Emitted only inside an onboarding session, and only once per session, so scans from `/discover` or a model-initiated call are excluded. | | `sample_setup_completed` | The sample dbt project was materialised. `success`, `models`, `tables`, and `reused` — the tool is deliberately re-callable, so this is per invocation. The target path is never sent. | @@ -88,7 +87,7 @@ We collect the following categories of events: | `plugin_session_start` | A Claude Code session started with the Altimate Code plugin, sent by the plugin through `altimate-code tool report-event`. Its payload is the plugin version, this altimate-code's version (`altimate_code_version`), the OS as Claude Code names it (`host_os`: `macos`, `linux`, `windows`, `wsl` or `unknown`; named apart from the `os` other events carry as `process.platform`) and the plugin's anonymous install id (a random UUID the plugin makes on first run and keeps in its Claude Code plugin store). It carries no session id, machine id, project id or account (`user_id`, `tenant`), nor the per-launch `launch_id`, so it cannot be joined to the CLI's other events: beside its own fields, only `cli_version`, `client` and `source`, keyed to the install id (`ai.user.id`). It is sent in a request of its own, never in one batch with the CLI's other events. | | `plugin_feature_used` | One of the plugin's panels or commands was opened (`lineage`, `dbt_show`, `profile_ctes`, `scan_cost`, `comments`, `sql_graph`, `health`, `runs`, `to_model`), or one of its gates held or allowed a command (`cost_gate`, `health_push_gate`). Its payload is the feature, the outcome (`opened`; `failed` when the panel could not open; `held` or `allowed` for a gate), the plugin version and the install id: no model, column, file or project names, SQL or session text. Like `plugin_session_start`, it carries no session id, machine id, project id, launch id or account: beside its own fields, only `cli_version`, `client` and `source`, keyed to the install id. | -Each event (except the plugin's `plugin_session_start` and `plugin_feature_used`, described above) includes a timestamp, session ID, a per-launch correlation ID (`launch_id` — a random value regenerated every process start, not persisted and not derived from your machine or identity; it exists only to group events from the same run), CLI version, and a machine ID (a random UUID stored in `~/.altimate/machine-id`, generated once and not derived from your hardware or identity). The final `telemetry_opted_out`, in the same table, is the other exception: it carries the timestamp, CLI version and machine ID, but no session ID, `launch_id` or account. When the machine is signed in to Altimate, each event also carries `user_id` and `tenant`, described under [User Identification](#new-user-identification). +Each event (except the plugin's `plugin_session_start` and `plugin_feature_used`, described above) includes a timestamp, session ID, a per-launch correlation ID (`launch_id` — a random value regenerated every process start, not persisted and not derived from your machine or identity; it exists only to group events from the same run), CLI version, and a machine ID (a random UUID stored in `~/.altimate/machine-id`, generated once and not derived from your hardware or identity). When the machine is signed in to Altimate, each event also carries `user_id` and `tenant`, described under [User Identification](#new-user-identification). ### Workspace events @@ -183,13 +182,9 @@ You can also set the environment variable: export ALTIMATE_TELEMETRY_DISABLED=true ``` -When telemetry is disabled, a machine with an existing machine ID sends one final `telemetry_opted_out` event, then nothing: no further events and no requests to the telemetry endpoint until telemetry is turned back on. The event carries only the machine ID, the opt-out source, the CLI version and the client — see the event table above. With it, an opted-out machine can be counted instead of looking like a client that stopped working. +`OPENCODE_DISABLE_TELEMETRY` is also supported. Both variables accept `1` or `true` (case-insensitive). -- The event is sent only if `~/.altimate/machine-id` already exists. A machine that never ran with telemetry on sends nothing. -- Once the telemetry endpoint accepts the event, Altimate Code writes the marker file `~/.altimate/telemetry-opted-out`, and later launches send nothing. If the endpoint cannot be reached, no marker is written and a later launch tries again. -- While the event is being sent, a short-lived `~/.altimate/telemetry-opted-out.sending` file stops a second process from sending it too. -- Turning telemetry back on removes the marker, so a later opt-out is recorded again. -- No account lookup is made while telemetry is disabled. +When either variable or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. If startup cannot determine the config setting, it suppresses telemetry. This includes startup before a configured remote source that could set the flag has been loaded. ### Test runs are excluded @@ -207,7 +202,7 @@ Two escape hatches exist for reporting from a test run deliberately: is always honoured, which is how the project's own telemetry tests work. - Set `ALTIMATE_TELEMETRY_FORCE=true` to use the default endpoint anyway. -`ALTIMATE_TELEMETRY_DISABLED` and the config opt-out take precedence over both. +Both environment opt-outs and the config opt-out take precedence over these settings. ## Privacy @@ -232,7 +227,7 @@ What identifies the sender of an event depends on whether the machine is signed The Claude Code plugin's `plugin_session_start` and `plugin_feature_used` are the exception: signed in or not, they carry neither the machine ID nor your account, and their `ai.user.id` is the plugin's own random install id. -These identifiers are sent only while telemetry is enabled. The final `telemetry_opted_out` event carries the machine ID and nothing that identifies your account, and no `/users/me` lookup is made while telemetry is disabled. Disable telemetry entirely with `ALTIMATE_TELEMETRY_DISABLED=true` or the config option above. +These identifiers are sent only while telemetry is enabled. No telemetry `/users/me` lookup is made while telemetry is disabled. Disable telemetry entirely with `ALTIMATE_TELEMETRY_DISABLED=true` or the config option above. ### CLI Authentication Flow diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index a5d1789755..0d8d8ed0ae 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -1,9 +1,12 @@ +import { Database as SQLite } from "bun:sqlite" import path from "path" import fs from "fs/promises" import { existsSync } from "fs" import * as Effect from "effect/Effect" import { Flag, env as flagEnv } from "@opencode-ai/core/flag/flag" import { FSUtil } from "@opencode-ai/core/fs-util" +import { Database } from "@opencode-ai/core/database/database" +import { Auth } from "@/auth" import { Global } from "../../global" import { ConfigPaths } from "@/config/paths" import { ConfigManaged } from "@/config/managed" @@ -13,20 +16,20 @@ import { validateLoaded } from "@/config/config" * Whether the user config turns telemetry off, read without an Instance. * * `Config.get()` needs an Instance, and the CLI's main thread initialises telemetry in middleware - * before one exists, so there it throws. Treating that as "enabled" let an opted-out user's main - * thread clear the opt-out marker and resolve their identity. This reads the same files `Config` + * before one exists, so there it throws. This reads the same files `Config` * merges, in the same order (a later source overrides an earlier one), straight from disk: * the global config files (the legacy TOML `config` file included), `OPENCODE_CONFIG`, the project * files and `.altimate-code`/`.opencode` directories found from `directory`, the inline * `OPENCODE_CONFIG_CONTENT`, the managed config directory and macOS managed preferences. Remote and - * account configs are not read (they need the network). The read emits no telemetry of its own: it - * runs before telemetry knows whether it may. + * account configs are not fetched here. If either could still opt out, the answer is unknown. + * The read runs before telemetry knows whether it may send. * * - `disabled`: the last source that sets `telemetry.disabled` sets it to `true`. * - `enabled`: no source turns it off. * - `unreadable`: some source could not be read, parsed or validated as `Config` does (a missing * `{file:}` reference, a value its schema rejects). `Config` would fail to load at all, so the - * answer is unknown. Callers fail closed for anything an opt-out forbids. + * answer is unknown. A configured remote source that could still opt out is also unknown. + * Callers fail closed for anything an opt-out forbids. */ export type State = "disabled" | "enabled" | "unreadable" @@ -44,6 +47,33 @@ function worktreeOf(directory: string): string | undefined { } } +// The well-known config merges before local files, while an active organization's config can +// override them. Inspect only local credentials and account state; never fetch config here. +async function remoteMayDisable(local: boolean | undefined): Promise { + if (local === undefined && Object.values(await Auth.all()).some((entry) => entry?.type === "wellknown")) { + return true + } + + // No on-disk account state to inspect. Avoid opening or creating a database on a fresh install. + const dbPath = Database.path() + if (dbPath === ":memory:") return false + try { + await fs.stat(dbPath) + } catch (error) { + if ((error as NodeJS.ErrnoException)?.code === "ENOENT") return false + throw error + } + // Use a read-only connection so this check cannot run migrations or initialize account storage. + const db = new SQLite(dbPath, { readonly: true }) + try { + return db.query(`SELECT 1 FROM account_state + JOIN account ON account.id = account_state.active_account_id + WHERE account_state.id = 1 AND account_state.active_org_id IS NOT NULL`).get() !== null + } finally { + db.close() + } +} + export async function disabledState(directory: string = process.cwd()): Promise { try { let value: boolean | undefined @@ -118,7 +148,8 @@ export async function disabledState(directory: string = process.cwd()): Promise< if (managed) await readText(managed.text, managed.source, path.dirname(managed.source)) if (unknown) return "unreadable" - return value ? "disabled" : "enabled" + if (value === true) return "disabled" + return (await remoteMayDisable(value)) ? "unreadable" : "enabled" } catch { return "unreadable" } diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 5df4d68dc3..f0455d24fc 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -8,7 +8,6 @@ import { getOrCreateMachineId } from "@/altimate/util/machine-id" // altimate_change — the Claude Code plugin's actions, whose events are sent anonymous (see ANONYMOUS_EVENTS) import { PLUGIN_ACTIONS } from "@/altimate/tool-cli/report-event" import { TelemetryIdentity } from "./identity" -import { OptOutMarker } from "./opt-out" import { TelemetryConfig } from "./config-state" import { createHash, randomUUID } from "crypto" // altimate_change — first-run health: the event-loop stall monitor labels which thread stalled @@ -69,17 +68,9 @@ const log = Log.create({ service: "telemetry" }) */ function isAutomatedRun(): boolean { if (process.env.ALTIMATE_TELEMETRY_FORCE === "true") return false - return underTestRunner() -} - -// altimate_change start — the raw test-runner check, without the force flag. The opt-out marker -// reads and writes files in the real home directory, so under a test runner it stays inert unless -// a suite opts in through Telemetry.allowOptOutUnderTestRunner(); the force flag must not reach it. -function underTestRunner(): boolean { if (process.env.NODE_ENV === "test") return true return Boolean(process.env.BUN_TEST || process.env.VITEST || process.env.JEST_WORKER_ID) } -// altimate_change end // altimate_change start — composed path-masking rules (shared fragments) // R: one path-run character — anything but whitespace/separators/quotes, @@ -1058,14 +1049,6 @@ export namespace Telemetry { // The 0.11.0 first-run freeze (an in-process @npmcli/arborist install blocking the loop for minutes) // was invisible for two months: nothing timed startup or registration, and a blocked loop cannot // flush, so a killed process left only `session_start`. These events close that gap. - | { - /** The last event an opted-out machine sends; nothing follows it until telemetry is - * turned back on. Built directly in recordOptOut(), never through track(). */ - type: "telemetry_opted_out" - timestamp: number - /** Where the opt-out was set: an environment variable or the user config. */ - opt_out_source: "env" | "config" - } | { type: "startup_ready" timestamp: number @@ -2325,15 +2308,6 @@ export namespace Telemetry { // once by the stamp comparison; the backoff only throttles retries of the unchanged one. const IDENTITY_RETRY_MS = 60_000 let identityRetryAt = 0 // 0: no retry pending - // altimate_change start — bumped by shutdown(); a detached opt-out send started under an earlier - // lifecycle does not post. Its marker write keys on markerGeneration instead, which only an - // enabled init bumps: a send accepted across a shutdown while still opted out keeps its marker. - let lifecycleGeneration = 0 - let markerGeneration = 0 - // altimate_change end - // altimate_change — false when this init could not read the user config: an opted-out user may be - // behind it, so no identity is resolved (at init, at a flush or on refresh) until an init that can. - let identityAllowed = true // altimate_change — the project the command will run in, for reading the config without an // Instance: the CLI initialises telemetry before a command changes into its `--dir` or project. let configDirectory: string | undefined @@ -2415,9 +2389,6 @@ export namespace Telemetry { return { iKey, endpoint: `${base}v2/track` } } - // altimate_change — `ids` lets a caller build envelopes for a machine and identity other than - // the module's current state (the opt-out marker runs while telemetry is disabled and must not - // touch the state an enabled init may be using concurrently). // altimate_change start — the Claude Code plugin's usage events are anonymous and unlinkable: they carry // none of the identifiers the CLI's other events share (account, machine id, project, session, launch id), // so they cannot be joined to a signed-in row. They are keyed to the plugin's own random install id only. @@ -2427,10 +2398,9 @@ export namespace Telemetry { function toAppInsightsEnvelopes( events: Event[], cfg: AppInsightsConfig, - ids?: { machineId: string; identity: TelemetryIdentity.Identity | undefined }, + ids: { machineId: string; identity: TelemetryIdentity.Identity | undefined }, ): object[] { - const mid = ids ? ids.machineId : machineId - const who = ids ? ids.identity : identity + const { machineId: mid, identity: who } = ids // Process-level client, read live from the env flag (defaults to "cli") so events // emitted before any prompt runs — startup, connection setup, standalone CLI // subcommands — are labelled correctly instead of stuck at a hardcoded default. @@ -2562,30 +2532,21 @@ export namespace Telemetry { // (previously only wired in test fixtures, silent no-op in product). if (Flag.truthyEnv("ALTIMATE_TELEMETRY_DISABLED") || Flag.truthyEnv("OPENCODE_DISABLE_TELEMETRY")) { buffer = [] - optOutSend = recordOptOut("env") return } - // Config.get() may throw outside Instance context (e.g. CLI middleware - // before Instance.provide()). Telemetry stays enabled then, as before. - // altimate_change start — but the opt-out still counts: read `telemetry.disabled` from the - // config files directly, and when even that fails, skip what an opt-out forbids (clearing the - // opt-out marker, resolving the account) while ordinary rows keep flowing. - let configUnreadable = false + // altimate_change start — verify the opt-out before initializing either telemetry transport. + // CLI middleware can run before Instance.provide(), so fall back to the local config files. + // Suppress telemetry when the config state is unknown, since it may contain an opt-out. + let disabled: boolean try { - const userConfig = (await Config.get()) as any - if (userConfig.telemetry?.disabled) { - buffer = [] - optOutSend = recordOptOut("config") - return - } + const userConfig = (await Config.get()) + disabled = userConfig.telemetry?.disabled === true } catch { - const state = await TelemetryConfig.disabledState(configDirectory) - if (state === "disabled") { - buffer = [] - optOutSend = recordOptOut("config") - return - } - configUnreadable = state === "unreadable" + disabled = (await TelemetryConfig.disabledState(configDirectory)) !== "enabled" + } + if (disabled) { + buffer = [] + return } // altimate_change end // App Insights: env var overrides default (for dev/testing), otherwise use the baked-in key. @@ -2607,25 +2568,17 @@ export namespace Telemetry { return } appInsights = cfg - identityAllowed = !configUnreadable // altimate_change start — identity for the funnel join: the backend user uuid and tenant from // the stored Altimate credential, cached per credential so this costs no network unless the // credential changed. Replaces the hashed account email. Not awaited: events flushed before it // resolves carry only the machine id, and telemetry never waits on the backend. - if (identityAllowed) void resolveIdentity() + void resolveIdentity() // altimate_change end // altimate_change — use shared getOrCreateMachineId() from util/machine-id.ts. // Returns "" on all error conditions (ENOENT: mints new UUID; EACCES/corrupt/oversized: // logs + returns ""). No try/catch needed — all paths are handled inside. machineId = getOrCreateMachineId() enabled = true - // altimate_change — telemetry is on: forget the opt-out marker, so turning it off again is - // recorded again. The bump first, so a send still in flight never recreates it. Not when the - // config could not be read: the user may have opted out there. - if (!configUnreadable) { - markerGeneration++ - OptOutMarker.clear() - } log.info("telemetry initialized", { mode: "appinsights" }) // altimate_change — clear any existing interval before installing a new one. doInit() can // run more than once per process (init/shutdown cycles per session in prompt.ts), and @@ -2718,8 +2671,11 @@ export namespace Telemetry { * Does nothing while telemetry is disabled. */ export async function refreshIdentity(): Promise { // Opted out (or not initialised): no lookup; an enabled init resolves from the stored credential. - if (!enabled || !identityAllowed) return + if (!enabled) return + // A refresh queued behind a flush belongs to the init that started it. + const startedUnder = initPromise await flush() + if (!enabled || initPromise !== startedUnder) return identity = undefined await resolveIdentity({ refresh: true }) } @@ -2735,74 +2691,6 @@ export namespace Telemetry { } // altimate_change end - // altimate_change start — the final event of an opted-out machine. Sent once, only from a - // machine that has sent telemetry before (a machine id exists; none is minted here), under the - // same sink rules as doInit(). It carries the machine id and the opt-out source, never the account, - // project or launch. One send at a time across threads and processes (OptOutMarker.claim). The - // marker is written only once the ingest endpoint accepted the event, so an offline launch tries - // again next time; after the marker, nothing is sent until telemetry is re-enabled. Not awaited: - // an opted-out launch must not wait on the network. - const OPT_OUT_TIMEOUT_MS = 3_000 - // The launch does not wait for the send, but shutdown does (bounded), so a short command such as - // `tool run` records the marker instead of sending the event again on every later launch. - let optOutSend: Promise | undefined - let optOutUnderTestRunner = false - /** Test seam: let a suite that redirects the home directory exercise recordOptOut(). */ - export function allowOptOutUnderTestRunner(on: boolean) { - optOutUnderTestRunner = on - } - async function recordOptOut(source: "env" | "config"): Promise { - const lifecycle = lifecycleGeneration - const marker = markerGeneration - try { - if (underTestRunner() && !optOutUnderTestRunner) return - // The force flag is a developer knob for running telemetry under a test runner; the opt-out - // marker is about real users, and "disabled" must keep winning over "force" to the letter. - if (process.env.ALTIMATE_TELEMETRY_FORCE === "true") return - if (OptOutMarker.exists()) return - const id = OptOutMarker.readMachineId() - if (!id) return - const explicit = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING - const cfg = parseConnectionString(explicit ?? DEFAULT_CONNECTION_STRING) - if (!cfg) return - const envelopes = toAppInsightsEnvelopes( - [{ type: "telemetry_opted_out", timestamp: Date.now(), opt_out_source: source }], - cfg, - { machineId: id, identity: undefined }, - ) as Array<{ data: { baseData: { properties: Record } } }> - for (const envelope of envelopes) { - delete envelope.data.baseData.properties.project_id - delete envelope.data.baseData.properties.launch_id - } - // A shutdown since this task started means a later init may own the marker now: do not - // send, and let the next disabled init start over. - if (lifecycle !== lifecycleGeneration) return - const claim = OptOutMarker.claim() - if (!claim) return - const controller = new AbortController() - const timeout = setTimeout(() => controller.abort(), OPT_OUT_TIMEOUT_MS) - try { - // Another send may have finished between the marker check above and the claim. - if (OptOutMarker.exists()) return - const res = await fetch(cfg.endpoint, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(envelopes), - signal: controller.signal, - }) - // Accepted: write the marker unless telemetry was turned back on meanwhile, in this process - // (the generation) or another one (an enabled init removes the claim). - if (res.ok && marker === markerGeneration && OptOutMarker.holds(claim)) OptOutMarker.write() - } finally { - clearTimeout(timeout) - OptOutMarker.release(claim) - } - } catch { - // The opt-out path never surfaces: a missed marker only means one more attempt next launch. - } - } - // altimate_change end - /** Returns the turn generation for the session; pass it to `endSession` so only this turn ends it. */ export function setContext(opts: { sessionId: string; projectId: string }): number { sessionId = opts.sessionId @@ -3028,7 +2916,7 @@ export namespace Telemetry { // change on disk and re-resolve (cheap: two stats, and the cache answers unless the key changed). const who = identity const mid = machineId - if (enabled && identityAllowed) { + if (enabled) { const stamp = TelemetryIdentity.credentialStamp() const retryDue = identityRetryAt !== 0 && Date.now() >= identityRetryAt if (stamp !== identityStamp || retryDue) { @@ -3161,15 +3049,6 @@ export namespace Telemetry { // init failed — nothing to flush } } - // altimate_change start — let an opted-out launch's final event finish before the process exits - if (optOutSend) { - const send = optOutSend - optOutSend = undefined - let timer: ReturnType | undefined - await Promise.race([send, new Promise((resolve) => (timer = setTimeout(resolve, Math.min(timeoutMs ?? OPT_OUT_TIMEOUT_MS, OPT_OUT_TIMEOUT_MS))))]) - if (timer) clearTimeout(timer) - } - // altimate_change end // altimate_change — first-run health: stop the stall monitor only once init has settled, so a // shutdown that overlaps init cannot be undone by doInit() starting the monitor afterwards. stopLoopMonitor() @@ -3225,7 +3104,6 @@ export namespace Telemetry { // previous account on events; doInit() resolves it again from whatever credential is on disk. // The generation bump makes any resolution still in flight a no-op when it settles. identityGeneration++ - lifecycleGeneration++ identity = undefined identityStamp = "" identityRetryAt = 0 diff --git a/packages/opencode/src/altimate/telemetry/opt-out.ts b/packages/opencode/src/altimate/telemetry/opt-out.ts deleted file mode 100644 index 92a86ffba3..0000000000 --- a/packages/opencode/src/altimate/telemetry/opt-out.ts +++ /dev/null @@ -1,111 +0,0 @@ -import fs from "fs" -import { randomUUID } from "crypto" -import path from "path" -import { Global } from "../../global" -import { readExistingMachineId } from "@/altimate/util/machine-id" - -/** - * The marker that says this machine already sent its final ``telemetry_opted_out`` event. - * - * A machine that turns telemetry off goes silent, which on the dashboards looks exactly like a - * client that stopped emitting. So the last event an opted-out machine sends is the opt-out - * itself, once; the marker is what makes it once. It lives next to the machine id because both - * describe the machine, not the user, and it is removed when telemetry is turned back on so a - * later opt-out is recorded again. See ``recordOptOut`` in index.ts. - * - * Paths go through ``Global.Path.home`` so a test that sets ``OPENCODE_TEST_HOME`` never reads - * or writes the real home directory; in a real session that is the same directory the machine - * id lives in. - */ -function dir(): string { - return path.join(Global.Path.home, ".altimate") -} - -export function markerPath(): string { - return path.join(dir(), "telemetry-opted-out") -} - -/** The machine id minted by an earlier telemetry-enabled run, if any. Never mints one: a machine - * that never sent telemetry has nothing to mark. Bounded and symlink-safe, like the minting read. */ -export function readMachineId(): string | undefined { - return readExistingMachineId(path.join(dir(), "machine-id")) || undefined -} - -export function exists(): boolean { - return fs.existsSync(markerPath()) -} - -export function write(): void { - fs.mkdirSync(dir(), { recursive: true, mode: 0o700 }) - // Exclusive create: never follow a planted symlink; an existing entry fails the write. - fs.writeFileSync(markerPath(), `${new Date().toISOString()}\n`, { mode: 0o600, flag: "wx" }) -} - -/** A send older than this is a process that died mid-send; its claim no longer holds. The send - * itself is capped at 3 s. */ -const CLAIM_STALE_MS = 30_000 - -function claimPath(): string { - return path.join(dir(), "telemetry-opted-out.sending") -} - -/** - * Claim the one opt-out send, across threads and processes: an exclusive create of an in-flight - * file next to the marker. The TUI's main thread and its worker both init telemetry, so without - * this the first opted-out launch sent the event twice. Returns this send's token, or undefined when - * another send holds a fresh claim (or the file cannot be created); a claim left by a process that - * died is taken over. - */ -export function claim(): string | undefined { - const token = `${process.pid}:${randomUUID()}` - const create = () => fs.writeFileSync(claimPath(), `${token}\n`, { mode: 0o600, flag: "wx" }) - try { - create() - return token - } catch (err) { - if ((err as NodeJS.ErrnoException)?.code !== "EEXIST") return undefined - } - try { - const age = Date.now() - fs.lstatSync(claimPath()).mtimeMs - if (age < CLAIM_STALE_MS) return undefined - fs.rmSync(claimPath(), { force: true }) - create() - return token - } catch { - return undefined - } -} - -/** Whether `token`'s claim still stands. An enabled init in any process removes the claim with the - * marker (see `clear`), so a send it outlived must not write the marker back. */ -export function holds(token: string): boolean { - try { - return fs.readFileSync(claimPath(), "utf-8").trim() === token - } catch { - return false - } -} - -/** Give the claim back, if it is still this send's: after the marker is written, or when the send - * failed so a later launch tries. */ -export function release(token: string): void { - try { - if (holds(token)) fs.rmSync(claimPath(), { force: true }) - } catch { - // a leftover claim goes stale and is taken over - } -} - -/** Telemetry is on again: remove the marker and any in-flight claim, so a send still running in - * another process does not write the marker back. Best effort: an unremovable marker (read-only - * directory) must never fail an init. */ -export function clear(): void { - try { - fs.rmSync(markerPath(), { force: true }) - fs.rmSync(claimPath(), { force: true }) - } catch { - // leave it; the next opt-out is then not recorded again, which is the lesser failure - } -} - -export * as OptOutMarker from "./opt-out" diff --git a/packages/opencode/src/altimate/util/machine-id.ts b/packages/opencode/src/altimate/util/machine-id.ts index d65a9b96f5..30956ceb03 100644 --- a/packages/opencode/src/altimate/util/machine-id.ts +++ b/packages/opencode/src/altimate/util/machine-id.ts @@ -37,24 +37,6 @@ function readCappedUtf8(idPath: string): string { } } -/** - * Read an existing machine id without minting one. Same regular-file, size-cap and UUID - * checks as {@link getOrCreateMachineId}; returns `""` when the file is absent, unreadable, - * not a regular file, oversized or not a UUID. For callers that must not create a machine - * identity as a side effect (the telemetry opt-out marker). - */ -export function readExistingMachineId(machineIdPath?: string): string { - const idPath = machineIdPath ?? path.join(os.homedir(), ".altimate", "machine-id") - try { - const stat = fs.lstatSync(idPath) - if (!stat.isFile() || stat.size > MAX_BYTES) return "" - const raw = readCappedUtf8(idPath) - return UUID_RE.test(raw) ? raw : "" - } catch { - return "" - } -} - /** * Read the machine-id from `~/.altimate/machine-id`, minting a new random UUID * with `flag: "wx"` (exclusive create) if the file is absent. diff --git a/packages/opencode/src/cli/welcome.ts b/packages/opencode/src/cli/welcome.ts index f8ffd3f954..c9ab214fac 100644 --- a/packages/opencode/src/cli/welcome.ts +++ b/packages/opencode/src/cli/welcome.ts @@ -123,19 +123,6 @@ export function showWelcomeBannerIfNeeded(): void { // first-install from auto-update) — carrying that in the marker would be the fix if a // strict install count is ever required. Documented in docs/docs/reference/telemetry.md. // - // FIXME(telemetry-init-config-opt-out): doInit() may run before Instance.provide() has made - // Config.get() resolvable (see the try/catch around Config.get in telemetry/index.ts::doInit - // — the catch branch proceeds with telemetry enabled). A user who opted out via the - // `telemetry.disabled` config key — with no env var set — can therefore still have early - // events transmitted. The env-var opt-out (ALTIMATE_TELEMETRY_DISABLED / - // OPENCODE_DISABLE_TELEMETRY) is unaffected — that check needs no Instance context. - // Pre-existing and NOT specific to this event: every event emitted from CLI middleware - // shares the same gate. It is called out here because this event's volume grew ~30x when - // the shell and extension installers began writing the marker, so the exposure window is - // now routinely hit rather than theoretical. Fixing it belongs in telemetry init (make - // Config resolvable there, or adopt an explicit fail-closed policy module-wide) rather - // than in this function, which cannot resolve config without duplicating the merge and - // JSONC semantics of config/config.ts. const machineIdPath = path.join(os.homedir(), ".altimate", "machine-id") const isUpgrade = fs.existsSync(machineIdPath) // altimate_change end diff --git a/packages/opencode/test/altimate/telemetry/identity.test.ts b/packages/opencode/test/altimate/telemetry/identity.test.ts index df63ec5995..b3cdfc1c24 100644 --- a/packages/opencode/test/altimate/telemetry/identity.test.ts +++ b/packages/opencode/test/altimate/telemetry/identity.test.ts @@ -357,6 +357,23 @@ describe("telemetry identity", () => { expect(Telemetry.identityForTest()).toBeUndefined() }) + test("a queued identity refresh cannot cross into an opted-out init", async () => { + process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = + "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://ingest.example.invalid/" + writeCreds() + await Telemetry.shutdown() + await Telemetry.init() + expect(await until(() => Telemetry.identityForTest()?.user_id === UUID)).toBe(true) + + const refresh = Telemetry.refreshIdentity() + const shutdown = Telemetry.shutdown() + process.env.ALTIMATE_TELEMETRY_DISABLED = "1" + await Promise.all([refresh, shutdown, Telemetry.init()]) + + expect(Telemetry.isEnabled()).toBe(false) + expect(meCalls()).toHaveLength(1) + }) + test("a rejected key is not polled; only a new credential is looked up again", async () => { process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://ingest.example.invalid/" diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 8fe4750bfd..47593b023e 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -1,134 +1,74 @@ +import { Database as SQLite } from "bun:sqlite" import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test" -import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, utimesSync, writeFileSync } from "fs" +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs" import os from "os" import path from "path" +import { Database } from "@opencode-ai/core/database/database" import { Auth } from "../../../src/auth" import { Config } from "../../../src/config/config" import { Telemetry } from "../../../src/altimate/telemetry" -import { TelemetryIdentity } from "../../../src/altimate/telemetry/identity" -import { OptOutMarker } from "../../../src/altimate/telemetry/opt-out" -const MACHINE = "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d" -const UUID = "0f3c2a1e-6b7d-4c8e-9f10-1a2b3c4d5e6f" -const API = "https://api.example.invalid" const CS = "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://ingest.example.invalid/" - -type Call = { url: string; body: string } - -async function waitFor(pred: () => boolean, ms = 2_000) { - const until = Date.now() + ms - while (!pred() && Date.now() < until) await new Promise((r) => setTimeout(r, 20)) - return pred() -} - -describe("telemetry opt-out marker", () => { +const ENV = [ + "OPENCODE_TEST_HOME", + "APPLICATIONINSIGHTS_CONNECTION_STRING", + "ALTIMATE_TELEMETRY_DISABLED", + "OPENCODE_DISABLE_TELEMETRY", + "ALTIMATE_TELEMETRY_FORCE", + "OPENCODE_CONFIG_CONTENT", +] as const + +describe("telemetry opt-out", () => { let home: string - let calls: Call[] - let trackStatus = 200 - /** When set, the next /v2/track POST waits on it before answering. */ - let holdTrack: Promise | undefined - let fetchSpy: ReturnType - let homedirSpy: ReturnType - let authSpy: ReturnType + let fetchSpy: ReturnType> + let configSpy: ReturnType> + let homedirSpy: ReturnType> + let authSpy: ReturnType> const saved: Record = {} - const ENV = [ - "OPENCODE_TEST_HOME", - "APPLICATIONINSIGHTS_CONNECTION_STRING", - "ALTIMATE_TELEMETRY_DISABLED", - "OPENCODE_DISABLE_TELEMETRY", - "ALTIMATE_TELEMETRY_FORCE", - "OPENCODE_CONFIG_CONTENT", - ] - - const optOuts = () => - calls - .filter((c) => c.url.includes("/v2/track")) - .flatMap((c) => JSON.parse(c.body) as any[]) - .filter((e) => e.data?.baseData?.name === "telemetry_opted_out") - const trackPosts = () => calls.filter((c) => c.url.includes("/v2/track")) - function writeMachineId() { - mkdirSync(path.join(home, ".altimate"), { recursive: true }) - writeFileSync(path.join(home, ".altimate", "machine-id"), MACHINE) - } - function writeCreds() { - mkdirSync(path.join(home, ".altimate"), { recursive: true }) + beforeEach(async () => { + await Telemetry.shutdown() + home = mkdtempSync(path.join(os.tmpdir(), "telemetry-opt-out-")) + mkdirSync(path.join(home, ".altimate")) + // Simulate a previously signed-in installation with an ID and no opt-out marker. + writeFileSync(path.join(home, ".altimate", "machine-id"), "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d") writeFileSync( path.join(home, ".altimate", "altimate.json"), - JSON.stringify({ altimateUrl: API, altimateInstanceName: "acme", altimateApiKey: "key-1" }), + JSON.stringify({ + altimateUrl: "https://api.example.invalid", + altimateInstanceName: "workspace", + altimateApiKey: "test-key", + }), ) - } - - beforeEach(() => { - home = mkdtempSync(path.join(os.tmpdir(), "telemetry-opt-out-")) - for (const k of ENV) saved[k] = process.env[k] + for (const key of ENV) { + saved[key] = process.env[key] + delete process.env[key] + } process.env.OPENCODE_TEST_HOME = home process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = CS - delete process.env.ALTIMATE_TELEMETRY_DISABLED - delete process.env.OPENCODE_DISABLE_TELEMETRY - delete process.env.ALTIMATE_TELEMETRY_FORCE - homedirSpy = spyOn(os, "homedir").mockImplementation(() => home) - // The auth store lives in the real data directory; never let a test read it. + Telemetry.setConfigDirectory(home) + homedirSpy = spyOn(os, "homedir").mockReturnValue(home) authSpy = spyOn(Auth, "get").mockResolvedValue(undefined) - Telemetry.allowOptOutUnderTestRunner(true) - calls = [] - trackStatus = 200 - holdTrack = undefined - fetchSpy = spyOn(globalThis, "fetch").mockImplementation((async (input: any, init?: RequestInit) => { - const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url - calls.push({ url, body: String(init?.body ?? "") }) - if (url === `${API}/users/me`) { - return new Response(JSON.stringify({ id: 7, uuid: UUID }), { - status: 200, - headers: { "content-type": "application/json" }, - }) - } - if (url.includes("/v2/track")) { - if (holdTrack) await holdTrack - return new Response("", { status: trackStatus }) - } - return new Response("", { status: 200 }) - }) as any) + configSpy = spyOn(Config, "get").mockRejectedValue(new Error("InstanceRef not provided")) + fetchSpy = spyOn(globalThis, "fetch").mockRejectedValue(new Error("Telemetry must not invoke the transport")) }) afterEach(async () => { await Telemetry.shutdown() - Telemetry.allowOptOutUnderTestRunner(false) + Telemetry.setConfigDirectory(undefined) fetchSpy.mockRestore() + configSpy.mockRestore() homedirSpy.mockRestore() authSpy.mockRestore() - for (const k of ENV) { - if (saved[k] === undefined) delete process.env[k] - else process.env[k] = saved[k] + for (const key of ENV) { + if (saved[key] === undefined) delete process.env[key] + else process.env[key] = saved[key] } rmSync(home, { recursive: true, force: true }) }) - test("an opted-out machine sends one final event with its machine id only, then nothing", async () => { - writeMachineId() - writeCreds() - expect(await TelemetryIdentity.resolve()).toEqual({ user_id: UUID, tenant: "acme" }) - const meCallsBefore = calls.filter((c) => c.url.endsWith("/users/me")).length - - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" - await Telemetry.shutdown() - await Telemetry.init() - expect(await waitFor(() => optOuts().length > 0)).toBe(true) - const [event] = optOuts() - expect(event.data.baseData.properties.machine_id).toBe(MACHINE) - expect(event.data.baseData.properties.opt_out_source).toBe("env") - // Never the account, the project or the launch, even with a cached identity on disk. - for (const key of ["user_id", "tenant", "project_id", "launch_id"]) - expect(event.data.baseData.properties[key]).toBeUndefined() - expect(typeof event.data.baseData.properties.cli_version).toBe("string") - expect(event.tags["ai.user.id"]).toBe(MACHINE) - // No request to resolve an identity while opted out. - expect(calls.filter((c) => c.url.endsWith("/users/me")).length).toBe(meCallsBefore) - expect(await waitFor(() => OptOutMarker.exists())).toBe(true) - - // Nothing after it: tracked events are dropped, and a new init does not send again. - const posts = trackPosts().length - Telemetry.track({ + async function expectSilentLifecycle() { + const startupEvent = { type: "startup_ready", session_id: "", command: "test", @@ -136,298 +76,99 @@ describe("telemetry opt-out marker", () => { duration_ms: 1, fresh_install: false, timestamp: Date.now(), - }) - await Telemetry.flush() - await Telemetry.shutdown() + } as const + Telemetry.track(startupEvent) await Telemetry.init() - await new Promise((r) => setTimeout(r, 150)) - expect(trackPosts().length).toBe(posts) - expect(optOuts()).toHaveLength(1) - }) + const startupCalls = fetchSpy.mock.calls.length + const enabled = Telemetry.isEnabled() - test("a short opted-out run that shuts down at once still writes the marker, so the next launch sends nothing", async () => { - writeMachineId() - holdTrack = new Promise((r) => setTimeout(r, 100)) // the ingest endpoint answers after 100ms - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" - await Telemetry.shutdown() - await Telemetry.init() - await Telemetry.shutdown() // the command finished before the send did - expect(OptOutMarker.exists()).toBe(true) - await Telemetry.init() - await new Promise((r) => setTimeout(r, 100)) - expect(optOuts()).toHaveLength(1) - }) - - test("a machine that never sent telemetry sends nothing and gets no marker", async () => { - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" - await Telemetry.shutdown() - await Telemetry.init() - await new Promise((r) => setTimeout(r, 150)) - expect(trackPosts()).toHaveLength(0) - expect(OptOutMarker.exists()).toBe(false) - expect(existsSync(path.join(home, ".altimate", "machine-id"))).toBe(false) - }) - - test("a corrupt or oversized machine-id file sends nothing", async () => { - mkdirSync(path.join(home, ".altimate"), { recursive: true }) - writeFileSync(path.join(home, ".altimate", "machine-id"), "not-a-uuid\n" + "x".repeat(4096)) - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" - await Telemetry.shutdown() - await Telemetry.init() - await new Promise((r) => setTimeout(r, 150)) - expect(trackPosts()).toHaveLength(0) - expect(OptOutMarker.exists()).toBe(false) - }) - - test("the marker is written only once the sink accepted the event", async () => { - writeMachineId() - process.env.OPENCODE_DISABLE_TELEMETRY = "true" - trackStatus = 500 - await Telemetry.shutdown() - await Telemetry.init() - expect(await waitFor(() => trackPosts().length === 1)).toBe(true) - await new Promise((r) => setTimeout(r, 50)) - expect(OptOutMarker.exists()).toBe(false) - - trackStatus = 200 - await Telemetry.shutdown() - await Telemetry.init() - expect(await waitFor(() => trackPosts().length === 2)).toBe(true) - expect(await waitFor(() => OptOutMarker.exists())).toBe(true) - expect(optOuts()).toHaveLength(2) - expect(optOuts()[1].data.baseData.properties.user_id).toBeUndefined() - expect(optOuts()[1].tags["ai.user.id"]).toBe(MACHINE) - }) - - test("a send still pending when telemetry is re-enabled never recreates the marker", async () => { - writeMachineId() - let release: () => void = () => {} - holdTrack = new Promise((r) => (release = r)) - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" - await Telemetry.shutdown() - await Telemetry.init() - expect(await waitFor(() => trackPosts().length === 1)).toBe(true) // the POST is in flight - - delete process.env.ALTIMATE_TELEMETRY_DISABLED - await Telemetry.shutdown() - await Telemetry.init() // telemetry on again; this lifecycle owns the marker now - expect(Telemetry.isEnabled()).toBe(true) - release() - await new Promise((r) => setTimeout(r, 100)) - expect(OptOutMarker.exists()).toBe(false) - - // Opting out again is recorded afresh. - holdTrack = undefined - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" - await Telemetry.shutdown() - await Telemetry.init() - expect(await waitFor(() => optOuts().length === 2)).toBe(true) - expect(await waitFor(() => OptOutMarker.exists())).toBe(true) - }) + Telemetry.setContext({ sessionId: "session", projectId: "project" }) + Telemetry.track({ + type: "session_start", + timestamp: Date.now(), + session_id: "session", + project_id: "project", + model_id: "model", + provider_id: "provider", + agent: "agent", + os: process.platform, + arch: process.arch, + node_version: process.version, + }) + await Telemetry.refreshIdentity() + await Telemetry.flush() + const sessionCalls = fetchSpy.mock.calls.length - startupCalls - test("a send accepted after a shutdown still writes the marker, so the next opted-out init sends nothing", async () => { - writeMachineId() - let release: () => void = () => {} - holdTrack = new Promise((r) => (release = r)) - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" + // Leave a final event for shutdown to drain if tracking was accidentally enabled. + Telemetry.track({ + type: "error", + timestamp: Date.now(), + session_id: "session", + error_name: "TestError", + error_message: "test", + context: "test", + }) await Telemetry.shutdown() - await Telemetry.init() - expect(await waitFor(() => trackPosts().length === 1)).toBe(true) // the POST is in flight - - await Telemetry.shutdown() // still opted out: nothing has cleared the marker - release() - expect(await waitFor(() => OptOutMarker.exists())).toBe(true) + const shutdownCalls = fetchSpy.mock.calls.length - startupCalls - sessionCalls + expect({ startupCalls, sessionCalls, shutdownCalls }).toEqual({ startupCalls: 0, sessionCalls: 0, shutdownCalls: 0 }) + expect(enabled).toBe(false) + } - holdTrack = undefined - await Telemetry.init() - await new Promise((r) => setTimeout(r, 100)) - expect(optOuts()).toHaveLength(1) + test.each(["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY"])("%s suppresses all requests", async (key) => { + process.env[key] = "1" + await expectSilentLifecycle() + // A later launch must also stay silent with the same existing machine ID. + await expectSilentLifecycle() }) - test("an init that cannot read the config keeps the marker and resolves no account", async () => { - writeMachineId() - writeCreds() - OptOutMarker.write() - const configSpy = spyOn(Config, "get") - try { - // The main thread's init: no Instance, so Config.get() throws, and the files cannot be read. - configSpy.mockRejectedValue(new Error("InstanceRef not provided")) - process.env.OPENCODE_CONFIG_CONTENT = "{ not json" - await Telemetry.shutdown() - await Telemetry.init() - expect(Telemetry.isEnabled()).toBe(true) // ordinary rows keep flowing, as before - await Telemetry.flush() - await Telemetry.refreshIdentity() - await new Promise((r) => setTimeout(r, 50)) - expect(OptOutMarker.exists()).toBe(true) - expect(calls.filter((c) => c.url.endsWith("/users/me"))).toHaveLength(0) - expect(Telemetry.identityForTest()).toBeUndefined() - expect(optOuts()).toHaveLength(0) - - // The worker's init, inside an Instance: the config says disabled, and the marker held. - delete process.env.OPENCODE_CONFIG_CONTENT - configSpy.mockResolvedValue({ telemetry: { disabled: true } } as never) - await Telemetry.shutdown() - await Telemetry.init() - await new Promise((r) => setTimeout(r, 50)) - expect(Telemetry.isEnabled()).toBe(false) - expect(optOuts()).toHaveLength(0) - expect(OptOutMarker.exists()).toBe(true) - } finally { - configSpy.mockRestore() - } + test("opt-out takes precedence over the test force flag and explicit sink", async () => { + process.env.ALTIMATE_TELEMETRY_DISABLED = "TRUE" + process.env.ALTIMATE_TELEMETRY_FORCE = "true" + await expectSilentLifecycle() }) - test("an init without an Instance honours a config opt-out read from the files", async () => { - writeMachineId() - const configSpy = spyOn(Config, "get").mockRejectedValue(new Error("InstanceRef not provided")) - try { - process.env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ telemetry: { disabled: true } }) - await Telemetry.shutdown() - await Telemetry.init() - expect(Telemetry.isEnabled()).toBe(false) - expect(await waitFor(() => optOuts().length === 1)).toBe(true) - expect(optOuts()[0].data.baseData.properties.opt_out_source).toBe("config") - expect(await waitFor(() => OptOutMarker.exists())).toBe(true) - } finally { - configSpy.mockRestore() - } + test("loaded telemetry.disabled suppresses all requests", async () => { + configSpy.mockResolvedValue({ telemetry: { disabled: true } } as Awaited>) + await expectSilentLifecycle() }) - test("OPENCODE_DISABLE_TELEMETRY records the opt-out with source env", async () => { - writeMachineId() - process.env.OPENCODE_DISABLE_TELEMETRY = "true" - await Telemetry.shutdown() - await Telemetry.init() - expect(await waitFor(() => optOuts().length === 1)).toBe(true) - expect(optOuts()[0].data.baseData.properties.opt_out_source).toBe("env") - expect(await waitFor(() => OptOutMarker.exists())).toBe(true) + test("project telemetry.disabled suppresses all requests before instance startup", async () => { + mkdirSync(path.join(home, ".altimate-code")) + writeFileSync(path.join(home, ".altimate-code", "altimate-code.json"), '{ "telemetry": { "disabled": true } }') + await expectSilentLifecycle() }) - test("the config opt-out records the event with source config", async () => { - writeMachineId() - const configSpy = spyOn(Config, "get").mockResolvedValue({ telemetry: { disabled: true } } as never) + test("a configured well-known source suppresses telemetry until full config is available", async () => { + const auth = spyOn(Auth, "all").mockResolvedValue({ + "https://config.example.invalid": { type: "wellknown", key: "TEST_CONFIG_TOKEN", token: "test-token" }, + }) try { - await Telemetry.shutdown() - await Telemetry.init() - expect(Telemetry.isEnabled()).toBe(false) - expect(await waitFor(() => optOuts().length === 1)).toBe(true) - expect(optOuts()[0].data.baseData.properties.opt_out_source).toBe("config") + await expectSilentLifecycle() } finally { - configSpy.mockRestore() + auth.mockRestore() } }) - test("ALTIMATE_TELEMETRY_FORCE never sends the opt-out event", async () => { - writeMachineId() - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" - process.env.ALTIMATE_TELEMETRY_FORCE = "true" - await Telemetry.shutdown() - await Telemetry.init() - await new Promise((r) => setTimeout(r, 100)) // nothing to wait for: the force check returns first - expect(trackPosts()).toHaveLength(0) - expect(OptOutMarker.exists()).toBe(false) - expect(existsSync(path.join(home, ".altimate", "telemetry-opted-out.sending"))).toBe(false) - }) - - test("two disabled inits while the first send is in flight send the event once", async () => { - writeMachineId() - let release: () => void = () => {} - holdTrack = new Promise((r) => (release = r)) - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" - await Telemetry.shutdown() - await Telemetry.init() - expect(await waitFor(() => trackPosts().length === 1)).toBe(true) // the first send holds the claim - - await Telemetry.shutdown() - await Telemetry.init() // a second init, as the TUI's worker beside its main thread - await new Promise((r) => setTimeout(r, 100)) - expect(trackPosts()).toHaveLength(1) - - release() - expect(await waitFor(() => OptOutMarker.exists())).toBe(true) - expect(existsSync(path.join(home, ".altimate", "telemetry-opted-out.sending"))).toBe(false) - expect(optOuts()).toHaveLength(1) - }) - - test("another process's fresh claim holds the send; a stale one is taken over", async () => { - writeMachineId() - const claimFile = path.join(home, ".altimate", "telemetry-opted-out.sending") - writeFileSync(claimFile, "123\n") - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" - await Telemetry.shutdown() - await Telemetry.init() - await new Promise((r) => setTimeout(r, 100)) - expect(trackPosts()).toHaveLength(0) - - const old = (Date.now() - 60_000) / 1000 - utimesSync(claimFile, old, old) // the process that held it died mid-send - await Telemetry.shutdown() - await Telemetry.init() - expect(await waitFor(() => optOuts().length === 1)).toBe(true) - expect(await waitFor(() => OptOutMarker.exists())).toBe(true) - }) - - test("a failed send gives the claim back, so the next launch tries again", async () => { - writeMachineId() - trackStatus = 500 - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" - await Telemetry.shutdown() - await Telemetry.init() - expect(await waitFor(() => trackPosts().length === 1)).toBe(true) - const claimFile = path.join(home, ".altimate", "telemetry-opted-out.sending") - expect(await waitFor(() => !existsSync(claimFile))).toBe(true) - expect(OptOutMarker.exists()).toBe(false) - }) - - test("telemetry turned back on in another process stops an in-flight send from writing the marker", async () => { - writeMachineId() - let release: () => void = () => {} - holdTrack = new Promise((r) => (release = r)) - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" - await Telemetry.shutdown() - await Telemetry.init() - expect(await waitFor(() => trackPosts().length === 1)).toBe(true) - OptOutMarker.clear() // what an enabled init in another process does - release() - await new Promise((r) => setTimeout(r, 100)) - expect(OptOutMarker.exists()).toBe(false) - }) - - test("an init without an Instance reads the opt-out from the command's project directory", async () => { - writeMachineId() - const project = mkdtempSync(path.join(os.tmpdir(), "telemetry-opt-out-project-")) - mkdirSync(path.join(project, ".altimate-code")) - writeFileSync(path.join(project, ".altimate-code", "altimate-code.json"), '{ "telemetry": { "disabled": true } }') - const configSpy = spyOn(Config, "get").mockRejectedValue(new Error("InstanceRef not provided")) + test("a configured organization source suppresses telemetry until full config is available", async () => { + const dbPath = path.join(home, "account.db") + const db = new SQLite(dbPath) + db.exec(` + CREATE TABLE account (id TEXT PRIMARY KEY); + CREATE TABLE account_state (id INTEGER PRIMARY KEY, active_account_id TEXT, active_org_id TEXT); + INSERT INTO account VALUES ('account'); + INSERT INTO account_state VALUES (1, 'account', 'org'); + `) + db.close() + const database = spyOn(Database, "path").mockReturnValue(dbPath) try { - Telemetry.setConfigDirectory(project) - await Telemetry.shutdown() - await Telemetry.init() - expect(Telemetry.isEnabled()).toBe(false) - expect(await waitFor(() => optOuts().length === 1)).toBe(true) - expect(optOuts()[0].data.baseData.properties.opt_out_source).toBe("config") + await expectSilentLifecycle() } finally { - Telemetry.setConfigDirectory(undefined) - configSpy.mockRestore() - rmSync(project, { recursive: true, force: true }) + database.mockRestore() } }) - test("the marker creates a missing ~/.altimate owner-only", () => { - expect(existsSync(path.join(home, ".altimate"))).toBe(false) - OptOutMarker.write() - expect(statSync(path.join(home, ".altimate")).mode & 0o777).toBe(0o700) - }) - - test("turning telemetry back on clears the marker", async () => { - writeMachineId() - OptOutMarker.write() - expect(OptOutMarker.exists()).toBe(true) - await Telemetry.shutdown() - await Telemetry.init() - expect(Telemetry.isEnabled()).toBe(true) - expect(OptOutMarker.exists()).toBe(false) - expect(optOuts()).toHaveLength(0) + test("an unreadable config suppresses all requests", async () => { + process.env.OPENCODE_CONFIG_CONTENT = "{" + await expectSilentLifecycle() }) }) diff --git a/packages/opencode/test/skill/release-v0.12.9-adversarial.test.ts b/packages/opencode/test/skill/release-v0.12.9-adversarial.test.ts index 9c8d529ed7..768637b62b 100644 --- a/packages/opencode/test/skill/release-v0.12.9-adversarial.test.ts +++ b/packages/opencode/test/skill/release-v0.12.9-adversarial.test.ts @@ -2,7 +2,7 @@ * Adversarial coverage for the v0.12.9 release payload (v0.12.8..HEAD): the model-free `tool` CLI and * `mcp serve` permission gate (read/write split, the DROP DATABASE / DROP SCHEMA / TRUNCATE hard deny, the * allow-list, `--args -` folding, runner argument validation), the workspace-rules classifier and terminal - * sanitiser, the telemetry opt-out marker, identity cache, endpoint masking and string masking, sign-out + * sanitiser, the telemetry identity cache, endpoint masking and string masking, sign-out * removing the cached telemetry identity, analyst's post-config write denies, and `Filesystem.realLocation`. * * Targets the exported helpers with hostile inputs: comment-split and dollar-quoted SQL, chained @@ -30,7 +30,6 @@ import { } from "../../src/altimate/tools/sql-classify" import { classify as classifyRule, memoryScope } from "../../src/altimate/rules/classify" import { printable } from "../../src/altimate/rules/printable" -import { OptOutMarker } from "../../src/altimate/telemetry/opt-out" import { TelemetryIdentity } from "../../src/altimate/telemetry/identity" import { Telemetry } from "../../src/altimate/telemetry" import { endpointOf } from "../../src/altimate/workspace/api-client" @@ -543,10 +542,10 @@ describe("v0.12.9 adversarial: printable", () => { }) // --------------------------------------------------------------------------------------------------------- -// 3. #1501 / #1513 — telemetry: opt-out marker, identity cache, endpoint masking, maskString +// 3. #1501 / #1513 — telemetry: identity cache, endpoint masking, maskString // --------------------------------------------------------------------------------------------------------- -describe("v0.12.9 adversarial: telemetry opt-out marker and identity cache", () => { +describe("v0.12.9 adversarial: telemetry identity cache", () => { const originalHome = process.env.OPENCODE_TEST_HOME let home: string @@ -561,94 +560,9 @@ describe("v0.12.9 adversarial: telemetry opt-out marker and identity cache", () }) test("paths resolve under the redirected home", () => { - expect(OptOutMarker.markerPath()).toBe(path.join(home, ".altimate", "telemetry-opted-out")) expect(TelemetryIdentity.cachePath()).toBe(path.join(home, ".altimate", "telemetry-identity.json")) }) - test("write creates the marker once; a second write fails instead of overwriting", () => { - expect(OptOutMarker.exists()).toBe(false) - OptOutMarker.write() - expect(OptOutMarker.exists()).toBe(true) - expect(Number.isNaN(Date.parse(fs.readFileSync(OptOutMarker.markerPath(), "utf8").trim()))).toBe(false) - expect(() => OptOutMarker.write()).toThrow() - }) - - test.skipIf(process.platform === "win32")("write never follows a planted symlink", () => { - const victim = path.join(home, "victim.txt") - fs.writeFileSync(victim, "untouched") - fs.mkdirSync(path.join(home, ".altimate"), { recursive: true }) - fs.symlinkSync(victim, OptOutMarker.markerPath()) - expect(() => OptOutMarker.write()).toThrow() - expect(fs.readFileSync(victim, "utf8")).toBe("untouched") - }) - - test("claim is exclusive: a fresh claim blocks a second one until released", () => { - fs.mkdirSync(path.join(home, ".altimate"), { recursive: true }) - const token = OptOutMarker.claim() - expect(token).toBeString() - expect(OptOutMarker.holds(token!)).toBe(true) - expect(OptOutMarker.claim()).toBeUndefined() - OptOutMarker.release(token!) - expect(OptOutMarker.holds(token!)).toBe(false) - const next = OptOutMarker.claim() - expect(next).toBeString() - expect(next).not.toBe(token) - }) - - test("a stale claim is taken over", () => { - fs.mkdirSync(path.join(home, ".altimate"), { recursive: true }) - const old = OptOutMarker.claim()! - const claimFile = path.join(home, ".altimate", "telemetry-opted-out.sending") - const past = new Date(Date.now() - 60_000) - fs.utimesSync(claimFile, past, past) - const fresh = OptOutMarker.claim() - expect(fresh).toBeString() - expect(OptOutMarker.holds(old)).toBe(false) - expect(OptOutMarker.holds(fresh!)).toBe(true) - }) - - test("claim without the .altimate directory returns undefined instead of throwing", () => { - expect(OptOutMarker.claim()).toBeUndefined() - }) - - test("holds and release reject foreign, empty and prefix tokens", () => { - fs.mkdirSync(path.join(home, ".altimate"), { recursive: true }) - const token = OptOutMarker.claim()! - for (const other of ["", " ", token.slice(0, -1), `${token}x`, "__proto__"]) { - expect(OptOutMarker.holds(other), other).toBe(false) - OptOutMarker.release(other) - expect(OptOutMarker.holds(token)).toBe(true) - } - }) - - test("holds does not trim the caller's token", () => { - fs.mkdirSync(path.join(home, ".altimate"), { recursive: true }) - const token = OptOutMarker.claim()! - expect(OptOutMarker.holds(` ${token}`)).toBe(false) - }) - - test("clear removes the marker and an in-flight claim, and is a no-op when both are absent", () => { - expect(() => OptOutMarker.clear()).not.toThrow() - OptOutMarker.write() - const token = OptOutMarker.claim()! - OptOutMarker.clear() - expect(OptOutMarker.exists()).toBe(false) - expect(OptOutMarker.holds(token)).toBe(false) - }) - - test("readMachineId ignores a non-UUID or oversized file", () => { - fs.mkdirSync(path.join(home, ".altimate"), { recursive: true }) - const idFile = path.join(home, ".altimate", "machine-id") - expect(OptOutMarker.readMachineId()).toBeUndefined() - fs.writeFileSync(idFile, "not-a-uuid") - expect(OptOutMarker.readMachineId()).toBeUndefined() - fs.writeFileSync(idFile, "a".repeat(10_000)) - expect(OptOutMarker.readMachineId()).toBeUndefined() - const uuid = "123e4567-e89b-42d3-a456-426614174000" - fs.writeFileSync(idFile, `${uuid}\n`) - expect(OptOutMarker.readMachineId()).toBe(uuid) - }) - test("identity clear is a no-op when the cache is absent and removes it when present", async () => { await expect(TelemetryIdentity.clear()).resolves.toBeUndefined() fs.mkdirSync(path.dirname(TelemetryIdentity.cachePath()), { recursive: true }) From ef0d8d802c8eb75dabe3122ca9a554e9071803f9 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 21:49:12 -0800 Subject: [PATCH 02/63] fix: close remaining telemetry opt-out gaps --- docs/docs/reference/security-faq.md | 2 +- docs/docs/reference/telemetry.md | 6 ++-- .../opencode/src/altimate/plugin/altimate.ts | 14 +++----- .../src/altimate/telemetry/config-state.ts | 24 ++++++++++++-- .../opencode/src/altimate/telemetry/index.ts | 13 ++++---- packages/opencode/src/config/config.ts | 26 ++++++++++++--- .../test/altimate/telemetry/identity.test.ts | 33 +++++++++++-------- .../test/altimate/telemetry/opt-out.test.ts | 29 ++++++++++++++-- 8 files changed, 103 insertions(+), 44 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index 02082c7ea9..690368538e 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -183,7 +183,7 @@ No code, queries, file paths, or personal information is included. This event he The install scripts (`altimate.sh/install`, `install.ps1`), the npm postinstall, and the VS Code extension's installer send nothing themselves and contact no telemetry endpoint. They only record the version and installer name to a local file that the CLI reads on its next run, so the opt-out above decides whether anything is ever transmitted. -The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED` or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If startup cannot determine the config setting, it suppresses telemetry. +The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If startup cannot determine the config setting, it suppresses telemetry. ## What happens when I authenticate via a well-known URL? diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index 04aa0d5534..a5c162dd41 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -182,9 +182,9 @@ You can also set the environment variable: export ALTIMATE_TELEMETRY_DISABLED=true ``` -`OPENCODE_DISABLE_TELEMETRY` is also supported. Both variables accept `1` or `true` (case-insensitive). +`ALTIMATE_CLI_DISABLE_TELEMETRY` and `OPENCODE_DISABLE_TELEMETRY` are also supported. Each variable accepts `1` or `true` (case-insensitive). -When either variable or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. If startup cannot determine the config setting, it suppresses telemetry. This includes startup before a configured remote source that could set the flag has been loaded. +When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. If startup cannot determine the config setting, it suppresses telemetry. This includes startup before a configured remote source that could set the flag has been loaded. ### Test runs are excluded @@ -202,7 +202,7 @@ Two escape hatches exist for reporting from a test run deliberately: is always honoured, which is how the project's own telemetry tests work. - Set `ALTIMATE_TELEMETRY_FORCE=true` to use the default endpoint anyway. -Both environment opt-outs and the config opt-out take precedence over these settings. +The environment opt-outs and the config opt-out take precedence over these settings. ## Privacy diff --git a/packages/opencode/src/altimate/plugin/altimate.ts b/packages/opencode/src/altimate/plugin/altimate.ts index baf989aa1d..84b5133f6c 100644 --- a/packages/opencode/src/altimate/plugin/altimate.ts +++ b/packages/opencode/src/altimate/plugin/altimate.ts @@ -9,7 +9,6 @@ import { Telemetry } from "../telemetry" // altimate_change — shared machine-id helper (race-safe, UUID-validated, size-capped) import { getOrCreateMachineId } from "../util/machine-id" import { Config } from "@/config/config" -import { Flag } from "@/flag/flag" import { InstallationVersion } from "@opencode-ai/core/installation/version" import { Log } from "@/altimate/util/log" // altimate_change — reads the config telemetry opt-out without an Instance @@ -80,17 +79,12 @@ const log = Log.create({ service: "altimate-plugin" }) /** `directory`: the project the command acts on, whose config may opt out; the process's working * directory when the command has none (`auth login`). */ export async function buildCliContext(machineIdPath?: string, directory?: string): Promise { - // altimate_change start — honour both telemetry opt-out gates, mirroring - // telemetry/index.ts::doInit: - // 1. ALTIMATE_TELEMETRY_DISABLED / OPENCODE_DISABLE_TELEMETRY env vars - // ("true"/"TRUE"/"1", case-insensitive — see Flag.truthyEnv) - // 2. config.telemetry.disabled (resolved via the async Config.get()) - let disabled = - Flag.truthyEnv("ALTIMATE_TELEMETRY_DISABLED") || Flag.truthyEnv("OPENCODE_DISABLE_TELEMETRY") + // altimate_change start — apply the same opt-out to the auth URL’s machine ID + let disabled = Boolean(TelemetryConfig.disablingEnvironmentVariable()) if (!disabled) { try { - const userConfig = (await Config.get()) as any - disabled = Boolean(userConfig.telemetry?.disabled) + const userConfig = await Config.get() + disabled = userConfig.telemetry?.disabled === true || Config.telemetryConfigUnresolved(userConfig) } catch (err) { // Config was unreadable — NOT the normal path. Server routes run inside // Instance.provide() (AsyncLocalStorage-propagated across awaits), so diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 0d8d8ed0ae..cac7a1a297 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -47,12 +47,30 @@ function worktreeOf(directory: string): string | undefined { } } +export function disablingEnvironmentVariable(): string | undefined { + return ["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY", "ALTIMATE_CLI_DISABLE_TELEMETRY"].find((key) => + /^(true|1)$/i.test(process.env[key] ?? ""), + ) +} + +async function hasWellKnownSource(): Promise { + let contents = process.env.OPENCODE_AUTH_CONTENT + if (!contents) { + try { + contents = await fs.readFile(Auth.filepath(), "utf8") + } catch (error) { + if ((error as NodeJS.ErrnoException)?.code === "ENOENT") return false + throw error + } + } + const entries = JSON.parse(contents) as Record + return Object.values(entries).some((entry) => entry?.type === "wellknown") +} + // The well-known config merges before local files, while an active organization's config can // override them. Inspect only local credentials and account state; never fetch config here. async function remoteMayDisable(local: boolean | undefined): Promise { - if (local === undefined && Object.values(await Auth.all()).some((entry) => entry?.type === "wellknown")) { - return true - } + if (local === undefined && (await hasWellKnownSource())) return true // No on-disk account state to inspect. Avoid opening or creating a database on a fresh install. const dbPath = Database.path() diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index f0455d24fc..62bc304292 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2527,10 +2527,9 @@ export namespace Telemetry { async function doInit() { try { - // altimate_change — accept "true"/"TRUE"/"1" (case-insensitive) via truthyEnv, - // and honor the OPENCODE_DISABLE_TELEMETRY fallback promised by v0.9.4's CHANGELOG - // (previously only wired in test fixtures, silent no-op in product). - if (Flag.truthyEnv("ALTIMATE_TELEMETRY_DISABLED") || Flag.truthyEnv("OPENCODE_DISABLE_TELEMETRY")) { + // altimate_change — ALTIMATE_TELEMETRY_DISABLED and either spelling of the legacy opt-out + // act independently, so a false alias cannot override a truthy opt-out. + if (TelemetryConfig.disablingEnvironmentVariable()) { buffer = [] return } @@ -2540,7 +2539,7 @@ export namespace Telemetry { let disabled: boolean try { const userConfig = (await Config.get()) - disabled = userConfig.telemetry?.disabled === true + disabled = userConfig.telemetry?.disabled === true || Config.telemetryConfigUnresolved(userConfig) } catch { disabled = (await TelemetryConfig.disabledState(configDirectory)) !== "enabled" } @@ -2671,11 +2670,11 @@ export namespace Telemetry { * Does nothing while telemetry is disabled. */ export async function refreshIdentity(): Promise { // Opted out (or not initialised): no lookup; an enabled init resolves from the stored credential. - if (!enabled) return + if (!enabled || shutdownPromise) return // A refresh queued behind a flush belongs to the init that started it. const startedUnder = initPromise await flush() - if (!enabled || initPromise !== startedUnder) return + if (!enabled || shutdownPromise || initPromise !== startedUnder) return identity = undefined await resolveIdentity({ refresh: true }) } diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 345a4c2e87..ed318939f4 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -51,6 +51,14 @@ import { withTransientReadRetry } from "@/util/effect-http-client" import { makeRuntime } from "@/effect/run-service" // altimate_change end +// altimate_change start — keep telemetry off when an organization config was unavailable +const configsWithUnresolvedOrg = new WeakSet() + +export function telemetryConfigUnresolved(config: Info): boolean { + return configsWithUnresolvedOrg.has(config) +} +// altimate_change end + // altimate_change start — bootstrap can inspect config already loaded by service initialization // without introducing another asynchronous dependency for opted-out learning capture. const loadedConfig = new Map() @@ -683,6 +691,9 @@ export const layer = Layer.effect( yield* Effect.logDebug("loaded custom config from OPENCODE_CONFIG_CONTENT") } + // altimate_change start — preserve resolution status for the telemetry opt-out gate + let orgConfigUnresolved = false + // altimate_change end const activeAccount = Option.getOrUndefined( yield* accountSvc.active().pipe(Effect.catch(() => Effect.succeed(Option.none()))), ) @@ -716,11 +727,14 @@ export const layer = Layer.effect( } }).pipe( Effect.withSpan("Config.loadActiveOrgConfig"), - Effect.catch((err) => - Effect.logDebug("failed to fetch remote account config", { + // altimate_change start — telemetry must distinguish a partial config from a successful load + Effect.catch((err) => { + orgConfigUnresolved = true + return Effect.logDebug("failed to fetch remote account config", { error: err instanceof Error ? err.message : String(err), - }), - ), + }) + }), + // altimate_change end ) } @@ -893,6 +907,10 @@ export const layer = Layer.effect( } // altimate_change end + // altimate_change start — associate the status with this resolved config object + if (orgConfigUnresolved) configsWithUnresolvedOrg.add(result) + // altimate_change end + return { config: result, directories, diff --git a/packages/opencode/test/altimate/telemetry/identity.test.ts b/packages/opencode/test/altimate/telemetry/identity.test.ts index b3cdfc1c24..4f1b206714 100644 --- a/packages/opencode/test/altimate/telemetry/identity.test.ts +++ b/packages/opencode/test/altimate/telemetry/identity.test.ts @@ -4,6 +4,7 @@ import os from "os" import path from "path" import { Telemetry } from "../../../src/altimate/telemetry" import { Auth } from "../../../src/auth" +import { Config } from "../../../src/config/config" import { TelemetryIdentity } from "../../../src/altimate/telemetry/identity" const UUID = "0f3c2a1e-6b7d-4c8e-9f10-1a2b3c4d5e6f" @@ -357,21 +358,27 @@ describe("telemetry identity", () => { expect(Telemetry.identityForTest()).toBeUndefined() }) - test("a queued identity refresh cannot cross into an opted-out init", async () => { + test.each(["before", "after"] as const)("an identity refresh queued %s shutdown cannot reach an opted-out init", async (when) => { process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://ingest.example.invalid/" - writeCreds() - await Telemetry.shutdown() - await Telemetry.init() - expect(await until(() => Telemetry.identityForTest()?.user_id === UUID)).toBe(true) - - const refresh = Telemetry.refreshIdentity() - const shutdown = Telemetry.shutdown() - process.env.ALTIMATE_TELEMETRY_DISABLED = "1" - await Promise.all([refresh, shutdown, Telemetry.init()]) - - expect(Telemetry.isEnabled()).toBe(false) - expect(meCalls()).toHaveLength(1) + const config = spyOn(Config, "get").mockResolvedValue({} as Awaited>) + try { + writeCreds() + await Telemetry.shutdown() + await Telemetry.init() + expect(await until(() => Telemetry.identityForTest()?.user_id === UUID)).toBe(true) + + const queued = when === "before" ? Telemetry.refreshIdentity() : undefined + const shutdown = Telemetry.shutdown() + process.env.ALTIMATE_TELEMETRY_DISABLED = "1" + const disabledInit = Telemetry.init() + await Promise.all([queued ?? Telemetry.refreshIdentity(), shutdown, disabledInit]) + + expect(Telemetry.isEnabled()).toBe(false) + expect(meCalls()).toHaveLength(1) + } finally { + config.mockRestore() + } }) test("a rejected key is not polled; only a new credential is looked up again", async () => { diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 47593b023e..55968fb4ab 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -16,6 +16,9 @@ const ENV = [ "OPENCODE_DISABLE_TELEMETRY", "ALTIMATE_TELEMETRY_FORCE", "OPENCODE_CONFIG_CONTENT", + "ALTIMATE_CLI_CONFIG_CONTENT", + "ALTIMATE_CLI_DISABLE_TELEMETRY", + "OPENCODE_AUTH_CONTENT", ] as const describe("telemetry opt-out", () => { @@ -23,6 +26,7 @@ describe("telemetry opt-out", () => { let fetchSpy: ReturnType> let configSpy: ReturnType> let homedirSpy: ReturnType> + let authFileSpy: ReturnType> let authSpy: ReturnType> const saved: Record = {} @@ -48,6 +52,7 @@ describe("telemetry opt-out", () => { process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = CS Telemetry.setConfigDirectory(home) homedirSpy = spyOn(os, "homedir").mockReturnValue(home) + authFileSpy = spyOn(Auth, "filepath").mockReturnValue(path.join(home, "auth.json")) authSpy = spyOn(Auth, "get").mockResolvedValue(undefined) configSpy = spyOn(Config, "get").mockRejectedValue(new Error("InstanceRef not provided")) fetchSpy = spyOn(globalThis, "fetch").mockRejectedValue(new Error("Telemetry must not invoke the transport")) @@ -59,6 +64,7 @@ describe("telemetry opt-out", () => { fetchSpy.mockRestore() configSpy.mockRestore() homedirSpy.mockRestore() + authFileSpy.mockRestore() authSpy.mockRestore() for (const key of ENV) { if (saved[key] === undefined) delete process.env[key] @@ -114,13 +120,19 @@ describe("telemetry opt-out", () => { expect(enabled).toBe(false) } - test.each(["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY"])("%s suppresses all requests", async (key) => { + test.each(["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY", "ALTIMATE_CLI_DISABLE_TELEMETRY"])("%s suppresses all requests", async (key) => { process.env[key] = "1" await expectSilentLifecycle() // A later launch must also stay silent with the same existing machine ID. await expectSilentLifecycle() }) + test("a false canonical alias cannot override the legacy opt-out", async () => { + process.env.ALTIMATE_CLI_DISABLE_TELEMETRY = "false" + process.env.OPENCODE_DISABLE_TELEMETRY = "1" + await expectSilentLifecycle() + }) + test("opt-out takes precedence over the test force flag and explicit sink", async () => { process.env.ALTIMATE_TELEMETRY_DISABLED = "TRUE" process.env.ALTIMATE_TELEMETRY_FORCE = "true" @@ -139,13 +151,24 @@ describe("telemetry opt-out", () => { }) test("a configured well-known source suppresses telemetry until full config is available", async () => { - const auth = spyOn(Auth, "all").mockResolvedValue({ + process.env.OPENCODE_AUTH_CONTENT = JSON.stringify({ "https://config.example.invalid": { type: "wellknown", key: "TEST_CONFIG_TOKEN", token: "test-token" }, }) + await expectSilentLifecycle() + }) + + test("an unreadable auth store does not rule out a well-known opt-out", async () => { + writeFileSync(Auth.filepath(), "{") + await expectSilentLifecycle() + }) + + test("a partial config cannot enable telemetry after an organization config load failed", async () => { + configSpy.mockResolvedValue({} as Awaited>) + const unresolved = spyOn(Config, "telemetryConfigUnresolved").mockReturnValue(true) try { await expectSilentLifecycle() } finally { - auth.mockRestore() + unresolved.mockRestore() } }) From 6ee41c41023f9551d7642b0c364626c613d8d632 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 21:51:04 -0800 Subject: [PATCH 03/63] test: check the shared telemetry opt-out gate --- .../telemetry/telemetry-opt-out-flag.test.ts | 200 +++--------------- 1 file changed, 35 insertions(+), 165 deletions(-) diff --git a/packages/opencode/test/telemetry/telemetry-opt-out-flag.test.ts b/packages/opencode/test/telemetry/telemetry-opt-out-flag.test.ts index d985834736..cdd9994f3d 100644 --- a/packages/opencode/test/telemetry/telemetry-opt-out-flag.test.ts +++ b/packages/opencode/test/telemetry/telemetry-opt-out-flag.test.ts @@ -1,181 +1,51 @@ -// v0.9.5 review — Chaos gremlin P1 + End-user P2, plus bot-review follow-ups -// (codex + coderabbit + cubic all named the same gap: the initial version of -// this file only tested the shared `Flag.truthyEnv` helper against -// `ALTIMATE_TELEMETRY_DISABLED`. That meant a regression that dropped the -// `OPENCODE_DISABLE_TELEMETRY` fallback OR removed the OR-composition at either -// call site (`altimate/plugin/altimate.ts::buildCliContext`, -// `altimate/telemetry/index.ts::doInit`) would still pass every test — the -// exact failure this file exists to prevent). -// -// The file now covers three layers: -// 1. Parser semantics — `Flag.truthyEnv` accepts "true"/"TRUE"/"1", rejects -// the everything-else surface (case sensitivity, whitespace, non-1 digits). -// 2. Consumer-boundary composition — the exact `truthyEnv(A) || truthyEnv(B)` -// shape used at both gate sites returns true when EITHER env var is set. -// 3. Gate-site source anchor — both `altimate.ts` and `telemetry/index.ts` -// reference both env-var names on the same line. Brittle by design: if a -// future edit deletes the fallback branch, this test catches it without -// needing to boot the full telemetry init in a unit test. -// -// Env-mutation isolation: each test snapshots the two vars before mutating -// them and restores what it found. This keeps the suite safe against other -// tests in the same process reading `process.env.ALTIMATE_TELEMETRY_DISABLED` -// or `OPENCODE_DISABLE_TELEMETRY` and against parallel suites in other -// packages (bot-review follow-up, coderabbit). - -import { afterEach, beforeEach, describe, expect, test } from "bun:test" -import fs from "fs" +import { afterEach, beforeEach, expect, test } from "bun:test" +import { readFileSync } from "fs" import path from "path" -import { Flag } from "../../src/flag/flag" - -const ALTIMATE_VAR = "ALTIMATE_TELEMETRY_DISABLED" -const OPENCODE_VAR = "OPENCODE_DISABLE_TELEMETRY" +import { TelemetryConfig } from "../../src/altimate/telemetry/config-state" -// Snapshot both env vars and restore them after each test — protects against -// leakage into or out of this suite regardless of what set them. -let snapshot: { altimate: string | undefined; opencode: string | undefined } +const keys = ["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY", "ALTIMATE_CLI_DISABLE_TELEMETRY"] +const saved = new Map() beforeEach(() => { - snapshot = { - altimate: process.env[ALTIMATE_VAR], - opencode: process.env[OPENCODE_VAR], + for (const key of keys) { + saved.set(key, process.env[key]) + delete process.env[key] } }) afterEach(() => { - if (snapshot.altimate === undefined) delete process.env[ALTIMATE_VAR] - else process.env[ALTIMATE_VAR] = snapshot.altimate - if (snapshot.opencode === undefined) delete process.env[OPENCODE_VAR] - else process.env[OPENCODE_VAR] = snapshot.opencode + for (const [key, value] of saved) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } }) -describe("Flag.truthyEnv — parser semantics on ALTIMATE_TELEMETRY_DISABLED", () => { - test("unset env var → false (default: telemetry enabled)", () => { - delete process.env[ALTIMATE_VAR] - expect(Flag.truthyEnv(ALTIMATE_VAR)).toBe(false) - }) - - test("empty string → false", () => { - process.env[ALTIMATE_VAR] = "" - expect(Flag.truthyEnv(ALTIMATE_VAR)).toBe(false) - }) - - test.each([ - ["true", true], - ["TRUE", true], - ["True", true], - ["1", true], - ["false", false], - ["FALSE", false], - ["0", false], - ["yes", false], - ["on", false], - [" true ", false], // no trimming — matches existing truthy() semantics - ["2", false], - ])("value %j → %s", (value, expected) => { - process.env[ALTIMATE_VAR] = value - expect(Flag.truthyEnv(ALTIMATE_VAR)).toBe(expected) - }) - - test("re-reads process.env on each call (not frozen at import)", () => { - delete process.env[ALTIMATE_VAR] - expect(Flag.truthyEnv(ALTIMATE_VAR)).toBe(false) - process.env[ALTIMATE_VAR] = "1" - expect(Flag.truthyEnv(ALTIMATE_VAR)).toBe(true) - process.env[ALTIMATE_VAR] = "false" - expect(Flag.truthyEnv(ALTIMATE_VAR)).toBe(false) - }) +test("an unset environment does not opt out", () => { + expect(TelemetryConfig.disablingEnvironmentVariable()).toBeUndefined() }) -describe("Consumer-boundary composition — both env vars route through the same OR gate", () => { - // The two production callers use `truthyEnv(A) || truthyEnv(B)`. These tests - // exercise both branches of that OR expression so a regression that hard-wires - // one branch to false would fail here (codex/coderabbit/cubic finding). - // - // We reproduce the composition inline via a local helper so the tests read - // as one unit rather than four permutations. The "gate-site anchor" tests - // below then prove the production callers actually contain this shape. - const gate = () => - Flag.truthyEnv(ALTIMATE_VAR) || Flag.truthyEnv(OPENCODE_VAR) - - test("neither set → gate is closed (telemetry enabled)", () => { - delete process.env[ALTIMATE_VAR] - delete process.env[OPENCODE_VAR] - expect(gate()).toBe(false) - }) - - test("only ALTIMATE_TELEMETRY_DISABLED set → gate is open (primary branch)", () => { - delete process.env[OPENCODE_VAR] - process.env[ALTIMATE_VAR] = "1" - expect(gate()).toBe(true) - }) - - test("only OPENCODE_DISABLE_TELEMETRY set → gate is open (fallback branch)", () => { - // v0.9.4 CHANGELOG advertised this name; before v0.9.5 it was silently - // ignored in product. Removing the second `truthyEnv(...)` from either - // call site would silently regress this — the source-anchor test below - // catches that additional shape. - delete process.env[ALTIMATE_VAR] - process.env[OPENCODE_VAR] = "1" - expect(gate()).toBe(true) - }) - - test.each([ - ["true", "true"], - ["1", "1"], - ["TRUE", "true"], - ])( - "both set (%j / %j) → gate is open", - (altimateVal, opencodeVal) => { - process.env[ALTIMATE_VAR] = altimateVal - process.env[OPENCODE_VAR] = opencodeVal - expect(gate()).toBe(true) - }, - ) - - test("both set with non-truthy values → gate is closed", () => { - process.env[ALTIMATE_VAR] = "false" - process.env[OPENCODE_VAR] = "0" - expect(gate()).toBe(false) - }) +test.each(["true", "TRUE", "True", "1"])("accepts %j", (value) => { + process.env.ALTIMATE_TELEMETRY_DISABLED = value + expect(TelemetryConfig.disablingEnvironmentVariable()).toBe("ALTIMATE_TELEMETRY_DISABLED") }) -describe("Gate-site anchor — both call sites reference both env-var names", () => { - // codex/coderabbit/cubic all pointed out that testing the shared helper in - // isolation doesn't prove the CALLER retains the fallback branch. Without an - // integration-level runner for `doInit()` / `buildCliContext` (both touch - // Config, machine-id, and a network sink), the closest deterministic proof is - // a source-shape assertion: both call sites must mention both env-var names - // within a small window. A future edit that deletes the fallback fails here - // and gives a clear name for what regressed. - // - // The window (a single non-comment line, or up to two adjacent non-comment - // lines) is deliberately narrow — enough for the OR expression to wrap to a - // second line for prettier, but not enough for the two names to sit in - // unrelated pieces of the file. - const GATE_FILES = [ - "src/altimate/plugin/altimate.ts", - "src/altimate/telemetry/index.ts", - ] +test.each(["", "false", "FALSE", "0", "yes", "on", " true ", "2"])("rejects %j", (value) => { + process.env.ALTIMATE_TELEMETRY_DISABLED = value + expect(TelemetryConfig.disablingEnvironmentVariable()).toBeUndefined() +}) - test.each(GATE_FILES)( - "%s references both %s and %s in the same gate", - (relativePath) => { - const absolute = path.resolve(__dirname, "../..", relativePath) - const source = fs.readFileSync(absolute, "utf8") - // Strip line comments so a `// mentions X and Y` comment doesn't count. - const codeLines = source - .split("\n") - .map((l) => l.replace(/\/\/.*$/, "").trim()) - const window = 2 - let matched = false - for (let i = 0; i < codeLines.length && !matched; i++) { - const slice = codeLines.slice(i, i + window).join(" ") - if (slice.includes(ALTIMATE_VAR) && slice.includes(OPENCODE_VAR)) { - matched = true - } - } - expect(matched).toBe(true) - }, - ) +test.each(keys)("%s opts out independently of the other names", (selected) => { + for (const key of keys) process.env[key] = "false" + process.env[selected] = "1" + expect(TelemetryConfig.disablingEnvironmentVariable()).toBe(selected) + process.env[selected] = "0" + expect(TelemetryConfig.disablingEnvironmentVariable()).toBeUndefined() }) + +test.each(["src/altimate/plugin/altimate.ts", "src/altimate/telemetry/index.ts"])( + "%s uses the shared opt-out", + (relativePath) => { + const source = readFileSync(path.resolve(__dirname, "../..", relativePath), "utf8") + expect(source).toMatch(/^[^/\n]*TelemetryConfig\.disablingEnvironmentVariable\(\)/m) + }, +) From 8e5dfa1ab355ced7b1ba3ba4e8c003ce5b4684fe Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 21:51:36 -0800 Subject: [PATCH 04/63] fix: treat account lookup failures as unresolved telemetry config --- packages/opencode/src/config/config.ts | 9 ++++-- packages/opencode/test/config/config.test.ts | 30 +++++++++++++++++++- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index ed318939f4..4152ee23bc 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -693,10 +693,15 @@ export const layer = Layer.effect( // altimate_change start — preserve resolution status for the telemetry opt-out gate let orgConfigUnresolved = false - // altimate_change end const activeAccount = Option.getOrUndefined( - yield* accountSvc.active().pipe(Effect.catch(() => Effect.succeed(Option.none()))), + yield* accountSvc.active().pipe( + Effect.catch(() => { + orgConfigUnresolved = true + return Effect.succeed(Option.none()) + }), + ), ) + // altimate_change end if (activeAccount?.active_org_id) { const accountID = activeAccount.id const orgID = activeAccount.active_org_id diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index f32e56f635..6e3498aec2 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -13,7 +13,7 @@ import { InstanceRef } from "../../src/effect/instance-ref" import type { InstanceContext } from "../../src/project/instance-context" import { Auth } from "../../src/auth" import { Account } from "../../src/account/account" -import { AccessToken, AccountID, OrgID } from "../../src/account/schema" +import { AccessToken, AccountID, AccountServiceError, OrgID } from "../../src/account/schema" import { FSUtil } from "@opencode-ai/core/fs-util" import { Env } from "../../src/env" import { @@ -687,9 +687,37 @@ accountTokenIt.instance("resolves env templates in account config with account t Effect.gen(function* () { const config = yield* Config.use.get() expect(config.provider?.["opencode"]?.options?.apiKey).toBe("st_test_token") + expect(Config.telemetryConfigUnresolved(config)).toBe(false) }), ) +for (const failure of ["account", "organization"] as const) { + const unavailable = Effect.fail(new AccountServiceError({ message: "Account config unavailable" })) + const failedAccountIt = configIt({ + account: Layer.mock(Account.Service)({ + active: () => + failure === "account" + ? unavailable + : Effect.succeed( + Option.some({ + id: AccountID.make("account-1"), + email: "user@example.com", + url: "https://control.example.com", + active_org_id: OrgID.make("org-1"), + }), + ), + config: () => unavailable, + token: () => Effect.succeed(Option.none()), + }), + }) + failedAccountIt.instance(`an unavailable ${failure} leaves the telemetry config unresolved`, () => + Effect.gen(function* () { + const config = yield* Config.use.get() + expect(Config.telemetryConfigUnresolved(config)).toBe(true) + }), + ) +} + it.instance("validates config schema and throws on invalid fields", () => Effect.gen(function* () { const test = yield* TestInstance From ff9b6fd6361edde91545b132855822580cdd18e4 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 21:54:54 -0800 Subject: [PATCH 05/63] fix: retry telemetry initialization after config becomes available --- .../opencode/src/altimate/telemetry/index.ts | 12 +++++++++- .../test/altimate/telemetry/opt-out.test.ts | 23 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 62bc304292..b7d9a7c07b 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2327,6 +2327,8 @@ export namespace Telemetry { let appInsights: AppInsightsConfig | undefined let droppedEvents = 0 let initPromise: Promise | undefined + // altimate_change — a pre-instance config read can defer this lifecycle until the next init call. + let startupConfigUnresolved = false let initDone = false // altimate_change — shutdown needs to cancel a flush already in flight, not just stop waiting // for it: `flush()` chains through inFlightFlush, so a timed-out drain still had its final @@ -2521,6 +2523,11 @@ export namespace Telemetry { } return reinitPromise } + if (startupConfigUnresolved) { + startupConfigUnresolved = false + initDone = false + return (initPromise = doInit()) + } return (initPromise ??= doInit()) // altimate_change end } @@ -2541,7 +2548,9 @@ export namespace Telemetry { const userConfig = (await Config.get()) disabled = userConfig.telemetry?.disabled === true || Config.telemetryConfigUnresolved(userConfig) } catch { - disabled = (await TelemetryConfig.disabledState(configDirectory)) !== "enabled" + const state = await TelemetryConfig.disabledState(configDirectory) + startupConfigUnresolved = state === "unreadable" + disabled = state !== "enabled" } if (disabled) { buffer = [] @@ -3093,6 +3102,7 @@ export namespace Telemetry { inFlightFlush = undefined shuttingDown = false enabled = false + startupConfigUnresolved = false appInsights = undefined buffer = [] droppedEvents = 0 diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 55968fb4ab..152c290ba3 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -190,6 +190,29 @@ describe("telemetry opt-out", () => { } }) + test("a later init can enable telemetry after the startup config resolves", async () => { + process.env.OPENCODE_CONFIG_CONTENT = "{" + await Telemetry.init() + expect(Telemetry.isEnabled()).toBe(false) + expect(fetchSpy).not.toHaveBeenCalled() + + configSpy.mockResolvedValue({ telemetry: { disabled: false } } as Awaited>) + await Telemetry.init() + expect(Telemetry.isEnabled()).toBe(true) + Telemetry.track({ + type: "startup_ready", + timestamp: Date.now(), + session_id: "", + command: "test", + surface: "test", + duration_ms: 1, + fresh_install: false, + }) + await Telemetry.flush() + expect(fetchSpy.mock.calls.some(([url]) => url === "https://ingest.example.invalid/v2/track")).toBe(true) + await Telemetry.refreshIdentity() + }) + test("an unreadable config suppresses all requests", async () => { process.env.OPENCODE_CONFIG_CONTENT = "{" await expectSilentLifecycle() From e43aaa55306d9964d9b44469543bf4dffe1e64e2 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:21:53 -0800 Subject: [PATCH 06/63] fix: hold telemetry until opt-out state resolves --- docs/docs/reference/security-faq.md | 2 +- docs/docs/reference/telemetry.md | 8 +- .../opencode/src/altimate/plugin/altimate.ts | 38 ++---- .../src/altimate/telemetry/config-state.ts | 90 +++++++++++--- .../src/altimate/telemetry/identity.ts | 3 +- .../opencode/src/altimate/telemetry/index.ts | 71 ++++++----- packages/opencode/src/auth/index.ts | 49 +++++++- packages/opencode/src/config/config.ts | 46 +++++-- packages/opencode/src/session/prompt.ts | 2 +- .../test/altimate/telemetry/opt-out.test.ts | 112 +++++++++++++++--- packages/opencode/test/config/config.test.ts | 77 ++++++++++++ .../test/install/install-telemetry.test.ts | 2 + .../telemetry/telemetry-opt-out-flag.test.ts | 2 +- 13 files changed, 385 insertions(+), 117 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index 690368538e..cf4c701ccf 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -183,7 +183,7 @@ No code, queries, file paths, or personal information is included. This event he The install scripts (`altimate.sh/install`, `install.ps1`), the npm postinstall, and the VS Code extension's installer send nothing themselves and contact no telemetry endpoint. They only record the version and installer name to a local file that the CLI reads on its next run, so the opt-out above decides whether anything is ever transmitted. -The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If startup cannot determine the config setting, it suppresses telemetry. +The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED` or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. ## What happens when I authenticate via a well-known URL? diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index a5c162dd41..5d41eca2d0 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -87,7 +87,7 @@ We collect the following categories of events: | `plugin_session_start` | A Claude Code session started with the Altimate Code plugin, sent by the plugin through `altimate-code tool report-event`. Its payload is the plugin version, this altimate-code's version (`altimate_code_version`), the OS as Claude Code names it (`host_os`: `macos`, `linux`, `windows`, `wsl` or `unknown`; named apart from the `os` other events carry as `process.platform`) and the plugin's anonymous install id (a random UUID the plugin makes on first run and keeps in its Claude Code plugin store). It carries no session id, machine id, project id or account (`user_id`, `tenant`), nor the per-launch `launch_id`, so it cannot be joined to the CLI's other events: beside its own fields, only `cli_version`, `client` and `source`, keyed to the install id (`ai.user.id`). It is sent in a request of its own, never in one batch with the CLI's other events. | | `plugin_feature_used` | One of the plugin's panels or commands was opened (`lineage`, `dbt_show`, `profile_ctes`, `scan_cost`, `comments`, `sql_graph`, `health`, `runs`, `to_model`), or one of its gates held or allowed a command (`cost_gate`, `health_push_gate`). Its payload is the feature, the outcome (`opened`; `failed` when the panel could not open; `held` or `allowed` for a gate), the plugin version and the install id: no model, column, file or project names, SQL or session text. Like `plugin_session_start`, it carries no session id, machine id, project id, launch id or account: beside its own fields, only `cli_version`, `client` and `source`, keyed to the install id. | -Each event (except the plugin's `plugin_session_start` and `plugin_feature_used`, described above) includes a timestamp, session ID, a per-launch correlation ID (`launch_id` — a random value regenerated every process start, not persisted and not derived from your machine or identity; it exists only to group events from the same run), CLI version, and a machine ID (a random UUID stored in `~/.altimate/machine-id`, generated once and not derived from your hardware or identity). When the machine is signed in to Altimate, each event also carries `user_id` and `tenant`, described under [User Identification](#new-user-identification). +Each event (except the plugin's `plugin_session_start` and `plugin_feature_used`, described above) includes a timestamp, session ID, a per-launch correlation ID (`launch_id` — a random value regenerated every process start, not persisted and not derived from your machine or identity; it exists only to group events from the same run), CLI version, and a machine ID when available (a random UUID stored in `~/.altimate/machine-id`, generated once and not derived from your hardware or identity). Signed-in events carry `user_id` and `tenant` once account identity resolves. See [User Identification](#new-user-identification). ### Workspace events @@ -182,7 +182,7 @@ You can also set the environment variable: export ALTIMATE_TELEMETRY_DISABLED=true ``` -`ALTIMATE_CLI_DISABLE_TELEMETRY` and `OPENCODE_DISABLE_TELEMETRY` are also supported. Each variable accepts `1` or `true` (case-insensitive). +`OPENCODE_DISABLE_TELEMETRY` is also supported. Each variable accepts `1` or `true` (case-insensitive). When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. If startup cannot determine the config setting, it suppresses telemetry. This includes startup before a configured remote source that could set the flag has been loaded. @@ -227,11 +227,11 @@ What identifies the sender of an event depends on whether the machine is signed The Claude Code plugin's `plugin_session_start` and `plugin_feature_used` are the exception: signed in or not, they carry neither the machine ID nor your account, and their `ai.user.id` is the plugin's own random install id. -These identifiers are sent only while telemetry is enabled. No telemetry `/users/me` lookup is made while telemetry is disabled. Disable telemetry entirely with `ALTIMATE_TELEMETRY_DISABLED=true` or the config option above. +These identifiers are sent only while telemetry is enabled. While the opt-out setting is unresolved, Altimate Code holds events in a bounded in-memory buffer and skips telemetry requests, including the `/users/me` lookup. If a later initialization resolves telemetry as enabled, it sends the queued events. If it resolves as disabled or the process exits while the setting is still unresolved, it discards them. ### CLI Authentication Flow -When you sign in using the CLI browser auth flow (`altimate auth login`), the anonymous machine ID (a random UUID persisted at `~/.altimate/machine-id` — a device/installation identifier, reused across sessions) is included in the authorization URL and associated with your account in product analytics. This is used solely to correlate CLI install events with authenticated accounts in aggregate funnel analytics — it is not used for advertising or cross-site tracking. Your telemetry opt-out suppresses this: when you disable telemetry — via `ALTIMATE_TELEMETRY_DISABLED=true` **or** the `telemetry.disabled` config option — the machine ID is omitted from the authorization URL entirely. The machine ID is associated with your account in PostHog for this funnel analysis, separate from the Azure Application Insights pipeline used for other CLI telemetry events. +When you sign in using the CLI browser auth flow (`altimate auth login`), the anonymous machine ID (a random UUID persisted at `~/.altimate/machine-id` — a device/installation identifier, reused across sessions) is included in the authorization URL and associated with your account in product analytics. This is used solely to correlate CLI install events with authenticated accounts in aggregate funnel analytics — it is not used for advertising or cross-site tracking. Your telemetry opt-out suppresses this: when you disable telemetry — via `ALTIMATE_TELEMETRY_DISABLED=true`, `OPENCODE_DISABLE_TELEMETRY=true`, or the `telemetry.disabled` config option — the machine ID is omitted from the authorization URL entirely. The machine ID is associated with your account in PostHog for this funnel analysis, separate from the Azure Application Insights pipeline used for other CLI telemetry events. ### Data Retention diff --git a/packages/opencode/src/altimate/plugin/altimate.ts b/packages/opencode/src/altimate/plugin/altimate.ts index 84b5133f6c..40f4ae3b60 100644 --- a/packages/opencode/src/altimate/plugin/altimate.ts +++ b/packages/opencode/src/altimate/plugin/altimate.ts @@ -1,6 +1,7 @@ import type { Hooks, PluginInput } from "@opencode-ai/plugin" import { createServer } from "http" import { randomBytes } from "crypto" +import path from "path" import open from "open" import { AltimateApi } from "../api/client" // altimate_change — onboarding telemetry for the gateway sign-in funnel @@ -8,7 +9,6 @@ import * as OnboardingTelemetry from "../telemetry/onboarding" import { Telemetry } from "../telemetry" // altimate_change — shared machine-id helper (race-safe, UUID-validated, size-capped) import { getOrCreateMachineId } from "../util/machine-id" -import { Config } from "@/config/config" import { InstallationVersion } from "@opencode-ai/core/installation/version" import { Log } from "@/altimate/util/log" // altimate_change — reads the config telemetry opt-out without an Instance @@ -82,31 +82,17 @@ export async function buildCliContext(machineIdPath?: string, directory?: string // altimate_change start — apply the same opt-out to the auth URL’s machine ID let disabled = Boolean(TelemetryConfig.disablingEnvironmentVariable()) if (!disabled) { - try { - const userConfig = await Config.get() - disabled = userConfig.telemetry?.disabled === true || Config.telemetryConfigUnresolved(userConfig) - } catch (err) { - // Config was unreadable — NOT the normal path. Server routes run inside - // Instance.provide() (AsyncLocalStorage-propagated across awaits), so - // Config.get() resolves during an ordinary browser authorize(). It fires on - // the paths that skip instance bootstrap: `altimate auth login ` and the - // create-and-link hand-off of `altimate-code link`. Read `telemetry.disabled` - // from the config files directly: an opt-out there, or files that cannot be - // read (an opt-out may be behind them), omit the id. Only a config that - // readably leaves telemetry on defers to the telemetry module's own state - // (opted out by env, no sink, test runner). - const state = await TelemetryConfig.disabledState(directory) - if (state === "enabled") { - await Telemetry.init().catch(() => {}) - disabled = !Telemetry.isEnabled() - } else { - disabled = true - } - log.info("cli_context: config unavailable, read the opt-out from the files", { - code: (err as NodeJS.ErrnoException)?.code, - state, - enabled: !disabled, - }) + const instance = TelemetryConfig.instanceDirectory() + const differentProject = instance && directory && path.resolve(directory) !== instance + const state = differentProject + ? undefined + : await TelemetryConfig.loadedState().catch(() => instance ? "unreadable" : undefined) + if (state) { + disabled = state !== "enabled" + } else { + const local = await TelemetryConfig.disabledState(directory) + if (local === "enabled") await Telemetry.init().catch(() => {}) + disabled = local !== "enabled" || !Telemetry.isEnabled() } } let machineId = "" diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index cac7a1a297..ac435dfc48 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -3,6 +3,8 @@ import path from "path" import fs from "fs/promises" import { existsSync } from "fs" import * as Effect from "effect/Effect" +import { InstanceRef } from "@/effect/instance-ref" +import { attach } from "@/effect/run-service" import { Flag, env as flagEnv } from "@opencode-ai/core/flag/flag" import { FSUtil } from "@opencode-ai/core/fs-util" import { Database } from "@opencode-ai/core/database/database" @@ -10,7 +12,7 @@ import { Auth } from "@/auth" import { Global } from "../../global" import { ConfigPaths } from "@/config/paths" import { ConfigManaged } from "@/config/managed" -import { validateLoaded } from "@/config/config" +import { Config, validateLoaded } from "@/config/config" /** * Whether the user config turns telemetry off, read without an Instance. @@ -48,42 +50,94 @@ function worktreeOf(directory: string): string | undefined { } export function disablingEnvironmentVariable(): string | undefined { - return ["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY", "ALTIMATE_CLI_DISABLE_TELEMETRY"].find((key) => + return ["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY"].find((key) => /^(true|1)$/i.test(process.env[key] ?? ""), ) } -async function hasWellKnownSource(): Promise { +async function authEntries(): Promise> { let contents = process.env.OPENCODE_AUTH_CONTENT if (!contents) { try { contents = await fs.readFile(Auth.filepath(), "utf8") } catch (error) { - if ((error as NodeJS.ErrnoException)?.code === "ENOENT") return false + if ((error as NodeJS.ErrnoException)?.code === "ENOENT") return {} throw error } } - const entries = JSON.parse(contents) as Record - return Object.values(entries).some((entry) => entry?.type === "wellknown") + const entries: unknown = JSON.parse(contents) + if (!entries || typeof entries !== "object" || Array.isArray(entries)) { + throw new Error("Invalid auth store") + } + const values = Object.values(entries) + for (const entry of values) { + if (!entry || typeof entry !== "object" || !("type" in entry) || entry.type !== "wellknown") continue + if (!("key" in entry && typeof entry.key === "string" && "token" in entry && typeof entry.token === "string")) { + throw new Error("Invalid well-known auth entry") + } + } + return entries as Record +} + +export function instanceDirectory(): string | undefined { + return Effect.runSync(attach(InstanceRef))?.directory +} + +export async function loadedState(retry = false): Promise { + const config = await Config.get(retry) + if (Config.telemetryConfigUnresolved(config)) return "unreadable" + // Auth.all() can return an empty store when its read or parse fails. + try { + await authEntries() + } catch { + return "unreadable" + } + return config.telemetry?.disabled ? "disabled" : "enabled" +} + +export async function resolve(directory?: string, retry = false): Promise { + try { + return await loadedState(retry) + } catch { + // A failed full load can hide remote settings. The local probe is only for + // commands that have no instance to load yet. + return instanceDirectory() ? "unreadable" : disabledState(directory) + } } -// The well-known config merges before local files, while an active organization's config can -// override them. Inspect only local credentials and account state; never fetch config here. async function remoteMayDisable(local: boolean | undefined): Promise { - if (local === undefined && (await hasWellKnownSource())) return true + const auth = await authEntries() + if (local === undefined && Object.values(auth).some((entry) => + entry && typeof entry === "object" && "type" in entry && entry.type === "wellknown" + )) return true - // No on-disk account state to inspect. Avoid opening or creating a database on a fresh install. const dbPath = Database.path() - if (dbPath === ":memory:") return false - try { - await fs.stat(dbPath) - } catch (error) { - if ((error as NodeJS.ErrnoException)?.code === "ENOENT") return false + if (dbPath === ":memory:") return true + + // Only read a WAL database. In rollback-journal mode even a short SELECT + // takes a shared lock that can block a writer's commit. + const header = await fs.open(dbPath, "r").catch((error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return undefined throw error + }) + if (!header) return false + try { + const versions = Buffer.alloc(2) + const { bytesRead } = await header.read(versions, 0, 2, 18) + if (bytesRead !== 2 || versions[0] !== 2 || versions[1] !== 2) return true + } finally { + await header.close() } - // Use a read-only connection so this check cannot run migrations or initialize account storage. + const db = new SQLite(dbPath, { readonly: true }) try { + db.exec("PRAGMA busy_timeout = 0") + // If the journal mode changed since the header read, defer to the full loader. + if (db.query<{ journal_mode: string }, []>("PRAGMA journal_mode").get()?.journal_mode !== "wal") return true + const tables = db.query<{ count: number }, []>( + "SELECT count(*) AS count FROM sqlite_schema WHERE name IN ('account', 'account_state') AND type = 'table'", + ).get() + if (tables?.count !== 2) return false // A pre-migration database cannot select an organization. return db.query(`SELECT 1 FROM account_state JOIN account ON account.id = account_state.active_account_id WHERE account_state.id = 1 AND account_state.active_org_id IS NOT NULL`).get() !== null @@ -166,8 +220,8 @@ export async function disabledState(directory: string = process.cwd()): Promise< if (managed) await readText(managed.text, managed.source, path.dirname(managed.source)) if (unknown) return "unreadable" - if (value === true) return "disabled" - return (await remoteMayDisable(value)) ? "unreadable" : "enabled" + if (await remoteMayDisable(value)) return "unreadable" + return value === true ? "disabled" : "enabled" } catch { return "unreadable" } diff --git a/packages/opencode/src/altimate/telemetry/identity.ts b/packages/opencode/src/altimate/telemetry/identity.ts index 23625b2cf5..c2bb1d912e 100644 --- a/packages/opencode/src/altimate/telemetry/identity.ts +++ b/packages/opencode/src/altimate/telemetry/identity.ts @@ -135,7 +135,7 @@ export type Outcome = "ok" | "none" | "rejected" | "error" /** {@link resolve}, also saying how it ended, so a caller retries only a transient failure. */ export async function resolveWithOutcome( - opts: { refresh?: boolean } = {}, + opts: { refresh?: boolean; canSend?: () => boolean } = {}, ): Promise<{ identity?: Identity; outcome: Outcome }> { try { const creds = await loadCredential() @@ -149,6 +149,7 @@ export async function resolveWithOutcome( if (hit && hit.fingerprint === fp) return { identity: { user_id: hit.user_id, tenant: hit.tenant }, outcome: "ok" } } + if (opts.canSend && !opts.canSend()) return { outcome: "none" } const answer = await fetchMe(creds) if (answer.kind === "rejected") { const hit = await readCache() diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index b7d9a7c07b..7aaadb238b 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -1,4 +1,3 @@ -import { Config } from "@/config/config" import { Flag } from "@/flag/flag" import { InstallationVersion } from "@opencode-ai/core/installation/version" import { Log } from "@/altimate/util/log" @@ -2327,8 +2326,8 @@ export namespace Telemetry { let appInsights: AppInsightsConfig | undefined let droppedEvents = 0 let initPromise: Promise | undefined - // altimate_change — a pre-instance config read can defer this lifecycle until the next init call. - let startupConfigUnresolved = false + // altimate_change — unresolved config holds events for the next init call. + let configUnresolved = false let initDone = false // altimate_change — shutdown needs to cancel a flush already in flight, not just stop waiting // for it: `flush()` chains through inFlightFlush, so a timed-out drain still had its final @@ -2523,10 +2522,18 @@ export namespace Telemetry { } return reinitPromise } - if (startupConfigUnresolved) { - startupConfigUnresolved = false + if (!initDone && initPromise && TelemetryConfig.instanceDirectory()) { + // A session can join the middleware init while its local probe is still running. + // Retry once from the session's context when the probe could not resolve config. + const pending = initPromise + return pending.then(() => { + if (initPromise !== pending) return initPromise + if (!shutdownPromise && configUnresolved) return init() + }) + } + if (initDone && configUnresolved) { + initPromise = undefined initDone = false - return (initPromise = doInit()) } return (initPromise ??= doInit()) // altimate_change end @@ -2534,26 +2541,22 @@ export namespace Telemetry { async function doInit() { try { - // altimate_change — ALTIMATE_TELEMETRY_DISABLED and either spelling of the legacy opt-out - // act independently, so a false alias cannot override a truthy opt-out. + // altimate_change start — hold bounded startup events until the opt-out is resolved. + const retry = configUnresolved + configUnresolved = false if (TelemetryConfig.disablingEnvironmentVariable()) { buffer = [] + droppedEvents = 0 return } - // altimate_change start — verify the opt-out before initializing either telemetry transport. - // CLI middleware can run before Instance.provide(), so fall back to the local config files. - // Suppress telemetry when the config state is unknown, since it may contain an opt-out. - let disabled: boolean - try { - const userConfig = (await Config.get()) - disabled = userConfig.telemetry?.disabled === true || Config.telemetryConfigUnresolved(userConfig) - } catch { - const state = await TelemetryConfig.disabledState(configDirectory) - startupConfigUnresolved = state === "unreadable" - disabled = state !== "enabled" + const state = await TelemetryConfig.resolve(configDirectory, retry) + if (state === "unreadable") { + configUnresolved = true + return } - if (disabled) { + if (state === "disabled") { buffer = [] + droppedEvents = 0 return } // altimate_change end @@ -2599,7 +2602,7 @@ export namespace Telemetry { // altimate_change start — first-run health: drain anchor events that were tracked before init // finished (first_launch always is) instead of leaving them to the 5 s interval a startup freeze // would block. The stall watcher starts in `finally`, telemetry or not. - if (buffer.some((event) => ANCHOR_EVENTS.has(event.type))) void Telemetry.flush().catch(() => {}) + if (retry || buffer.some((event) => ANCHOR_EVENTS.has(event.type))) void Telemetry.flush().catch(() => {}) // altimate_change end } catch { buffer = [] @@ -2662,7 +2665,10 @@ export namespace Telemetry { const generation = ++identityGeneration identityStamp = TelemetryIdentity.credentialStamp() identityRetryAt = 0 - return TelemetryIdentity.resolveWithOutcome(opts) + return TelemetryIdentity.resolveWithOutcome({ + ...opts, + canSend: () => generation === identityGeneration && !shutdownPromise, + }) .then(({ identity: resolved, outcome }) => { if (generation !== identityGeneration) return identity = resolved @@ -2869,9 +2875,8 @@ export namespace Telemetry { // altimate_change end export function track(event: Event) { - // Before init completes: buffer (flushed once init enables, or cleared if disabled). - // After init completed and disabled telemetry: drop silently. - if (initDone && !enabled) return + // Buffer during init and while config is unresolved. A resolved opt-out drops events. + if (initDone && !enabled && !configUnresolved) return // altimate_change start — stamp the client trace of the turn the event's own session is // running, now: the event is serialised at flush time, when that turn may be over. Only an // explicit per-event `session_id` is used — the process-global session can be another one. @@ -2924,7 +2929,7 @@ export namespace Telemetry { // change on disk and re-resolve (cheap: two stats, and the cache answers unless the key changed). const who = identity const mid = machineId - if (enabled) { + if (enabled && !shuttingDown) { const stamp = TelemetryIdentity.credentialStamp() const retryDue = identityRetryAt !== 0 && Date.now() >= identityRetryAt if (stamp !== identityStamp || retryDue) { @@ -3021,7 +3026,7 @@ export namespace Telemetry { // `timeoutMs` bounds the flush from the inside. Racing shutdown() against an external timer // does NOT cancel it: the losing promise keeps running and resets module state after the // caller has already moved on. Exit paths pass a budget so the fetch itself is aborted. - export async function shutdown(opts?: { timeoutMs?: number }) { + export async function shutdown(opts?: { timeoutMs?: number; preserveUnresolved?: boolean }) { if (shutdownPromise) { // An earlier caller is mid-flush, possibly on the default 10s budget. Returning its promise // unchanged would silently ignore this caller's deadline and make the exit path wait past @@ -3039,13 +3044,13 @@ export namespace Telemetry { if (timer) clearTimeout(timer) return } - shutdownPromise = doShutdown(opts?.timeoutMs).finally(() => { + shutdownPromise = doShutdown(opts?.timeoutMs, opts?.preserveUnresolved).finally(() => { shutdownPromise = undefined }) return shutdownPromise } - async function doShutdown(timeoutMs?: number) { + async function doShutdown(timeoutMs?: number, preserveUnresolved?: boolean) { const initPromiseAtShutdown = initPromise // Wait for init to complete so we know whether telemetry is enabled // and have a valid endpoint to flush to. init() is fire-and-forget @@ -3102,10 +3107,12 @@ export namespace Telemetry { inFlightFlush = undefined shuttingDown = false enabled = false - startupConfigUnresolved = false appInsights = undefined - buffer = [] - droppedEvents = 0 + if (!preserveUnresolved || !configUnresolved) { + configUnresolved = false + buffer = [] + droppedEvents = 0 + } sessionId = "" projectId = "" machineId = "" diff --git a/packages/opencode/src/auth/index.ts b/packages/opencode/src/auth/index.ts index c06d17254d..9aabd2e593 100644 --- a/packages/opencode/src/auth/index.ts +++ b/packages/opencode/src/auth/index.ts @@ -67,6 +67,14 @@ export interface Interface { export class Service extends Context.Service()("@opencode/Auth.cli") {} // altimate_change end +// altimate_change start — Config needs to know when a tolerant auth read may hide remote config. +const incompleteStores = new WeakSet>() + +export function configSourcesUnresolved(store: Record): boolean { + return incompleteStores.has(store) +} +// altimate_change end + export const layer = Layer.effect( Service, Effect.gen(function* () { @@ -74,14 +82,45 @@ export const layer = Layer.effect( const decode = Schema.decodeUnknownOption(Info) const all = Effect.fn("Auth.all")(function* () { - if (process.env.OPENCODE_AUTH_CONTENT) { + // altimate_change start — preserve unreadable stores and invalid well-known entries for Config. + let incomplete = false + let data: Record | undefined + const parseStore = (text: string) => { try { - return JSON.parse(process.env.OPENCODE_AUTH_CONTENT) - } catch (err) {} + const parsed: unknown = JSON.parse(text) + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed as Record + } catch {} + incomplete = true + return undefined } - const data = (yield* fsys.readJson(file).pipe(Effect.orElseSucceed(() => ({})))) as Record - return Record.filterMap(data, (value) => Result.fromOption(decode(value), () => undefined)) + if (process.env.OPENCODE_AUTH_CONTENT) { + data = parseStore(process.env.OPENCODE_AUTH_CONTENT) + if (data) { + const inline = data as Record + if (Object.values(inline).some((value) => value?.type === "wellknown" && decode(value)._tag === "None")) { + incompleteStores.add(inline) + } + return inline + } + } + if (!data) { + const text = yield* fsys.readFileStringSafe(file).pipe(Effect.catch(() => { + incomplete = true + return Effect.succeed(undefined) + })) + data = text === undefined ? {} : parseStore(text) ?? {} + } + const store = Record.filterMap(data, (value) => { + const auth = decode(value) + if (auth._tag === "None" && value && typeof value === "object" && "type" in value && value.type === "wellknown") { + incomplete = true + } + return Result.fromOption(auth, () => undefined) + }) + if (incomplete) incompleteStores.add(store) + return store + // altimate_change end }) const get = Effect.fn("Auth.get")(function* (providerID: string) { diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 4152ee23bc..53c66e34a8 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -48,14 +48,15 @@ import { ConfigVariable } from "./variable" import { Npm } from "@opencode-ai/core/npm" import { withTransientReadRetry } from "@/util/effect-http-client" // altimate_change start — makeRuntime for the restored Promise wrappers (see bottom of file) -import { makeRuntime } from "@/effect/run-service" +import { attach, makeRuntime } from "@/effect/run-service" +import { InstanceRef } from "@/effect/instance-ref" // altimate_change end -// altimate_change start — keep telemetry off when an organization config was unavailable -const configsWithUnresolvedOrg = new WeakSet() +// altimate_change start — defer telemetry when any config layer was unavailable +const configsWithUnresolvedTelemetry = new WeakSet() export function telemetryConfigUnresolved(config: Info): boolean { - return configsWithUnresolvedOrg.has(config) + return configsWithUnresolvedTelemetry.has(config) } // altimate_change end @@ -270,7 +271,7 @@ type State = { } export interface Interface { - readonly get: () => Effect.Effect + readonly get: (retryTelemetry?: boolean) => Effect.Effect // altimate_change — retry partial telemetry config readonly getGlobal: () => Effect.Effect readonly getConsoleState: () => Effect.Effect readonly update: (config: Info) => Effect.Effect @@ -430,6 +431,8 @@ export const layer = Layer.effect( return yield* loadConfig(text, { path: filepath }, env) }) + // altimate_change — the legacy loader can return partial config after an unreadable TOML file. + const incompleteGlobals = new WeakSet() const loadGlobal = Effect.fnUntraced(function* (env?: Record) { let result: Info = {} // Seed the default global config with the schema for editor completion, but avoid writing when the user @@ -466,7 +469,11 @@ export const layer = Layer.effect( await fsNode.writeFile(path.join(Global.Path.config, "config.json"), JSON.stringify(result, null, 2)) await fsNode.unlink(legacy) }) - .catch(() => {}), + // altimate_change start — preserve the failure for the telemetry gate + .catch(() => { + incompleteGlobals.add(result) + }), + // altimate_change end ) } @@ -478,7 +485,13 @@ export const layer = Layer.effect( Effect.tapError((error) => Effect.logError("failed to load global config, using defaults", { error: String(error) }), ), - Effect.orElseSucceed((): Info => ({})), + // altimate_change start — a global fallback can hide an opt-out + Effect.orElseSucceed((): Info => { + const fallback: Info = {} + incompleteGlobals.add(fallback) + return fallback + }), + // altimate_change end ), Duration.infinity, ) @@ -913,7 +926,9 @@ export const layer = Layer.effect( // altimate_change end // altimate_change start — associate the status with this resolved config object - if (orgConfigUnresolved) configsWithUnresolvedOrg.add(result) + if (orgConfigUnresolved || incompleteGlobals.has(global) || Auth.configSourcesUnresolved(auth)) { + configsWithUnresolvedTelemetry.add(result) + } // altimate_change end return { @@ -947,9 +962,16 @@ export const layer = Layer.effect( }), ) - const get = Effect.fn("Config.get")(function* () { + // altimate_change start — reload partial config for the current instance on telemetry retry + const get = Effect.fn("Config.get")(function* (retryTelemetry = false) { + const cached = retryTelemetry && (yield* InstanceState.has(state)) + const config = yield* InstanceState.use(state, (s) => s.config) + if (!cached || !telemetryConfigUnresolved(config)) return config + yield* invalidateGlobal + yield* InstanceState.invalidate(state) return yield* InstanceState.use(state, (s) => s.config) }) + // altimate_change end const directories = Effect.fn("Config.directories")(function* () { return yield* InstanceState.use(state, (s) => s.directories) @@ -1057,8 +1079,10 @@ export const node = LayerNode.make(layer, () => [FSUtil.node, Auth.node, Account // call `await Config.get()` etc. The makeRuntime bridge's `attach()` reads WorkspaceContext + // the current fiber's InstanceRef, so these reads stay bound to the active workspace/instance. const { runPromise: runConfig } = makeRuntime(Service, defaultLayer) -export async function get() { - return runConfig((svc) => svc.get()) +export async function get(retryTelemetry = false) { + // Reject before building the runtime and opening its database without an instance. + if (!Effect.runSync(attach(InstanceRef))) throw new Error("InstanceRef not provided") + return runConfig((svc) => svc.get(retryTelemetry)) } export async function getGlobal() { return runConfig((svc) => svc.getGlobal()) diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 93187d0201..5a18c2a7b0 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -2796,7 +2796,7 @@ export namespace SessionPrompt { }) Telemetry.endSession(sessionID, telemetryTurn) // altimate_change — after the row, this turn only } - await Telemetry.shutdown() + await Telemetry.shutdown({ preserveUnresolved: true }) // altimate_change end // altimate_change start — resolve callbacks from this prompt generation only for (const item of orderedMessageStream(readMessageOrder())) { diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 152c290ba3..d37f1eaa4b 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -7,6 +7,7 @@ import { Database } from "@opencode-ai/core/database/database" import { Auth } from "../../../src/auth" import { Config } from "../../../src/config/config" import { Telemetry } from "../../../src/altimate/telemetry" +import { TelemetryConfig } from "../../../src/altimate/telemetry/config-state" const CS = "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://ingest.example.invalid/" const ENV = [ @@ -17,7 +18,6 @@ const ENV = [ "ALTIMATE_TELEMETRY_FORCE", "OPENCODE_CONFIG_CONTENT", "ALTIMATE_CLI_CONFIG_CONTENT", - "ALTIMATE_CLI_DISABLE_TELEMETRY", "OPENCODE_AUTH_CONTENT", ] as const @@ -27,6 +27,7 @@ describe("telemetry opt-out", () => { let configSpy: ReturnType> let homedirSpy: ReturnType> let authFileSpy: ReturnType> + let databaseSpy: ReturnType> let authSpy: ReturnType> const saved: Record = {} @@ -34,7 +35,7 @@ describe("telemetry opt-out", () => { await Telemetry.shutdown() home = mkdtempSync(path.join(os.tmpdir(), "telemetry-opt-out-")) mkdirSync(path.join(home, ".altimate")) - // Simulate a previously signed-in installation with an ID and no opt-out marker. + // Simulate a previously signed-in installation with a machine ID. writeFileSync(path.join(home, ".altimate", "machine-id"), "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d") writeFileSync( path.join(home, ".altimate", "altimate.json"), @@ -53,6 +54,7 @@ describe("telemetry opt-out", () => { Telemetry.setConfigDirectory(home) homedirSpy = spyOn(os, "homedir").mockReturnValue(home) authFileSpy = spyOn(Auth, "filepath").mockReturnValue(path.join(home, "auth.json")) + databaseSpy = spyOn(Database, "path").mockReturnValue(path.join(home, "missing.db")) authSpy = spyOn(Auth, "get").mockResolvedValue(undefined) configSpy = spyOn(Config, "get").mockRejectedValue(new Error("InstanceRef not provided")) fetchSpy = spyOn(globalThis, "fetch").mockRejectedValue(new Error("Telemetry must not invoke the transport")) @@ -66,6 +68,7 @@ describe("telemetry opt-out", () => { homedirSpy.mockRestore() authFileSpy.mockRestore() authSpy.mockRestore() + databaseSpy.mockRestore() for (const key of ENV) { if (saved[key] === undefined) delete process.env[key] else process.env[key] = saved[key] @@ -120,7 +123,7 @@ describe("telemetry opt-out", () => { expect(enabled).toBe(false) } - test.each(["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY", "ALTIMATE_CLI_DISABLE_TELEMETRY"])("%s suppresses all requests", async (key) => { + test.each(["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY"])("%s suppresses all requests", async (key) => { process.env[key] = "1" await expectSilentLifecycle() // A later launch must also stay silent with the same existing machine ID. @@ -128,7 +131,7 @@ describe("telemetry opt-out", () => { }) test("a false canonical alias cannot override the legacy opt-out", async () => { - process.env.ALTIMATE_CLI_DISABLE_TELEMETRY = "false" + process.env.ALTIMATE_TELEMETRY_DISABLED = "false" process.env.OPENCODE_DISABLE_TELEMETRY = "1" await expectSilentLifecycle() }) @@ -176,29 +179,39 @@ describe("telemetry opt-out", () => { const dbPath = path.join(home, "account.db") const db = new SQLite(dbPath) db.exec(` + PRAGMA journal_mode = WAL; CREATE TABLE account (id TEXT PRIMARY KEY); CREATE TABLE account_state (id INTEGER PRIMARY KEY, active_account_id TEXT, active_org_id TEXT); INSERT INTO account VALUES ('account'); INSERT INTO account_state VALUES (1, 'account', 'org'); `) db.close() - const database = spyOn(Database, "path").mockReturnValue(dbPath) + databaseSpy.mockReturnValue(dbPath) + await expectSilentLifecycle() + }) + + test("the startup probe can read while an account writer holds a WAL transaction", async () => { + const dbPath = path.join(home, "account.db") + const writer = new SQLite(dbPath) try { - await expectSilentLifecycle() + writer.exec(` + PRAGMA journal_mode = WAL; + CREATE TABLE account (id TEXT PRIMARY KEY); + CREATE TABLE account_state (id INTEGER PRIMARY KEY, active_account_id TEXT, active_org_id TEXT); + INSERT INTO account VALUES ('account'); + BEGIN IMMEDIATE; + INSERT INTO account_state VALUES (1, 'account', 'org'); + `) + databaseSpy.mockReturnValue(dbPath) + expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + writer.exec("COMMIT") + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") } finally { - database.mockRestore() + writer.close() } }) - test("a later init can enable telemetry after the startup config resolves", async () => { - process.env.OPENCODE_CONFIG_CONTENT = "{" - await Telemetry.init() - expect(Telemetry.isEnabled()).toBe(false) - expect(fetchSpy).not.toHaveBeenCalled() - - configSpy.mockResolvedValue({ telemetry: { disabled: false } } as Awaited>) - await Telemetry.init() - expect(Telemetry.isEnabled()).toBe(true) + function trackStartup() { Telemetry.track({ type: "startup_ready", timestamp: Date.now(), @@ -208,9 +221,74 @@ describe("telemetry opt-out", () => { duration_ms: 1, fresh_install: false, }) + } + + function recordIngestion() { + const names: string[] = [] + fetchSpy.mockImplementation(Object.assign(async (url: Parameters[0], request?: Parameters[1]) => { + if (url !== "https://ingest.example.invalid/v2/track") throw new Error("Unexpected telemetry request") + for (const envelope of JSON.parse(String(request?.body))) names.push(envelope.data.baseData.name) + return new Response(null, { status: 204 }) + }, { preconnect: fetch.preconnect })) + return names + } + + test("a later init sends held startup events exactly once", async () => { + const names = recordIngestion() + process.env.OPENCODE_CONFIG_CONTENT = "{" + trackStartup() + await Telemetry.init() + await Telemetry.refreshIdentity() + await Telemetry.flush() + expect(fetchSpy).not.toHaveBeenCalled() + + rmSync(path.join(home, ".altimate", "altimate.json")) + configSpy.mockResolvedValue({ telemetry: { disabled: false } }) + await Telemetry.init() + await Telemetry.flush() + await Telemetry.shutdown() + expect(names).toEqual(["startup_ready"]) + }) + + test("resolution to disabled discards held startup events", async () => { + const names = recordIngestion() + process.env.OPENCODE_CONFIG_CONTENT = "{" + trackStartup() + await Telemetry.init() + configSpy.mockResolvedValue({ telemetry: { disabled: true } }) + await Telemetry.init() await Telemetry.flush() - expect(fetchSpy.mock.calls.some(([url]) => url === "https://ingest.example.invalid/v2/track")).toBe(true) await Telemetry.refreshIdentity() + expect(fetchSpy).not.toHaveBeenCalled() + + await Telemetry.shutdown() + rmSync(path.join(home, ".altimate", "altimate.json")) + configSpy.mockResolvedValue({}) + await Telemetry.init() + await Telemetry.flush() + expect(names).toEqual([]) + }) + + test("exit while unresolved never sends and clears held events", async () => { + const names = recordIngestion() + process.env.OPENCODE_CONFIG_CONTENT = "{" + trackStartup() + await Telemetry.init() + trackStartup() + await Telemetry.shutdown() + expect(fetchSpy).not.toHaveBeenCalled() + + rmSync(path.join(home, ".altimate", "altimate.json")) + configSpy.mockResolvedValue({}) + await Telemetry.init() + await Telemetry.flush() + expect(names).toEqual([]) + }) + + test("malformed auth prevents an otherwise loaded config from enabling telemetry", async () => { + writeFileSync(Auth.filepath(), "null") + configSpy.mockResolvedValue({}) + await expectSilentLifecycle() }) test("an unreadable config suppresses all requests", async () => { diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 6e3498aec2..73e32689f3 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -5,6 +5,7 @@ import { NamedError } from "@opencode-ai/core/util/error" import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/unstable/http" import { NodeFileSystem, NodePath } from "@effect/platform-node" import { Config } from "@/config/config" +import { Telemetry } from "@/altimate/telemetry" import { ConfigManaged } from "@/config/managed" import { ConfigParse } from "../../src/config/parse" import { EffectFlock } from "@opencode-ai/core/util/effect-flock" @@ -718,6 +719,82 @@ for (const failure of ["account", "organization"] as const) { ) } +test("telemetry sends held events after an organization config fetch recovers", async () => { + const directory = await tmpdir() + const savedSink = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING + const savedOptOut = process.env.ALTIMATE_TELEMETRY_DISABLED + process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = + "InstrumentationKey=test;IngestionEndpoint=https://ingest.example.invalid/" + delete process.env.ALTIMATE_TELEMETRY_DISABLED + let recovered = false + let orgLoads = 0 + const account = Layer.mock(Account.Service)({ + active: () => Effect.succeed(Option.some({ + id: AccountID.make("telemetry-account"), + email: "user@example.com", + url: "https://control.example.invalid", + active_org_id: OrgID.make("telemetry-org"), + })), + config: () => Effect.suspend(() => { + orgLoads++ + return recovered + ? Effect.succeed(Option.some({ telemetry: { disabled: false } })) + : Effect.fail(new AccountServiceError({ message: "Temporary organization config failure" })) + }), + token: () => Effect.succeed(Option.none()), + }) + const events: string[] = [] + await Telemetry.shutdown() + const fetchSpy = spyOn(globalThis, "fetch").mockImplementation(Object.assign(async (url: Parameters[0], request?: Parameters[1]) => { + if (url !== "https://ingest.example.invalid/v2/track") throw new Error("Unexpected telemetry request") + for (const envelope of JSON.parse(String(request?.body))) events.push(envelope.data.baseData.name) + return new Response(null, { status: 204 }) + }, { preconnect: fetch.preconnect })) + // Exercise the real per-instance config cache with only its account service replaced. + const context = { directory: directory.path, worktree: directory.path } as InstanceContext + const program = Config.Service.use((service) => Effect.promise(async () => { + const config = spyOn(Config, "get").mockImplementation((retry?: boolean) => + Effect.runPromise(provideCurrentInstance( + service.get(retry), + context, + )), + ) + try { + const track = () => Telemetry.track({ + type: "startup_ready", timestamp: Date.now(), session_id: "", + command: "run", surface: "run", duration_ms: 1, fresh_install: false, + }) + track() + await Telemetry.init() + track() + await Telemetry.refreshIdentity() + await Telemetry.flush() + const telemetryCalls = fetchSpy.mock.calls.filter(([url]) => /\/(v2\/track|users\/me)$/.test(String(url))) + expect(telemetryCalls).toEqual([]) + expect(orgLoads).toBe(1) + + recovered = true + await Telemetry.init() + await Telemetry.flush() + expect(events).toEqual(["startup_ready", "startup_ready"]) + expect(orgLoads).toBe(2) + } finally { + await Telemetry.shutdown() + config.mockRestore() + } + })) + try { + await Effect.runPromise(program.pipe(Effect.scoped, Effect.provide(configLayer({ account })))) + } finally { + fetchSpy.mockRestore() + if (savedSink === undefined) delete process.env.APPLICATIONINSIGHTS_CONNECTION_STRING + else process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = savedSink + if (savedOptOut === undefined) delete process.env.ALTIMATE_TELEMETRY_DISABLED + else process.env.ALTIMATE_TELEMETRY_DISABLED = savedOptOut + await directory[Symbol.asyncDispose]() + } +}) + it.instance("validates config schema and throws on invalid fields", () => Effect.gen(function* () { const test = yield* TestInstance diff --git a/packages/opencode/test/install/install-telemetry.test.ts b/packages/opencode/test/install/install-telemetry.test.ts index 4ef0dfe49b..f9a0c64515 100644 --- a/packages/opencode/test/install/install-telemetry.test.ts +++ b/packages/opencode/test/install/install-telemetry.test.ts @@ -27,6 +27,7 @@ import { join } from "node:path" import os from "os" import path from "path" import { Telemetry } from "@/altimate/telemetry" +import { Config } from "@/config/config" const REPO_ROOT = join(import.meta.dir, "..", "..", "..", "..") const INSTALL_SH = readFileSync(join(REPO_ROOT, "install"), "utf-8") @@ -303,6 +304,7 @@ describe("is_upgrade ordering", () => { const origOpencodeDisabled = process.env.OPENCODE_DISABLE_TELEMETRY const tmpHome = mkdtempSync(join(os.tmpdir(), "install-telemetry-home-")) spyOn(os, "homedir").mockImplementation(() => tmpHome) + spyOn(Config, "get").mockResolvedValue({}) spyOn(global, "fetch").mockImplementation((async () => new Response("", { status: 200 })) as any) try { diff --git a/packages/opencode/test/telemetry/telemetry-opt-out-flag.test.ts b/packages/opencode/test/telemetry/telemetry-opt-out-flag.test.ts index cdd9994f3d..0a5f67ab12 100644 --- a/packages/opencode/test/telemetry/telemetry-opt-out-flag.test.ts +++ b/packages/opencode/test/telemetry/telemetry-opt-out-flag.test.ts @@ -3,7 +3,7 @@ import { readFileSync } from "fs" import path from "path" import { TelemetryConfig } from "../../src/altimate/telemetry/config-state" -const keys = ["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY", "ALTIMATE_CLI_DISABLE_TELEMETRY"] +const keys = ["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY"] const saved = new Map() beforeEach(() => { From 827026bae6e1d085e1fd51ab59e28bb6b3f89b29 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:22:35 -0800 Subject: [PATCH 07/63] test: follow the shared telemetry config resolver --- .../test/upstream/altimate-features.test.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/opencode/test/upstream/altimate-features.test.ts b/packages/opencode/test/upstream/altimate-features.test.ts index a57a868f9d..c05ae4041c 100644 --- a/packages/opencode/test/upstream/altimate-features.test.ts +++ b/packages/opencode/test/upstream/altimate-features.test.ts @@ -398,13 +398,13 @@ describe("altimate features: SystemPrompt.skills sorting", () => { // 9. Telemetry stays fail-safe outside Instance context // =========================================================================== describe("altimate features: telemetry fail-safe init", () => { - test("telemetry/index.ts catches Config.get() failures so init never throws", async () => { - const src = await readSrc("altimate", "telemetry", "index.ts") - // The try/catch around Config.get() — must be present so init() can be - // called from CLI middleware before Instance.provide(). - expect(src).toMatch(/try\s*\{\s*const userConfig = \(await Config\.get\(\)\)/) - // The ALTIMATE_TELEMETRY_DISABLED env var escape hatch. - expect(src).toContain("ALTIMATE_TELEMETRY_DISABLED") + test("telemetry can resolve the opt-out before an Instance exists", async () => { + const init = await readSrc("altimate", "telemetry", "index.ts") + const config = await readSrc("altimate", "telemetry", "config-state.ts") + expect(init).toContain("await TelemetryConfig.resolve(configDirectory, retry)") + expect(config).toMatch(/try\s*\{\s*return await loadedState\(retry\)/) + expect(config).toContain('return instanceDirectory() ? "unreadable" : disabledState(directory)') + expect(config).toContain("ALTIMATE_TELEMETRY_DISABLED") }) test("telemetry/index.ts no longer reads the account; identity comes from the stored credential", async () => { From a5be80703c086b70cf09d6b339ca9e596268045f Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:30:42 -0800 Subject: [PATCH 08/63] fix: retry cached telemetry config load failures --- packages/opencode/src/config/config.ts | 15 ++++++++++----- .../test/altimate/telemetry/opt-out.test.ts | 7 +++++++ packages/opencode/test/config/config.test.ts | 18 ++++++++++++++++++ 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 53c66e34a8..ae126f3cb9 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -457,6 +457,8 @@ export const layer = Layer.effect( const legacy = path.join(Global.Path.config, "config") if (existsSync(legacy)) { + // altimate_change — a failed migration can still leave the parsed configuration usable. + let parsedLegacy = false yield* Effect.promise(() => import(pathToFileURL(legacy).href, { with: { type: "toml" } }) .then(async (mod) => { @@ -466,12 +468,14 @@ export const layer = Layer.effect( result["$schema"] = "https://altimate.ai/config.json" // altimate_change end result = mergeConfig(result, rest) + // altimate_change — only read and parse failures leave the config unresolved. + parsedLegacy = true await fsNode.writeFile(path.join(Global.Path.config, "config.json"), JSON.stringify(result, null, 2)) await fsNode.unlink(legacy) }) // altimate_change start — preserve the failure for the telemetry gate .catch(() => { - incompleteGlobals.add(result) + if (!parsedLegacy) incompleteGlobals.add(result) }), // altimate_change end ) @@ -964,12 +968,13 @@ export const layer = Layer.effect( // altimate_change start — reload partial config for the current instance on telemetry retry const get = Effect.fn("Config.get")(function* (retryTelemetry = false) { - const cached = retryTelemetry && (yield* InstanceState.has(state)) - const config = yield* InstanceState.use(state, (s) => s.config) - if (!cached || !telemetryConfigUnresolved(config)) return config + const read = InstanceState.use(state, (s) => s.config) + if (!retryTelemetry || !(yield* InstanceState.has(state))) return yield* read + const cached = yield* Effect.exit(read) + if (Exit.isSuccess(cached) && !telemetryConfigUnresolved(cached.value)) return cached.value yield* invalidateGlobal yield* InstanceState.invalidate(state) - return yield* InstanceState.use(state, (s) => s.config) + return yield* read }) // altimate_change end diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index d37f1eaa4b..f4462c93b2 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -11,6 +11,10 @@ import { TelemetryConfig } from "../../../src/altimate/telemetry/config-state" const CS = "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://ingest.example.invalid/" const ENV = [ + "NODE_ENV", + "BUN_TEST", + "VITEST", + "JEST_WORKER_ID", "OPENCODE_TEST_HOME", "APPLICATIONINSIGHTS_CONNECTION_STRING", "ALTIMATE_TELEMETRY_DISABLED", @@ -49,6 +53,8 @@ describe("telemetry opt-out", () => { saved[key] = process.env[key] delete process.env[key] } + // Exercise the production opt-out behavior with both transports intercepted. + process.env.NODE_ENV = "production" process.env.OPENCODE_TEST_HOME = home process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = CS Telemetry.setConfigDirectory(home) @@ -138,6 +144,7 @@ describe("telemetry opt-out", () => { test("opt-out takes precedence over the test force flag and explicit sink", async () => { process.env.ALTIMATE_TELEMETRY_DISABLED = "TRUE" + process.env.NODE_ENV = "test" process.env.ALTIMATE_TELEMETRY_FORCE = "true" await expectSilentLifecycle() }) diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 73e32689f3..1b95b54b2b 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -723,9 +723,11 @@ test("telemetry sends held events after an organization config fetch recovers", const directory = await tmpdir() const savedSink = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING const savedOptOut = process.env.ALTIMATE_TELEMETRY_DISABLED + const savedLegacyOptOut = process.env.OPENCODE_DISABLE_TELEMETRY process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "InstrumentationKey=test;IngestionEndpoint=https://ingest.example.invalid/" delete process.env.ALTIMATE_TELEMETRY_DISABLED + delete process.env.OPENCODE_DISABLE_TELEMETRY let recovered = false let orgLoads = 0 const account = Layer.mock(Account.Service)({ @@ -791,10 +793,26 @@ test("telemetry sends held events after an organization config fetch recovers", else process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = savedSink if (savedOptOut === undefined) delete process.env.ALTIMATE_TELEMETRY_DISABLED else process.env.ALTIMATE_TELEMETRY_DISABLED = savedOptOut + if (savedLegacyOptOut === undefined) delete process.env.OPENCODE_DISABLE_TELEMETRY + else process.env.OPENCODE_DISABLE_TELEMETRY = savedLegacyOptOut await directory[Symbol.asyncDispose]() } }) +it.instance("a telemetry retry reloads a repaired config after a cached load failure", () => + Effect.gen(function* () { + const { directory } = yield* TestInstance + const configPath = path.join(directory, "opencode.json") + yield* FSUtil.use.writeWithDirs(configPath, "{") + const failed = yield* Config.use.get().pipe(Effect.exit) + expect(Exit.isFailure(failed)).toBe(true) + + yield* FSUtil.use.writeWithDirs(configPath, JSON.stringify({ telemetry: { disabled: true } })) + const recovered = yield* Config.use.get(true) + expect(recovered.telemetry?.disabled).toBe(true) + }), +) + it.instance("validates config schema and throws on invalid fields", () => Effect.gen(function* () { const test = yield* TestInstance From 6c9a01f6333bfc4b6b4f03a66928f90f9b84343a Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:35:25 -0800 Subject: [PATCH 09/63] fix: preserve released telemetry opt-out compatibility --- docs/docs/reference/security-faq.md | 2 +- docs/docs/reference/telemetry.md | 4 +- .../opencode/src/altimate/debug/collect.ts | 5 +- .../src/altimate/telemetry/config-state.ts | 35 ++++------ packages/opencode/src/auth/index.ts | 65 +++++++++---------- packages/opencode/src/config/config.ts | 23 +++++-- .../test/altimate/telemetry/opt-out.test.ts | 25 ++++++- packages/opencode/test/config/config.test.ts | 22 +++++++ .../telemetry/telemetry-opt-out-flag.test.ts | 2 +- 9 files changed, 116 insertions(+), 67 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index cf4c701ccf..052c528591 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -183,7 +183,7 @@ No code, queries, file paths, or personal information is included. This event he The install scripts (`altimate.sh/install`, `install.ps1`), the npm postinstall, and the VS Code extension's installer send nothing themselves and contact no telemetry endpoint. They only record the version and installer name to a local file that the CLI reads on its next run, so the opt-out above decides whether anything is ever transmitted. -The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED` or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. +The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. ## What happens when I authenticate via a well-known URL? diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index 5d41eca2d0..6f429ce45f 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -182,7 +182,7 @@ You can also set the environment variable: export ALTIMATE_TELEMETRY_DISABLED=true ``` -`OPENCODE_DISABLE_TELEMETRY` is also supported. Each variable accepts `1` or `true` (case-insensitive). +`ALTIMATE_CLI_DISABLE_TELEMETRY` and its older spelling `OPENCODE_DISABLE_TELEMETRY` are also supported. Each variable accepts `1` or `true` (case-insensitive). When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. If startup cannot determine the config setting, it suppresses telemetry. This includes startup before a configured remote source that could set the flag has been loaded. @@ -231,7 +231,7 @@ These identifiers are sent only while telemetry is enabled. While the opt-out se ### CLI Authentication Flow -When you sign in using the CLI browser auth flow (`altimate auth login`), the anonymous machine ID (a random UUID persisted at `~/.altimate/machine-id` — a device/installation identifier, reused across sessions) is included in the authorization URL and associated with your account in product analytics. This is used solely to correlate CLI install events with authenticated accounts in aggregate funnel analytics — it is not used for advertising or cross-site tracking. Your telemetry opt-out suppresses this: when you disable telemetry — via `ALTIMATE_TELEMETRY_DISABLED=true`, `OPENCODE_DISABLE_TELEMETRY=true`, or the `telemetry.disabled` config option — the machine ID is omitted from the authorization URL entirely. The machine ID is associated with your account in PostHog for this funnel analysis, separate from the Azure Application Insights pipeline used for other CLI telemetry events. +When you sign in using the CLI browser auth flow (`altimate auth login`), the anonymous machine ID (a random UUID persisted at `~/.altimate/machine-id` — a device/installation identifier, reused across sessions) is included in the authorization URL and associated with your account in product analytics. This is used solely to correlate CLI install events with authenticated accounts in aggregate funnel analytics — it is not used for advertising or cross-site tracking. Your telemetry opt-out suppresses this: when you disable telemetry — via any of the environment flags above or the `telemetry.disabled` config option — the machine ID is omitted from the authorization URL entirely. The machine ID is associated with your account in PostHog for this funnel analysis, separate from the Azure Application Insights pipeline used for other CLI telemetry events. ### Data Retention diff --git a/packages/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index 2d35a56241..95ed707797 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -6,6 +6,7 @@ * names or hosts before they leave this file. */ import fs from "fs" +import { TelemetryConfig } from "@/altimate/telemetry/config-state" import os from "os" import path from "path" import dns from "dns/promises" @@ -92,8 +93,8 @@ function envFlags(): string[] { /** With `network`, telemetry has been started by the CLI; its start is awaited here so the answer is not read * before it settles. Without, it is not started (it would send), so only the environment switches are checked. */ async function telemetryFacts(network: boolean): Promise { - if (/^(1|true)$/i.test(process.env["ALTIMATE_TELEMETRY_DISABLED"] ?? "")) return { enabled: false, reason: "ALTIMATE_TELEMETRY_DISABLED is set" } - if (/^(1|true)$/i.test(process.env["OPENCODE_DISABLE_TELEMETRY"] ?? "")) return { enabled: false, reason: "OPENCODE_DISABLE_TELEMETRY is set" } + const optOut = TelemetryConfig.disablingEnvironmentVariable() + if (optOut) return { enabled: false, reason: `${optOut} is set` } if (!network) return { enabled: false, checked: false, reason: "not started with --no-network" } try { await Telemetry.init() diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index ac435dfc48..33f956e10c 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -50,33 +50,24 @@ function worktreeOf(directory: string): string | undefined { } export function disablingEnvironmentVariable(): string | undefined { - return ["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY"].find((key) => + return ["ALTIMATE_TELEMETRY_DISABLED", "ALTIMATE_CLI_DISABLE_TELEMETRY", "OPENCODE_DISABLE_TELEMETRY"].find((key) => /^(true|1)$/i.test(process.env[key] ?? ""), ) } -async function authEntries(): Promise> { +async function hasWellKnownAuth(): Promise { let contents = process.env.OPENCODE_AUTH_CONTENT if (!contents) { try { contents = await fs.readFile(Auth.filepath(), "utf8") } catch (error) { - if ((error as NodeJS.ErrnoException)?.code === "ENOENT") return {} + if ((error as NodeJS.ErrnoException)?.code === "ENOENT") return false throw error } } - const entries: unknown = JSON.parse(contents) - if (!entries || typeof entries !== "object" || Array.isArray(entries)) { - throw new Error("Invalid auth store") - } - const values = Object.values(entries) - for (const entry of values) { - if (!entry || typeof entry !== "object" || !("type" in entry) || entry.type !== "wellknown") continue - if (!("key" in entry && typeof entry.key === "string" && "token" in entry && typeof entry.token === "string")) { - throw new Error("Invalid well-known auth entry") - } - } - return entries as Record + const parsed = Auth.parseStore(contents) + if (!parsed || parsed.incomplete) throw new Error("Unresolved auth store") + return parsed.hasWellKnown } export function instanceDirectory(): string | undefined { @@ -88,7 +79,7 @@ export async function loadedState(retry = false): Promise { if (Config.telemetryConfigUnresolved(config)) return "unreadable" // Auth.all() can return an empty store when its read or parse fails. try { - await authEntries() + await hasWellKnownAuth() } catch { return "unreadable" } @@ -106,10 +97,8 @@ export async function resolve(directory?: string, retry = false): Promise } async function remoteMayDisable(local: boolean | undefined): Promise { - const auth = await authEntries() - if (local === undefined && Object.values(auth).some((entry) => - entry && typeof entry === "object" && "type" in entry && entry.type === "wellknown" - )) return true + const wellKnown = await hasWellKnownAuth() + if (local === undefined && wellKnown) return true const dbPath = Database.path() if (dbPath === ":memory:") return true @@ -138,9 +127,13 @@ async function remoteMayDisable(local: boolean | undefined): Promise { "SELECT count(*) AS count FROM sqlite_schema WHERE name IN ('account', 'account_state') AND type = 'table'", ).get() if (tables?.count !== 2) return false // A pre-migration database cannot select an organization. + const modern = db.query("SELECT 1 FROM pragma_table_info('account_state') WHERE name = 'active_org_id'").get() + // The earlier schema stored the selected org on the account row. The migration + // copies that value into account_state, so it can still enable remote config. + const orgColumn = modern ? "account_state.active_org_id" : "account.selected_org_id" return db.query(`SELECT 1 FROM account_state JOIN account ON account.id = account_state.active_account_id - WHERE account_state.id = 1 AND account_state.active_org_id IS NOT NULL`).get() !== null + WHERE account_state.id = 1 AND ${orgColumn} IS NOT NULL`).get() !== null } finally { db.close() } diff --git a/packages/opencode/src/auth/index.ts b/packages/opencode/src/auth/index.ts index 9aabd2e593..ef7a2a8946 100644 --- a/packages/opencode/src/auth/index.ts +++ b/packages/opencode/src/auth/index.ts @@ -73,6 +73,23 @@ const incompleteStores = new WeakSet>() export function configSourcesUnresolved(store: Record): boolean { return incompleteStores.has(store) } + +// Both the normal loader and the local telemetry probe need the same validation. +const decodeWellKnown = Schema.decodeUnknownOption(WellKnown) +export function parseStore(text: string) { + try { + const parsed: unknown = JSON.parse(text) + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return + const entries = parsed as Record + const wellKnown = Object.values(entries).filter( + (entry) => entry && typeof entry === "object" && "type" in entry && entry.type === "wellknown", + ) + const incomplete = wellKnown.some((entry) => decodeWellKnown(entry)._tag === "None") + return { entries, hasWellKnown: wellKnown.length > 0, incomplete } + } catch { + return + } +} // altimate_change end export const layer = Layer.effect( @@ -83,42 +100,22 @@ export const layer = Layer.effect( const all = Effect.fn("Auth.all")(function* () { // altimate_change start — preserve unreadable stores and invalid well-known entries for Config. - let incomplete = false - let data: Record | undefined - const parseStore = (text: string) => { - try { - const parsed: unknown = JSON.parse(text) - if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed as Record - } catch {} - incomplete = true - return undefined + const inline = process.env.OPENCODE_AUTH_CONTENT + const provided = inline ? parseStore(inline) : undefined + if (provided) { + const store = provided.entries as Record + if (provided.incomplete) incompleteStores.add(store) + return store } - if (process.env.OPENCODE_AUTH_CONTENT) { - data = parseStore(process.env.OPENCODE_AUTH_CONTENT) - if (data) { - const inline = data as Record - if (Object.values(inline).some((value) => value?.type === "wellknown" && decode(value)._tag === "None")) { - incompleteStores.add(inline) - } - return inline - } - } - if (!data) { - const text = yield* fsys.readFileStringSafe(file).pipe(Effect.catch(() => { - incomplete = true - return Effect.succeed(undefined) - })) - data = text === undefined ? {} : parseStore(text) ?? {} - } - const store = Record.filterMap(data, (value) => { - const auth = decode(value) - if (auth._tag === "None" && value && typeof value === "object" && "type" in value && value.type === "wellknown") { - incomplete = true - } - return Result.fromOption(auth, () => undefined) - }) - if (incomplete) incompleteStores.add(store) + let incomplete = Boolean(inline) + const text = yield* fsys.readFileStringSafe(file).pipe(Effect.catch(() => { + incomplete = true + return Effect.succeed(undefined) + })) + const disk = text === undefined ? undefined : parseStore(text) + const store = Record.filterMap(disk?.entries ?? {}, (value) => Result.fromOption(decode(value), () => undefined)) + if (incomplete || (text !== undefined && (!disk || disk.incomplete))) incompleteStores.add(store) return store // altimate_change end }) diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index ae126f3cb9..fa725e073f 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -54,6 +54,7 @@ import { InstanceRef } from "@/effect/instance-ref" // altimate_change start — defer telemetry when any config layer was unavailable const configsWithUnresolvedTelemetry = new WeakSet() +const configsWithUnresolvedGlobal = new WeakSet() export function telemetryConfigUnresolved(config: Info): boolean { return configsWithUnresolvedTelemetry.has(config) @@ -930,7 +931,9 @@ export const layer = Layer.effect( // altimate_change end // altimate_change start — associate the status with this resolved config object - if (orgConfigUnresolved || incompleteGlobals.has(global) || Auth.configSourcesUnresolved(auth)) { + const globalUnresolved = incompleteGlobals.has(global) + if (globalUnresolved) configsWithUnresolvedGlobal.add(result) + if (orgConfigUnresolved || globalUnresolved || Auth.configSourcesUnresolved(auth)) { configsWithUnresolvedTelemetry.add(result) } // altimate_change end @@ -966,13 +969,25 @@ export const layer = Layer.effect( }), ) - // altimate_change start — reload partial config for the current instance on telemetry retry + // altimate_change start — retry only this instance and rate-limit repeated reloads during an outage. + const telemetryRetryAt = new WeakMap() + const TELEMETRY_RETRY_MS = 30_000 const get = Effect.fn("Config.get")(function* (retryTelemetry = false) { const read = InstanceState.use(state, (s) => s.config) if (!retryTelemetry || !(yield* InstanceState.has(state))) return yield* read const cached = yield* Effect.exit(read) - if (Exit.isSuccess(cached) && !telemetryConfigUnresolved(cached.value)) return cached.value - yield* invalidateGlobal + const ctx = yield* InstanceState.context + if (Exit.isSuccess(cached) && !telemetryConfigUnresolved(cached.value)) { + telemetryRetryAt.delete(ctx) + return cached.value + } + const now = Date.now() + if (now < (telemetryRetryAt.get(ctx) ?? 0)) { + if (Exit.isFailure(cached)) return yield* Effect.failCause(cached.cause) + return cached.value + } + telemetryRetryAt.set(ctx, now + TELEMETRY_RETRY_MS) + if (Exit.isSuccess(cached) && configsWithUnresolvedGlobal.has(cached.value)) yield* invalidateGlobal yield* InstanceState.invalidate(state) return yield* read }) diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index f4462c93b2..9f66500899 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -19,6 +19,7 @@ const ENV = [ "APPLICATIONINSIGHTS_CONNECTION_STRING", "ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY", + "ALTIMATE_CLI_DISABLE_TELEMETRY", "ALTIMATE_TELEMETRY_FORCE", "OPENCODE_CONFIG_CONTENT", "ALTIMATE_CLI_CONFIG_CONTENT", @@ -129,7 +130,7 @@ describe("telemetry opt-out", () => { expect(enabled).toBe(false) } - test.each(["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY"])("%s suppresses all requests", async (key) => { + test.each(["ALTIMATE_TELEMETRY_DISABLED", "ALTIMATE_CLI_DISABLE_TELEMETRY", "OPENCODE_DISABLE_TELEMETRY"])("%s suppresses all requests", async (key) => { process.env[key] = "1" await expectSilentLifecycle() // A later launch must also stay silent with the same existing machine ID. @@ -137,7 +138,7 @@ describe("telemetry opt-out", () => { }) test("a false canonical alias cannot override the legacy opt-out", async () => { - process.env.ALTIMATE_TELEMETRY_DISABLED = "false" + process.env.ALTIMATE_CLI_DISABLE_TELEMETRY = "false" process.env.OPENCODE_DISABLE_TELEMETRY = "1" await expectSilentLifecycle() }) @@ -197,6 +198,26 @@ describe("telemetry opt-out", () => { await expectSilentLifecycle() }) + test("a legacy account schema still defers to its selected organization's config", async () => { + const dbPath = path.join(home, "account.db") + const db = new SQLite(dbPath) + try { + db.exec(` + PRAGMA journal_mode = WAL; + CREATE TABLE account (id TEXT PRIMARY KEY, selected_org_id TEXT); + CREATE TABLE account_state (id INTEGER PRIMARY KEY, active_account_id TEXT); + INSERT INTO account VALUES ('account', NULL); + INSERT INTO account_state VALUES (1, 'account'); + `) + databaseSpy.mockReturnValue(dbPath) + expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + db.exec("UPDATE account SET selected_org_id = 'org'") + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") + } finally { + db.close() + } + }) + test("the startup probe can read while an account writer holds a WAL transaction", async () => { const dbPath = path.join(home, "account.db") const writer = new SQLite(dbPath) diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 1b95b54b2b..2cdec79e30 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -724,10 +724,12 @@ test("telemetry sends held events after an organization config fetch recovers", const savedSink = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING const savedOptOut = process.env.ALTIMATE_TELEMETRY_DISABLED const savedLegacyOptOut = process.env.OPENCODE_DISABLE_TELEMETRY + const savedCliOptOut = process.env.ALTIMATE_CLI_DISABLE_TELEMETRY process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "InstrumentationKey=test;IngestionEndpoint=https://ingest.example.invalid/" delete process.env.ALTIMATE_TELEMETRY_DISABLED delete process.env.OPENCODE_DISABLE_TELEMETRY + delete process.env.ALTIMATE_CLI_DISABLE_TELEMETRY let recovered = false let orgLoads = 0 const account = Layer.mock(Account.Service)({ @@ -795,10 +797,30 @@ test("telemetry sends held events after an organization config fetch recovers", else process.env.ALTIMATE_TELEMETRY_DISABLED = savedOptOut if (savedLegacyOptOut === undefined) delete process.env.OPENCODE_DISABLE_TELEMETRY else process.env.OPENCODE_DISABLE_TELEMETRY = savedLegacyOptOut + if (savedCliOptOut === undefined) delete process.env.ALTIMATE_CLI_DISABLE_TELEMETRY + else process.env.ALTIMATE_CLI_DISABLE_TELEMETRY = savedCliOptOut await directory[Symbol.asyncDispose]() } }) +{ + let loads = 0 + const account = Layer.mock(Account.Service)({ + active: () => Effect.suspend(() => { + loads++ + return Effect.fail(new AccountServiceError({ message: "Organization unavailable" })) + }), + }) + configIt({ account }).instance("repeated telemetry retries back off while account config remains unavailable", () => + Effect.gen(function* () { + expect(Config.telemetryConfigUnresolved(yield* Config.use.get())).toBe(true) + expect(Config.telemetryConfigUnresolved(yield* Config.use.get(true))).toBe(true) + expect(Config.telemetryConfigUnresolved(yield* Config.use.get(true))).toBe(true) + expect(loads).toBe(2) + }), + ) +} + it.instance("a telemetry retry reloads a repaired config after a cached load failure", () => Effect.gen(function* () { const { directory } = yield* TestInstance diff --git a/packages/opencode/test/telemetry/telemetry-opt-out-flag.test.ts b/packages/opencode/test/telemetry/telemetry-opt-out-flag.test.ts index 0a5f67ab12..58e4036b56 100644 --- a/packages/opencode/test/telemetry/telemetry-opt-out-flag.test.ts +++ b/packages/opencode/test/telemetry/telemetry-opt-out-flag.test.ts @@ -3,7 +3,7 @@ import { readFileSync } from "fs" import path from "path" import { TelemetryConfig } from "../../src/altimate/telemetry/config-state" -const keys = ["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY"] +const keys = ["ALTIMATE_TELEMETRY_DISABLED", "ALTIMATE_CLI_DISABLE_TELEMETRY", "OPENCODE_DISABLE_TELEMETRY"] const saved = new Map() beforeEach(() => { From 547a06380c605a39281c0301b3cd29e70ffaf0b9 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:42:11 -0800 Subject: [PATCH 10/63] fix: scope telemetry backoff to stale remote results --- docs/docs/reference/telemetry.md | 2 +- packages/opencode/src/config/config.ts | 43 ++++++++++++-------- packages/opencode/test/config/config.test.ts | 9 ++++ 3 files changed, 37 insertions(+), 17 deletions(-) diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index 6f429ce45f..6e75de17d5 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -231,7 +231,7 @@ These identifiers are sent only while telemetry is enabled. While the opt-out se ### CLI Authentication Flow -When you sign in using the CLI browser auth flow (`altimate auth login`), the anonymous machine ID (a random UUID persisted at `~/.altimate/machine-id` — a device/installation identifier, reused across sessions) is included in the authorization URL and associated with your account in product analytics. This is used solely to correlate CLI install events with authenticated accounts in aggregate funnel analytics — it is not used for advertising or cross-site tracking. Your telemetry opt-out suppresses this: when you disable telemetry — via any of the environment flags above or the `telemetry.disabled` config option — the machine ID is omitted from the authorization URL entirely. The machine ID is associated with your account in PostHog for this funnel analysis, separate from the Azure Application Insights pipeline used for other CLI telemetry events. +When you sign in using the CLI browser auth flow (`altimate auth login`), the anonymous machine ID (a random UUID persisted at `~/.altimate/machine-id` — a device/installation identifier, reused across sessions) is included in the authorization URL and associated with your account in product analytics. This is used solely to correlate CLI install events with authenticated accounts in aggregate funnel analytics — it is not used for advertising or cross-site tracking. Your telemetry opt-out suppresses this: when you disable telemetry — via any of the environment flags above or the `telemetry.disabled` config option — the machine ID is omitted from the authorization URL entirely. The URL also omits it while telemetry permission is unresolved. The machine ID is associated with your account in PostHog for this funnel analysis, separate from the Azure Application Insights pipeline used for other CLI telemetry events. ### Data Retention diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index fa725e073f..020012e563 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -22,7 +22,7 @@ import { isRecord } from "@/util/record" import type { ConsoleState } from "@opencode-ai/core/v1/config/console-state" import { FSUtil } from "@opencode-ai/core/fs-util" import { InstanceState } from "@/effect/instance-state" -import { Context, Duration, Effect, Exit, Fiber, Layer, Option, Schema } from "effect" +import { Cause, Context, Duration, Effect, Exit, Fiber, Layer, Option, Schema } from "effect" // altimate_change — classify retryable remote failures // altimate_change start — upstream_fix: invalidate Config's per-instance cache after writes import { ScopedCache } from "effect" // altimate_change end @@ -55,6 +55,7 @@ import { InstanceRef } from "@/effect/instance-ref" // altimate_change start — defer telemetry when any config layer was unavailable const configsWithUnresolvedTelemetry = new WeakSet() const configsWithUnresolvedGlobal = new WeakSet() +const configsWithUnresolvedOrg = new WeakSet() export function telemetryConfigUnresolved(config: Info): boolean { return configsWithUnresolvedTelemetry.has(config) @@ -933,6 +934,7 @@ export const layer = Layer.effect( // altimate_change start — associate the status with this resolved config object const globalUnresolved = incompleteGlobals.has(global) if (globalUnresolved) configsWithUnresolvedGlobal.add(result) + if (orgConfigUnresolved) configsWithUnresolvedOrg.add(result) if (orgConfigUnresolved || globalUnresolved || Auth.configSourcesUnresolved(auth)) { configsWithUnresolvedTelemetry.add(result) } @@ -969,27 +971,36 @@ export const layer = Layer.effect( }), ) - // altimate_change start — retry only this instance and rate-limit repeated reloads during an outage. - const telemetryRetryAt = new WeakMap() + // altimate_change start — back off only for the same unresolved remote-config result. + // A refreshed cache or a repaired local config can recover on the next call. + const telemetryRetryAt = new WeakMap() const TELEMETRY_RETRY_MS = 30_000 + function remoteRetryKey(result: Exit.Exit): object | undefined { + if (Exit.isSuccess(result)) { + return configsWithUnresolvedOrg.has(result.value) ? result.value : undefined + } + const failure = Cause.squash(result.cause) + if (failure instanceof RemoteUnavailableError || failure instanceof RemoteAuthError) return failure + } + const get = Effect.fn("Config.get")(function* (retryTelemetry = false) { const read = InstanceState.use(state, (s) => s.config) if (!retryTelemetry || !(yield* InstanceState.has(state))) return yield* read const cached = yield* Effect.exit(read) - const ctx = yield* InstanceState.context - if (Exit.isSuccess(cached) && !telemetryConfigUnresolved(cached.value)) { - telemetryRetryAt.delete(ctx) - return cached.value - } - const now = Date.now() - if (now < (telemetryRetryAt.get(ctx) ?? 0)) { - if (Exit.isFailure(cached)) return yield* Effect.failCause(cached.cause) - return cached.value - } - telemetryRetryAt.set(ctx, now + TELEMETRY_RETRY_MS) - if (Exit.isSuccess(cached) && configsWithUnresolvedGlobal.has(cached.value)) yield* invalidateGlobal + if (Exit.isSuccess(cached) && !telemetryConfigUnresolved(cached.value)) return cached.value + + const remote = remoteRetryKey(cached) + if (remote && performance.now() < (telemetryRetryAt.get(remote) ?? 0)) return yield* cached + + // A failed local read can have come from the global cache. A known remote + // failure cannot, so keep a readable global cache in that case. + const reloadGlobal = Exit.isFailure(cached) ? !remote : configsWithUnresolvedGlobal.has(cached.value) + if (reloadGlobal) yield* invalidateGlobal yield* InstanceState.invalidate(state) - return yield* read + const retried = yield* Effect.exit(read) + const retryKey = remoteRetryKey(retried) + if (retryKey) telemetryRetryAt.set(retryKey, performance.now() + TELEMETRY_RETRY_MS) + return yield* retried }) // altimate_change end diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 2cdec79e30..2368bec49b 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -805,9 +805,11 @@ test("telemetry sends held events after an organization config fetch recovers", { let loads = 0 + let available = false const account = Layer.mock(Account.Service)({ active: () => Effect.suspend(() => { loads++ + if (available) return Effect.succeed(Option.none()) return Effect.fail(new AccountServiceError({ message: "Organization unavailable" })) }), }) @@ -817,6 +819,11 @@ test("telemetry sends held events after an organization config fetch recovers", expect(Config.telemetryConfigUnresolved(yield* Config.use.get(true))).toBe(true) expect(Config.telemetryConfigUnresolved(yield* Config.use.get(true))).toBe(true) expect(loads).toBe(2) + + available = true + yield* Config.use.invalidate() + expect(Config.telemetryConfigUnresolved(yield* Config.use.get(true))).toBe(false) + expect(loads).toBe(3) }), ) } @@ -828,6 +835,8 @@ it.instance("a telemetry retry reloads a repaired config after a cached load fai yield* FSUtil.use.writeWithDirs(configPath, "{") const failed = yield* Config.use.get().pipe(Effect.exit) expect(Exit.isFailure(failed)).toBe(true) + const failedRetry = yield* Config.use.get(true).pipe(Effect.exit) + expect(Exit.isFailure(failedRetry)).toBe(true) yield* FSUtil.use.writeWithDirs(configPath, JSON.stringify({ telemetry: { disabled: true } })) const recovered = yield* Config.use.get(true) From 515f5ff7c86cbc9a5677a9f10ccf36f8f0284628 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:46:39 -0800 Subject: [PATCH 11/63] fix: back off malformed remote telemetry config retries --- packages/opencode/src/config/config.ts | 16 +++++++++++--- packages/opencode/test/config/config.test.ts | 23 ++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 020012e563..3d712ddfb0 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -337,6 +337,8 @@ export const layer = Layer.effect( const env = yield* Env.Service const npmSvc = yield* Npm.Service const http = yield* HttpClient.HttpClient + // altimate_change — preserve the source of any remote load failure without changing its public error. + const remoteLoadFailures = new WeakSet() const readConfigFile = (filepath: string) => fs.readFileStringSafe(filepath).pipe(Effect.orDie) @@ -586,7 +588,10 @@ export const layer = Layer.effect( } for (const [key, value] of Object.entries(auth)) { - if (value.type === "wellknown") { + // altimate_change start — classify fetch, decode, and schema failures as remote for retry backoff. + if (value.type !== "wellknown") continue + yield* Effect.gen(function* () { + // altimate_change end const url = key.replace(/\/+$/, "") authEnv[value.key] = value.token const wellknownURL = `${url}/.well-known/opencode` @@ -631,7 +636,12 @@ export const layer = Layer.effect( ) yield* merge(source, next, "global") yield* Effect.logDebug("loaded remote config from well-known", { url }) - } + // altimate_change start — retain the original error for other config consumers. + }).pipe(Effect.tapCause((cause) => Effect.sync(() => { + const failure = Cause.squash(cause) + if (failure && typeof failure === "object") remoteLoadFailures.add(failure) + }))) + // altimate_change end } const global = Object.keys(authEnv).length ? yield* loadGlobal(authEnv) : yield* getGlobal() @@ -980,7 +990,7 @@ export const layer = Layer.effect( return configsWithUnresolvedOrg.has(result.value) ? result.value : undefined } const failure = Cause.squash(result.cause) - if (failure instanceof RemoteUnavailableError || failure instanceof RemoteAuthError) return failure + if (failure && typeof failure === "object" && remoteLoadFailures.has(failure)) return failure } const get = Effect.fn("Config.get")(function* (retryTelemetry = false) { diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 2368bec49b..e1180b0b82 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -828,6 +828,29 @@ test("telemetry sends held events after an organization config fetch recovers", ) } +for (const [format, body] of [ + ["JSON", "{"], + ["schema", JSON.stringify({ config: { telemetry: { disabled: "invalid" } } })], +]) { + let requests = 0 + const client = HttpClient.make((request) => { + requests++ + return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body, { + headers: { "content-type": "application/json" }, + }))) + }) + configIt({ auth: wellKnownAuth("https://config.example.invalid"), client }).instance( + `invalid well-known config ${format} backs off on repeated telemetry retries`, + () => + Effect.gen(function* () { + expect(Exit.isFailure(yield* Config.use.get().pipe(Effect.exit))).toBe(true) + expect(Exit.isFailure(yield* Config.use.get(true).pipe(Effect.exit))).toBe(true) + expect(Exit.isFailure(yield* Config.use.get(true).pipe(Effect.exit))).toBe(true) + expect(requests).toBe(2) + }), + ) +} + it.instance("a telemetry retry reloads a repaired config after a cached load failure", () => Effect.gen(function* () { const { directory } = yield* TestInstance From 0f296c58b44e1882795eb37922cb1838d1697c65 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 22:50:59 -0800 Subject: [PATCH 12/63] fix: classify invalid organization telemetry config --- packages/opencode/src/config/config.ts | 13 ++++++---- packages/opencode/test/config/config.test.ts | 25 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 3d712ddfb0..e71432c401 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -337,8 +337,13 @@ export const layer = Layer.effect( const env = yield* Env.Service const npmSvc = yield* Npm.Service const http = yield* HttpClient.HttpClient - // altimate_change — preserve the source of any remote load failure without changing its public error. + // altimate_change start — preserve remote failure origin without changing the public error. const remoteLoadFailures = new WeakSet() + const recordRemoteFailure = (cause: Cause.Cause) => Effect.sync(() => { + const failure = Cause.squash(cause) + if (failure && typeof failure === "object") remoteLoadFailures.add(failure) + }) + // altimate_change end const readConfigFile = (filepath: string) => fs.readFileStringSafe(filepath).pipe(Effect.orDie) @@ -637,10 +642,7 @@ export const layer = Layer.effect( yield* merge(source, next, "global") yield* Effect.logDebug("loaded remote config from well-known", { url }) // altimate_change start — retain the original error for other config consumers. - }).pipe(Effect.tapCause((cause) => Effect.sync(() => { - const failure = Cause.squash(cause) - if (failure && typeof failure === "object") remoteLoadFailures.add(failure) - }))) + }).pipe(Effect.tapCause(recordRemoteFailure)) // altimate_change end } @@ -768,6 +770,7 @@ export const layer = Layer.effect( error: err instanceof Error ? err.message : String(err), }) }), + Effect.tapCause(recordRemoteFailure), // altimate_change end ) } diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index e1180b0b82..c8861fcadb 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -851,6 +851,31 @@ for (const [format, body] of [ ) } +{ + let requests = 0 + const account = Layer.mock(Account.Service)({ + active: () => Effect.succeed(Option.some({ + id: AccountID.make("invalid-config-account"), + email: "user@example.com", + url: "https://control.example.invalid", + active_org_id: OrgID.make("org"), + })), + config: () => Effect.sync(() => { + requests++ + return Option.some({ telemetry: { disabled: "invalid" } }) + }), + token: () => Effect.succeed(Option.none()), + }) + configIt({ account }).instance("invalid organization config schema backs off on repeated telemetry retries", () => + Effect.gen(function* () { + expect(Exit.isFailure(yield* Config.use.get().pipe(Effect.exit))).toBe(true) + expect(Exit.isFailure(yield* Config.use.get(true).pipe(Effect.exit))).toBe(true) + expect(Exit.isFailure(yield* Config.use.get(true).pipe(Effect.exit))).toBe(true) + expect(requests).toBe(2) + }), + ) +} + it.instance("a telemetry retry reloads a repaired config after a cached load failure", () => Effect.gen(function* () { const { directory } = yield* TestInstance From 74a5310d489eb3ff066906135268deb62a6a7cef Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:00:49 -0800 Subject: [PATCH 13/63] fix: recheck unresolved local telemetry sources before refetching --- packages/opencode/src/config/config.ts | 54 ++++++++++++++------ packages/opencode/test/config/config.test.ts | 39 ++++++++++++++ 2 files changed, 77 insertions(+), 16 deletions(-) diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index e71432c401..d6119ea5a8 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -2,7 +2,6 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { httpClient } from "@opencode-ai/core/effect/layer-node-platform" import { serviceUse } from "@opencode-ai/core/effect/service-use" import path from "path" -import { pathToFileURL } from "url" import os from "os" import { mergeDeep } from "remeda" // altimate_change - use fork-branded global paths so config loads from ~/.config/altimate-code @@ -53,9 +52,8 @@ import { InstanceRef } from "@/effect/instance-ref" // altimate_change end // altimate_change start — defer telemetry when any config layer was unavailable -const configsWithUnresolvedTelemetry = new WeakSet() -const configsWithUnresolvedGlobal = new WeakSet() -const configsWithUnresolvedOrg = new WeakSet() +type UnresolvedTelemetrySources = { auth: boolean; global: boolean; organization: boolean } +const configsWithUnresolvedTelemetry = new WeakMap() export function telemetryConfigUnresolved(config: Info): boolean { return configsWithUnresolvedTelemetry.has(config) @@ -442,7 +440,8 @@ export const layer = Layer.effect( // altimate_change — the legacy loader can return partial config after an unreadable TOML file. const incompleteGlobals = new WeakSet() - const loadGlobal = Effect.fnUntraced(function* (env?: Record) { + // altimate_change — telemetry can recheck local files without migrating legacy config. + const loadGlobal = Effect.fnUntraced(function* (env?: Record, migrateLegacy = true) { let result: Info = {} // Seed the default global config with the schema for editor completion, but avoid writing when the user // explicitly routes config through env-provided paths or content. @@ -469,9 +468,11 @@ export const layer = Layer.effect( // altimate_change — a failed migration can still leave the parsed configuration usable. let parsedLegacy = false yield* Effect.promise(() => - import(pathToFileURL(legacy).href, { with: { type: "toml" } }) - .then(async (mod) => { - const { provider, model, ...rest } = mod.default + // altimate_change start — read again on retry so a repaired TOML file replaces a failed load. + fsNode.readFile(legacy, "utf8") + .then(async (text) => { + const { provider, model, ...rest } = Bun.TOML.parse(text) + // altimate_change end if (provider && model) result.model = `${provider}/${model}` // altimate_change start — altimate config schema URL result["$schema"] = "https://altimate.ai/config.json" @@ -479,6 +480,7 @@ export const layer = Layer.effect( result = mergeConfig(result, rest) // altimate_change — only read and parse failures leave the config unresolved. parsedLegacy = true + if (!migrateLegacy) return await fsNode.writeFile(path.join(Global.Path.config, "config.json"), JSON.stringify(result, null, 2)) await fsNode.unlink(legacy) }) @@ -945,11 +947,13 @@ export const layer = Layer.effect( // altimate_change end // altimate_change start — associate the status with this resolved config object - const globalUnresolved = incompleteGlobals.has(global) - if (globalUnresolved) configsWithUnresolvedGlobal.add(result) - if (orgConfigUnresolved) configsWithUnresolvedOrg.add(result) - if (orgConfigUnresolved || globalUnresolved || Auth.configSourcesUnresolved(auth)) { - configsWithUnresolvedTelemetry.add(result) + const unresolved = { + auth: Auth.configSourcesUnresolved(auth), + global: incompleteGlobals.has(global), + organization: orgConfigUnresolved, + } + if (unresolved.auth || unresolved.global || unresolved.organization) { + configsWithUnresolvedTelemetry.set(result, unresolved) } // altimate_change end @@ -990,24 +994,42 @@ export const layer = Layer.effect( const TELEMETRY_RETRY_MS = 30_000 function remoteRetryKey(result: Exit.Exit): object | undefined { if (Exit.isSuccess(result)) { - return configsWithUnresolvedOrg.has(result.value) ? result.value : undefined + return configsWithUnresolvedTelemetry.get(result.value)?.organization ? result.value : undefined } const failure = Cause.squash(result.cause) if (failure && typeof failure === "object" && remoteLoadFailures.has(failure)) return failure } + const localTelemetrySourcesReady = Effect.fnUntraced(function* (sources: UnresolvedTelemetrySources) { + if (!sources.auth && !sources.global) return true + + // Recheck local data before invalidating the merged result. An unreadable + // local layer cannot be repaired by fetching the remote configuration again. + const auth = yield* Effect.exit(authSvc.all()) + if (Exit.isFailure(auth) || Auth.configSourcesUnresolved(auth.value)) return false + if (!sources.global) return true + + const authEnv: Record = {} + for (const value of Object.values(auth.value)) { + if (value.type === "wellknown") authEnv[value.key] = value.token + } + const global = yield* Effect.exit(loadGlobal(authEnv, false)) + return Exit.isSuccess(global) && !incompleteGlobals.has(global.value) + }) + const get = Effect.fn("Config.get")(function* (retryTelemetry = false) { const read = InstanceState.use(state, (s) => s.config) if (!retryTelemetry || !(yield* InstanceState.has(state))) return yield* read const cached = yield* Effect.exit(read) - if (Exit.isSuccess(cached) && !telemetryConfigUnresolved(cached.value)) return cached.value + const sources = Exit.isSuccess(cached) ? configsWithUnresolvedTelemetry.get(cached.value) : undefined + if (Exit.isSuccess(cached) && (!sources || !(yield* localTelemetrySourcesReady(sources)))) return cached.value const remote = remoteRetryKey(cached) if (remote && performance.now() < (telemetryRetryAt.get(remote) ?? 0)) return yield* cached // A failed local read can have come from the global cache. A known remote // failure cannot, so keep a readable global cache in that case. - const reloadGlobal = Exit.isFailure(cached) ? !remote : configsWithUnresolvedGlobal.has(cached.value) + const reloadGlobal = Exit.isFailure(cached) ? !remote : sources?.global if (reloadGlobal) yield* invalidateGlobal yield* InstanceState.invalidate(state) const retried = yield* Effect.exit(read) diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index c8861fcadb..f186a80ece 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -876,6 +876,45 @@ for (const [format, body] of [ ) } +for (const localSource of ["auth", "global"] as const) { + let requests = 0 + const account = Layer.mock(Account.Service)({ + active: () => Effect.succeed(Option.some({ + id: AccountID.make("local-config-account"), + email: "user@example.com", + url: "https://control.example.invalid", + active_org_id: OrgID.make("org"), + })), + config: () => Effect.sync(() => { + requests++ + return Option.none() + }), + token: () => Effect.succeed(Option.none()), + }) + configIt({ account, auth: Auth.defaultLayer }).instance( + `an unreadable ${localSource} source recovers without refetching org config until repaired`, + () => + withGlobalConfig({}, ({ dir }) => + withProcessEnv( + "OPENCODE_AUTH_CONTENT", + localSource === "auth" ? "{" : "{}", + Effect.gen(function* () { + const legacy = path.join(dir, "config") + if (localSource === "global") yield* FSUtil.use.writeWithDirs(legacy, "broken = [") + expect(Config.telemetryConfigUnresolved(yield* Config.use.get())).toBe(true) + expect(Config.telemetryConfigUnresolved(yield* Config.use.get(true))).toBe(true) + expect(requests).toBe(1) + + if (localSource === "global") yield* FSUtil.use.writeWithDirs(legacy, "[telemetry]\ndisabled = false") + else process.env.OPENCODE_AUTH_CONTENT = "{}" + expect(Config.telemetryConfigUnresolved(yield* Config.use.get(true))).toBe(false) + expect(requests).toBe(2) + }), + ), + ), + ) +} + it.instance("a telemetry retry reloads a repaired config after a cached load failure", () => Effect.gen(function* () { const { directory } = yield* TestInstance From f7d043d1c331482efede21b74b06c296b7a89de8 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:04:09 -0800 Subject: [PATCH 14/63] fix: type the legacy config parser result --- packages/opencode/src/config/config.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index d6119ea5a8..fe4378be12 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -471,7 +471,8 @@ export const layer = Layer.effect( // altimate_change start — read again on retry so a repaired TOML file replaces a failed load. fsNode.readFile(legacy, "utf8") .then(async (text) => { - const { provider, model, ...rest } = Bun.TOML.parse(text) + const legacyConfig = Bun.TOML.parse(text) as Omit & { provider?: string } + const { provider, model, ...rest } = legacyConfig // altimate_change end if (provider && model) result.model = `${provider}/${model}` // altimate_change start — altimate config schema URL From 6af5b0100d19afaef2c4f2b628699f21690f17c3 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:10:26 -0800 Subject: [PATCH 15/63] fix: keep held telemetry scoped to its project --- .../opencode/src/altimate/telemetry/index.ts | 84 +++++++++++++------ .../test/altimate/telemetry/opt-out.test.ts | 32 +++++++ .../test/install/install-telemetry.test.ts | 4 + .../test/upstream/altimate-features.test.ts | 2 +- 4 files changed, 97 insertions(+), 25 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 7aaadb238b..612f01bcee 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -15,6 +15,7 @@ import fs from "fs" import path from "path" import os from "os" import { fileLog } from "@/altimate/util/file-log" +import { Filesystem } from "@/util/filesystem" const log = Log.create({ service: "telemetry" }) @@ -2286,7 +2287,9 @@ export namespace Telemetry { } let enabled = false - let buffer: Event[] = [] + let buffer: { event: Event; scope?: string; held?: boolean }[] = [] + let configScope: string | undefined + let reinitScope: string | undefined let flushTimer: ReturnType | undefined // altimate_change — who the machine is signed in as (backend user uuid + tenant), for the // funnel join with web events. Resolved off the stored credential in doInit(); see identity.ts. @@ -2311,7 +2314,11 @@ export namespace Telemetry { // Instance: the CLI initialises telemetry before a command changes into its `--dir` or project. let configDirectory: string | undefined export function setConfigDirectory(directory: string | undefined) { - configDirectory = directory + try { + configDirectory = directory === undefined ? undefined : Filesystem.resolve(directory) + } catch { + configDirectory = directory === undefined ? undefined : path.resolve(directory) + } } let machineId = "" let sessionId = "" @@ -2487,6 +2494,8 @@ export namespace Telemetry { // Deduplicates concurrent calls: non-awaited init() in middleware/worker // won't race with await init() in session prompt. export function init(): Promise { + const instance = TelemetryConfig.instanceDirectory() + const scope = instance ?? configDirectory ?? process.cwd() // altimate_change start — never re-init across an in-flight shutdown. // // session/prompt.ts init()s at the start of every session loop and shutdown()s at the end, so a @@ -2501,12 +2510,15 @@ export namespace Telemetry { // Chaining onto shutdownPromise keeps the generations separate: callers arriving mid-shutdown // wait for the new init rather than joining the dying one. if (shutdownPromise) { + if (reinitPromise && reinitScope !== scope) return reinitPromise.then(() => init()) if (!reinitPromise) { + reinitScope = scope reinitPromise = shutdownPromise .catch(() => {}) - .then(doInit) + .then(() => doInit(scope)) .finally(() => { reinitPromise = undefined + reinitScope = undefined }) // Publish it as initPromise too. Without this, a caller arriving after the shutdown had // settled — but before this chained doInit() finished — saw an empty initPromise and @@ -2522,7 +2534,10 @@ export namespace Telemetry { } return reinitPromise } - if (!initDone && initPromise && TelemetryConfig.instanceDirectory()) { + if (initPromise && configScope !== scope) { + return shutdown({ preserveUnresolved: true }).then(() => init()) + } + if (!initDone && initPromise && instance) { // A session can join the middleware init while its local probe is still running. // Retry once from the session's context when the probe could not resolve config. const pending = initPromise @@ -2535,28 +2550,40 @@ export namespace Telemetry { initPromise = undefined initDone = false } - return (initPromise ??= doInit()) + return (initPromise ??= doInit(scope)) // altimate_change end } - async function doInit() { + function clearScope(scope: string | undefined) { + buffer = buffer.filter((entry) => entry.scope !== scope) + droppedEvents = 0 + } + + async function doInit(scope: string) { + // Events tracked before the CLI selects its config directory belong to the + // first scope it resolves. Later scopes must resolve their own opt-out. + for (const entry of buffer) entry.scope ??= scope + const retry = (configUnresolved && configScope === scope) || buffer.some((entry) => entry.scope === scope && entry.held) + if (configScope !== undefined && configScope !== scope) droppedEvents = 0 + configScope = scope + configUnresolved = false try { // altimate_change start — hold bounded startup events until the opt-out is resolved. - const retry = configUnresolved - configUnresolved = false if (TelemetryConfig.disablingEnvironmentVariable()) { buffer = [] droppedEvents = 0 return } - const state = await TelemetryConfig.resolve(configDirectory, retry) + const state = await TelemetryConfig.resolve(scope, retry) if (state === "unreadable") { configUnresolved = true + for (const entry of buffer) { + if (entry.scope === scope) entry.held = true + } return } if (state === "disabled") { - buffer = [] - droppedEvents = 0 + clearScope(scope) return } // altimate_change end @@ -2569,13 +2596,13 @@ export namespace Telemetry { // and active-machine metric by ~33%. const explicit = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING if (!explicit && isAutomatedRun()) { - buffer = [] + clearScope(scope) return } const connectionString = explicit ?? DEFAULT_CONNECTION_STRING const cfg = parseConnectionString(connectionString) if (!cfg) { - buffer = [] + clearScope(scope) return } appInsights = cfg @@ -2602,10 +2629,10 @@ export namespace Telemetry { // altimate_change start — first-run health: drain anchor events that were tracked before init // finished (first_launch always is) instead of leaving them to the 5 s interval a startup freeze // would block. The stall watcher starts in `finally`, telemetry or not. - if (retry || buffer.some((event) => ANCHOR_EVENTS.has(event.type))) void Telemetry.flush().catch(() => {}) + if (buffer.some(({ event, scope: owner }) => owner === scope && (retry || ANCHOR_EVENTS.has(event.type)))) void Telemetry.flush().catch(() => {}) // altimate_change end } catch { - buffer = [] + clearScope(scope) } finally { initDone = true // altimate_change start — the stall watcher also writes each stall to opencode.log, which `debug bundle` @@ -2875,8 +2902,11 @@ export namespace Telemetry { // altimate_change end export function track(event: Event) { - // Buffer during init and while config is unresolved. A resolved opt-out drops events. - if (initDone && !enabled && !configUnresolved) return + // Membership is decided when events are tracked, never by whichever + // project happens to initialize before the next flush. + const directory = TelemetryConfig.instanceDirectory() ?? configDirectory + const scope = directory ?? (configScope === undefined ? undefined : process.cwd()) + if (scope === configScope && initDone && !enabled && !configUnresolved) return // altimate_change start — stamp the client trace of the turn the event's own session is // running, now: the event is serialised at flush time, when that turn may be over. Only an // explicit per-event `session_id` is used — the process-global session can be another one. @@ -2889,16 +2919,15 @@ export namespace Telemetry { // loop's rows, tool rows and memory rows carry the turn's; workspace rows carry their own) or it // carries none. A process-wide or per-session fallback kept attributing cancelled turns' rows to // their replacements. - buffer.push(event) + buffer.push({ event, scope, held: scope === configScope && configUnresolved }) if (buffer.length > MAX_BUFFER_SIZE) { - buffer.shift() - droppedEvents++ + if (buffer.shift()?.scope === configScope) droppedEvents++ } // altimate_change start — anchor events flush immediately. A frozen-then-killed process otherwise // dies with its buffer: the 5 s interval cannot fire while the loop is blocked, and the stall // report itself would be the first thing lost. if (event.type === "first_launch" && !event.is_upgrade) freshInstall = true - if (initDone && enabled && ANCHOR_EVENTS.has(event.type)) void Telemetry.flush().catch(() => {}) + if (scope === configScope && initDone && enabled && ANCHOR_EVENTS.has(event.type)) void Telemetry.flush().catch(() => {}) // altimate_change end } @@ -2940,7 +2969,10 @@ export namespace Telemetry { // altimate_change end if (!enabled || buffer.length === 0 || !appInsights) return - const events = buffer.splice(0, buffer.length) + const scope = configScope + const events = buffer.filter((entry) => entry.scope === scope).map(({ event }) => event) + if (events.length === 0) return + buffer = buffer.filter((entry) => entry.scope !== scope) if (droppedEvents > 0) { events.push({ @@ -2991,7 +3023,7 @@ export namespace Telemetry { if (attempted.has(e)) (e as any)._retried = true } const space = Math.max(0, MAX_BUFFER_SIZE - buffer.length) - buffer.unshift(...retriable.slice(0, space)) + buffer.unshift(...retriable.slice(0, space).map((event) => ({ event, scope }))) } finally { clearTimeout(timeout) if (activeFlushAbort === controller) activeFlushAbort = undefined @@ -3108,10 +3140,14 @@ export namespace Telemetry { shuttingDown = false enabled = false appInsights = undefined - if (!preserveUnresolved || !configUnresolved) { + if (!preserveUnresolved) { configUnresolved = false + configScope = undefined buffer = [] droppedEvents = 0 + } else if (!configUnresolved) { + clearScope(configScope) + configScope = undefined } sessionId = "" projectId = "" diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 9f66500899..3cd2b10a7c 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -278,6 +278,38 @@ describe("telemetry opt-out", () => { expect(names).toEqual(["startup_ready"]) }) + test("only the owning project can release a held startup event", async () => { + const names = recordIngestion() + process.env.OPENCODE_CONFIG_CONTENT = "{" + trackStartup() + await Telemetry.init() + await Telemetry.shutdown({ preserveUnresolved: true }) + expect(fetchSpy).not.toHaveBeenCalled() + + rmSync(path.join(home, ".altimate", "altimate.json")) + const other = path.join(home, "other") + mkdirSync(other) + Telemetry.setConfigDirectory(other) + configSpy.mockResolvedValue({}) + Telemetry.track({ + type: "error", + timestamp: Date.now(), + error_name: "OtherProject", + error_message: "test", + context: "test", + session_id: "", + }) + await Telemetry.init() + await Telemetry.flush() + expect(names).toEqual(["error"]) + await Telemetry.shutdown({ preserveUnresolved: true }) + + Telemetry.setConfigDirectory(home) + await Telemetry.init() + await Telemetry.flush() + expect(names).toEqual(["error", "startup_ready"]) + }) + test("resolution to disabled discards held startup events", async () => { const names = recordIngestion() process.env.OPENCODE_CONFIG_CONTENT = "{" diff --git a/packages/opencode/test/install/install-telemetry.test.ts b/packages/opencode/test/install/install-telemetry.test.ts index f9a0c64515..37c31eaa64 100644 --- a/packages/opencode/test/install/install-telemetry.test.ts +++ b/packages/opencode/test/install/install-telemetry.test.ts @@ -302,6 +302,7 @@ describe("is_upgrade ordering", () => { // would make the "machine-id exists after await" assertion fail on a machine or CI // runner that exports OPENCODE_DISABLE_TELEMETRY. const origOpencodeDisabled = process.env.OPENCODE_DISABLE_TELEMETRY + const origCliDisabled = process.env.ALTIMATE_CLI_DISABLE_TELEMETRY const tmpHome = mkdtempSync(join(os.tmpdir(), "install-telemetry-home-")) spyOn(os, "homedir").mockImplementation(() => tmpHome) spyOn(Config, "get").mockResolvedValue({}) @@ -312,6 +313,7 @@ describe("is_upgrade ordering", () => { // when it has no connection string — which would make this test vacuously pass. delete process.env.ALTIMATE_TELEMETRY_DISABLED delete process.env.OPENCODE_DISABLE_TELEMETRY + delete process.env.ALTIMATE_CLI_DISABLE_TELEMETRY process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "InstrumentationKey=k;IngestionEndpoint=https://example.invalid" // init() is `initPromise ??= doInit()`; shutdown() is the only seam that clears it, so @@ -336,6 +338,8 @@ describe("is_upgrade ordering", () => { else delete process.env.ALTIMATE_TELEMETRY_DISABLED if (origOpencodeDisabled !== undefined) process.env.OPENCODE_DISABLE_TELEMETRY = origOpencodeDisabled else delete process.env.OPENCODE_DISABLE_TELEMETRY + if (origCliDisabled !== undefined) process.env.ALTIMATE_CLI_DISABLE_TELEMETRY = origCliDisabled + else delete process.env.ALTIMATE_CLI_DISABLE_TELEMETRY rmSync(tmpHome, { recursive: true, force: true }) } }) diff --git a/packages/opencode/test/upstream/altimate-features.test.ts b/packages/opencode/test/upstream/altimate-features.test.ts index c05ae4041c..b501c340a2 100644 --- a/packages/opencode/test/upstream/altimate-features.test.ts +++ b/packages/opencode/test/upstream/altimate-features.test.ts @@ -401,7 +401,7 @@ describe("altimate features: telemetry fail-safe init", () => { test("telemetry can resolve the opt-out before an Instance exists", async () => { const init = await readSrc("altimate", "telemetry", "index.ts") const config = await readSrc("altimate", "telemetry", "config-state.ts") - expect(init).toContain("await TelemetryConfig.resolve(configDirectory, retry)") + expect(init).toContain("await TelemetryConfig.resolve(scope, retry)") expect(config).toMatch(/try\s*\{\s*return await loadedState\(retry\)/) expect(config).toContain('return instanceDirectory() ? "unreadable" : disabledState(directory)') expect(config).toContain("ALTIMATE_TELEMETRY_DISABLED") From f8e31acad9fab4fb960b1571bb64424eaff07abb Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:14:59 -0800 Subject: [PATCH 16/63] fix: gate identity refresh on project telemetry permission --- .../opencode/src/altimate/telemetry/index.ts | 9 +++++---- .../test/altimate/telemetry/opt-out.test.ts | 16 +++++++++++++--- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 612f01bcee..b8d2ceb981 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2712,11 +2712,11 @@ export namespace Telemetry { * Does nothing while telemetry is disabled. */ export async function refreshIdentity(): Promise { // Opted out (or not initialised): no lookup; an enabled init resolves from the stored credential. - if (!enabled || shutdownPromise) return + if (!isEnabled() || shutdownPromise) return // A refresh queued behind a flush belongs to the init that started it. const startedUnder = initPromise await flush() - if (!enabled || shutdownPromise || initPromise !== startedUnder) return + if (!isEnabled() || shutdownPromise || initPromise !== startedUnder) return identity = undefined await resolveIdentity({ refresh: true }) } @@ -2748,9 +2748,10 @@ export namespace Telemetry { return { sessionId, projectId } } - /** Returns true only after init() has completed and telemetry is enabled. */ + /** Returns true once telemetry is enabled for the calling project's config. */ export function isEnabled(): boolean { - return initDone && enabled + if (!initDone || !enabled) return false + return configScope === (TelemetryConfig.instanceDirectory() ?? configDirectory ?? process.cwd()) } // altimate_change start — first-run health instrumentation (see the startup_ready, event_loop_stall diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 3cd2b10a7c..8c2d9b0ec7 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -1,6 +1,6 @@ import { Database as SQLite } from "bun:sqlite" import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test" -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs" +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs" import os from "os" import path from "path" import { Database } from "@opencode-ai/core/database/database" @@ -286,7 +286,9 @@ describe("telemetry opt-out", () => { await Telemetry.shutdown({ preserveUnresolved: true }) expect(fetchSpy).not.toHaveBeenCalled() - rmSync(path.join(home, ".altimate", "altimate.json")) + const credentialsPath = path.join(home, ".altimate", "altimate.json") + const credentials = readFileSync(credentialsPath) + rmSync(credentialsPath) const other = path.join(home, "other") mkdirSync(other) Telemetry.setConfigDirectory(other) @@ -302,9 +304,17 @@ describe("telemetry opt-out", () => { await Telemetry.init() await Telemetry.flush() expect(names).toEqual(["error"]) - await Telemetry.shutdown({ preserveUnresolved: true }) + await Telemetry.refreshIdentity() + const callsBeforeSwitch = fetchSpy.mock.calls.length Telemetry.setConfigDirectory(home) + writeFileSync(credentialsPath, credentials) + expect(Telemetry.isEnabled()).toBe(false) + await Telemetry.refreshIdentity() + expect(fetchSpy).toHaveBeenCalledTimes(callsBeforeSwitch) + rmSync(credentialsPath) + await Telemetry.shutdown({ preserveUnresolved: true }) + await Telemetry.init() await Telemetry.flush() expect(names).toEqual(["error", "startup_ready"]) From 79f5440dc9253b2cbe21671082fb874611af75d5 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:17:52 -0800 Subject: [PATCH 17/63] fix: preserve telemetry scope on overflow and cwd failure --- .../opencode/src/altimate/telemetry/index.ts | 53 ++++++++++++++----- .../test/altimate/telemetry/opt-out.test.ts | 48 +++++++++++++++++ 2 files changed, 87 insertions(+), 14 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index b8d2ceb981..9f78701acc 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -217,6 +217,14 @@ const PATH_RULES = { } // altimate_change end +function telemetryWorkingDirectory(): string | undefined { + try { + return process.cwd() + } catch { + return undefined + } +} + export namespace Telemetry { const FLUSH_INTERVAL_MS = 5_000 const MAX_BUFFER_SIZE = 200 @@ -2287,7 +2295,7 @@ export namespace Telemetry { } let enabled = false - let buffer: { event: Event; scope?: string; held?: boolean }[] = [] + let buffer: { event: Event; scope?: string | null; held?: boolean }[] = [] let configScope: string | undefined let reinitScope: string | undefined let flushTimer: ReturnType | undefined @@ -2331,7 +2339,8 @@ export namespace Telemetry { let nextTurn = 0 // altimate_change end let appInsights: AppInsightsConfig | undefined - let droppedEvents = 0 + // Keep counters only for scopes still represented in the bounded buffer. + const droppedEvents = new Map() let initPromise: Promise | undefined // altimate_change — unresolved config holds events for the next init call. let configUnresolved = false @@ -2495,7 +2504,8 @@ export namespace Telemetry { // won't race with await init() in session prompt. export function init(): Promise { const instance = TelemetryConfig.instanceDirectory() - const scope = instance ?? configDirectory ?? process.cwd() + const scope = instance ?? configDirectory ?? telemetryWorkingDirectory() + if (scope === undefined) return Promise.resolve() // altimate_change start — never re-init across an in-flight shutdown. // // session/prompt.ts init()s at the start of every session loop and shutdown()s at the end, so a @@ -2556,22 +2566,28 @@ export namespace Telemetry { function clearScope(scope: string | undefined) { buffer = buffer.filter((entry) => entry.scope !== scope) - droppedEvents = 0 + droppedEvents.delete(scope) } async function doInit(scope: string) { // Events tracked before the CLI selects its config directory belong to the // first scope it resolves. Later scopes must resolve their own opt-out. - for (const entry of buffer) entry.scope ??= scope + for (const entry of buffer) { + if (entry.scope === undefined) entry.scope = scope + } + const earlyDrops = droppedEvents.get(undefined) + if (earlyDrops) { + droppedEvents.set(scope, (droppedEvents.get(scope) ?? 0) + earlyDrops) + droppedEvents.delete(undefined) + } const retry = (configUnresolved && configScope === scope) || buffer.some((entry) => entry.scope === scope && entry.held) - if (configScope !== undefined && configScope !== scope) droppedEvents = 0 configScope = scope configUnresolved = false try { // altimate_change start — hold bounded startup events until the opt-out is resolved. if (TelemetryConfig.disablingEnvironmentVariable()) { buffer = [] - droppedEvents = 0 + droppedEvents.clear() return } const state = await TelemetryConfig.resolve(scope, retry) @@ -2751,7 +2767,7 @@ export namespace Telemetry { /** Returns true once telemetry is enabled for the calling project's config. */ export function isEnabled(): boolean { if (!initDone || !enabled) return false - return configScope === (TelemetryConfig.instanceDirectory() ?? configDirectory ?? process.cwd()) + return configScope === (TelemetryConfig.instanceDirectory() ?? configDirectory ?? telemetryWorkingDirectory()) } // altimate_change start — first-run health instrumentation (see the startup_ready, event_loop_stall @@ -2906,7 +2922,9 @@ export namespace Telemetry { // Membership is decided when events are tracked, never by whichever // project happens to initialize before the next flush. const directory = TelemetryConfig.instanceDirectory() ?? configDirectory - const scope = directory ?? (configScope === undefined ? undefined : process.cwd()) + const cwd = directory === undefined ? telemetryWorkingDirectory() : undefined + // Keep events from an inaccessible directory unassigned until exit. + const scope = directory ?? (cwd === undefined ? null : configScope === undefined ? undefined : cwd) if (scope === configScope && initDone && !enabled && !configUnresolved) return // altimate_change start — stamp the client trace of the turn the event's own session is // running, now: the event is serialised at flush time, when that turn may be over. Only an @@ -2922,7 +2940,13 @@ export namespace Telemetry { // their replacements. buffer.push({ event, scope, held: scope === configScope && configUnresolved }) if (buffer.length > MAX_BUFFER_SIZE) { - if (buffer.shift()?.scope === configScope) droppedEvents++ + const dropped = buffer.shift()! + const owner = dropped.scope + if (owner !== null && buffer.some((entry) => entry.scope === owner)) { + droppedEvents.set(owner, (droppedEvents.get(owner) ?? 0) + 1) + } else { + droppedEvents.delete(owner) + } } // altimate_change start — anchor events flush immediately. A frozen-then-killed process otherwise // dies with its buffer: the 5 s interval cannot fire while the loop is blocked, and the stall @@ -2975,16 +2999,17 @@ export namespace Telemetry { if (events.length === 0) return buffer = buffer.filter((entry) => entry.scope !== scope) - if (droppedEvents > 0) { + const dropped = droppedEvents.get(scope) + droppedEvents.delete(scope) + if (dropped) { events.push({ type: "error", timestamp: Date.now(), session_id: sessionId, error_name: "TelemetryBufferOverflow", - error_message: `${droppedEvents} events dropped due to buffer overflow`, + error_message: `${dropped} events dropped due to buffer overflow`, context: "telemetry", } as Event) - droppedEvents = 0 } const controller = new AbortController() @@ -3145,7 +3170,7 @@ export namespace Telemetry { configUnresolved = false configScope = undefined buffer = [] - droppedEvents = 0 + droppedEvents.clear() } else if (!configUnresolved) { clearScope(configScope) configScope = undefined diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 8c2d9b0ec7..4d1d948309 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -320,6 +320,54 @@ describe("telemetry opt-out", () => { expect(names).toEqual(["error", "startup_ready"]) }) + test("a missing working directory leaves telemetry unresolved without throwing", async () => { + const names = recordIngestion() + Telemetry.setConfigDirectory(undefined) + const cwd = spyOn(process, "cwd").mockImplementation(() => { + throw new Error("working directory deleted") + }) + try { + trackStartup() + await Telemetry.init() + await Telemetry.flush() + expect(Telemetry.isEnabled()).toBe(false) + expect(fetchSpy).not.toHaveBeenCalled() + } finally { + cwd.mockRestore() + } + + rmSync(path.join(home, ".altimate", "altimate.json")) + Telemetry.setConfigDirectory(home) + configSpy.mockResolvedValue({}) + await Telemetry.init() + await Telemetry.flush() + expect(names).toEqual([]) + }) + + test("held overflow counts stay with the owning project", async () => { + const names = recordIngestion() + process.env.OPENCODE_CONFIG_CONTENT = "{" + await Telemetry.init() + for (let i = 0; i < 201; i++) trackStartup() + await Telemetry.shutdown({ preserveUnresolved: true }) + + rmSync(path.join(home, ".altimate", "altimate.json")) + const other = path.join(home, "other") + mkdirSync(other) + Telemetry.setConfigDirectory(other) + configSpy.mockResolvedValue({}) + await Telemetry.init() + await Telemetry.flush() + expect(names).toEqual([]) + await Telemetry.shutdown({ preserveUnresolved: true }) + + Telemetry.setConfigDirectory(home) + await Telemetry.init() + await Telemetry.flush() + expect(names.filter((name) => name === "startup_ready")).toHaveLength(200) + expect(names.filter((name) => name === "error")).toHaveLength(1) + }) + test("resolution to disabled discards held startup events", async () => { const names = recordIngestion() process.env.OPENCODE_CONFIG_CONTENT = "{" From bfbc81517a860bde54698a89a3ece0b92b9bd62f Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:21:07 -0800 Subject: [PATCH 18/63] fix: bound scoped telemetry handoffs and overflow accounting --- .../opencode/src/altimate/telemetry/index.ts | 37 ++++++++++++------- .../test/altimate/telemetry/opt-out.test.ts | 26 ++++++++++--- 2 files changed, 45 insertions(+), 18 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 9f78701acc..92b9fb02bd 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2339,8 +2339,8 @@ export namespace Telemetry { let nextTurn = 0 // altimate_change end let appInsights: AppInsightsConfig | undefined - // Keep counters only for scopes still represented in the bounded buffer. - const droppedEvents = new Map() + // Remember evicted scopes without letting overflow accounting grow unbounded. + const droppedEvents = new Map() let initPromise: Promise | undefined // altimate_change — unresolved config holds events for the next init call. let configUnresolved = false @@ -2545,7 +2545,7 @@ export namespace Telemetry { return reinitPromise } if (initPromise && configScope !== scope) { - return shutdown({ preserveUnresolved: true }).then(() => init()) + return shutdown({ preserveUnresolved: true, timeoutMs: EXIT_FLUSH_BUDGET_MS }).then(() => init()) } if (!initDone && initPromise && instance) { // A session can join the middleware init while its local probe is still running. @@ -2577,10 +2577,13 @@ export namespace Telemetry { } const earlyDrops = droppedEvents.get(undefined) if (earlyDrops) { - droppedEvents.set(scope, (droppedEvents.get(scope) ?? 0) + earlyDrops) + const scopedDrops = droppedEvents.get(scope) droppedEvents.delete(undefined) + droppedEvents.set(scope, { count: (scopedDrops?.count ?? 0) + earlyDrops.count, held: scopedDrops?.held }) } - const retry = (configUnresolved && configScope === scope) || buffer.some((entry) => entry.scope === scope && entry.held) + const retry = (configUnresolved && configScope === scope) || + droppedEvents.get(scope)?.held || + buffer.some((entry) => entry.scope === scope && entry.held) configScope = scope configUnresolved = false try { @@ -2593,6 +2596,8 @@ export namespace Telemetry { const state = await TelemetryConfig.resolve(scope, retry) if (state === "unreadable") { configUnresolved = true + const drops = droppedEvents.get(scope) + if (drops) drops.held = true for (const entry of buffer) { if (entry.scope === scope) entry.held = true } @@ -2645,7 +2650,9 @@ export namespace Telemetry { // altimate_change start — first-run health: drain anchor events that were tracked before init // finished (first_launch always is) instead of leaving them to the 5 s interval a startup freeze // would block. The stall watcher starts in `finally`, telemetry or not. - if (buffer.some(({ event, scope: owner }) => owner === scope && (retry || ANCHOR_EVENTS.has(event.type)))) void Telemetry.flush().catch(() => {}) + if (droppedEvents.has(scope) || buffer.some(({ event, scope: owner }) => + owner === scope && (retry || ANCHOR_EVENTS.has(event.type)), + )) void Telemetry.flush().catch(() => {}) // altimate_change end } catch { clearScope(scope) @@ -2921,7 +2928,8 @@ export namespace Telemetry { export function track(event: Event) { // Membership is decided when events are tracked, never by whichever // project happens to initialize before the next flush. - const directory = TelemetryConfig.instanceDirectory() ?? configDirectory + const directory = TelemetryConfig.instanceDirectory() ?? configDirectory ?? + (event.type === "event_loop_stall" ? configScope : undefined) const cwd = directory === undefined ? telemetryWorkingDirectory() : undefined // Keep events from an inaccessible directory unassigned until exit. const scope = directory ?? (cwd === undefined ? null : configScope === undefined ? undefined : cwd) @@ -2942,10 +2950,13 @@ export namespace Telemetry { if (buffer.length > MAX_BUFFER_SIZE) { const dropped = buffer.shift()! const owner = dropped.scope - if (owner !== null && buffer.some((entry) => entry.scope === owner)) { - droppedEvents.set(owner, (droppedEvents.get(owner) ?? 0) + 1) - } else { + if (owner !== null) { + const previous = droppedEvents.get(owner) droppedEvents.delete(owner) + droppedEvents.set(owner, { count: (previous?.count ?? 0) + 1, held: previous?.held || dropped.held }) + if (droppedEvents.size > MAX_BUFFER_SIZE) { + droppedEvents.delete(droppedEvents.keys().next().value) + } } } // altimate_change start — anchor events flush immediately. A frozen-then-killed process otherwise @@ -2992,14 +3003,14 @@ export namespace Telemetry { } } // altimate_change end - if (!enabled || buffer.length === 0 || !appInsights) return + if (!enabled || !appInsights) return const scope = configScope const events = buffer.filter((entry) => entry.scope === scope).map(({ event }) => event) - if (events.length === 0) return + const dropped = droppedEvents.get(scope)?.count + if (events.length === 0 && !dropped) return buffer = buffer.filter((entry) => entry.scope !== scope) - const dropped = droppedEvents.get(scope) droppedEvents.delete(scope) if (dropped) { events.push({ diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 4d1d948309..c71802f22d 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -344,28 +344,44 @@ describe("telemetry opt-out", () => { expect(names).toEqual([]) }) - test("held overflow counts stay with the owning project", async () => { + test("even a fully evicted project keeps its own overflow count", async () => { const names = recordIngestion() process.env.OPENCODE_CONFIG_CONTENT = "{" await Telemetry.init() - for (let i = 0; i < 201; i++) trackStartup() + trackStartup() await Telemetry.shutdown({ preserveUnresolved: true }) rmSync(path.join(home, ".altimate", "altimate.json")) const other = path.join(home, "other") mkdirSync(other) Telemetry.setConfigDirectory(other) - configSpy.mockResolvedValue({}) + for (let i = 0; i < 200; i++) trackStartup() + configSpy.mockResolvedValue({ telemetry: { disabled: true } }) await Telemetry.init() await Telemetry.flush() expect(names).toEqual([]) await Telemetry.shutdown({ preserveUnresolved: true }) Telemetry.setConfigDirectory(home) + configSpy.mockResolvedValue({}) + await Telemetry.init() + await Telemetry.flush() + expect(names).toEqual(["error"]) + expect(String(fetchSpy.mock.calls.at(-1)?.[1]?.body)).toContain("TelemetryBufferOverflow") + }) + + test("a process-wide stall keeps the active scope outside its instance context", async () => { + const names = recordIngestion() + rmSync(path.join(home, ".altimate", "altimate.json")) + configSpy.mockResolvedValue({}) await Telemetry.init() + + Telemetry.setConfigDirectory(undefined) + const stall = Telemetry.loopStallFor(1500, 0, 1000, "main") + expect(stall).toBeDefined() + Telemetry.track(stall!) await Telemetry.flush() - expect(names.filter((name) => name === "startup_ready")).toHaveLength(200) - expect(names.filter((name) => name === "error")).toHaveLength(1) + expect(names).toEqual(["event_loop_stall"]) }) test("resolution to disabled discards held startup events", async () => { From d026eda37ddaa20ed457e1712d5596e2740a0df5 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:30:11 -0800 Subject: [PATCH 19/63] fix: retain timed-out telemetry batches for their scope --- .../opencode/src/altimate/telemetry/index.ts | 47 ++++++++------- packages/opencode/src/session/prompt.ts | 2 +- .../test/altimate/telemetry/opt-out.test.ts | 57 +++++++++++++++++-- 3 files changed, 80 insertions(+), 26 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 92b9fb02bd..dbd97aa7a1 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2352,6 +2352,7 @@ export namespace Telemetry { // cleared and ship them under the NEXT lifecycle. let activeFlushAbort: AbortController | undefined let shuttingDown = false + let retainPendingOnShutdown = false // altimate_change — in-flight shutdown, declared with the rest of the module state so init() // above can consult it. See shutdown() for why concurrent shutdowns must be serialized. let shutdownPromise: Promise | undefined @@ -2500,11 +2501,16 @@ export namespace Telemetry { const DEFAULT_CONNECTION_STRING = "InstrumentationKey=5095f5e6-477e-4262-b7ae-2118de18550d;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=6564474f-329b-4b7d-849e-e70cb4181294" + function resolveScope(processWide = false) { + const instance = TelemetryConfig.instanceDirectory() + const directory = instance ?? (processWide ? configScope : undefined) ?? configDirectory + return { instance, directory, scope: directory ?? telemetryWorkingDirectory() } + } + // Deduplicates concurrent calls: non-awaited init() in middleware/worker // won't race with await init() in session prompt. export function init(): Promise { - const instance = TelemetryConfig.instanceDirectory() - const scope = instance ?? configDirectory ?? telemetryWorkingDirectory() + const { instance, scope } = resolveScope() if (scope === undefined) return Promise.resolve() // altimate_change start — never re-init across an in-flight shutdown. // @@ -2545,7 +2551,7 @@ export namespace Telemetry { return reinitPromise } if (initPromise && configScope !== scope) { - return shutdown({ preserveUnresolved: true, timeoutMs: EXIT_FLUSH_BUDGET_MS }).then(() => init()) + return shutdown({ preservePending: true, timeoutMs: EXIT_FLUSH_BUDGET_MS }).then(() => init()) } if (!initDone && initPromise && instance) { // A session can join the middleware init while its local probe is still running. @@ -2579,7 +2585,7 @@ export namespace Telemetry { if (earlyDrops) { const scopedDrops = droppedEvents.get(scope) droppedEvents.delete(undefined) - droppedEvents.set(scope, { count: (scopedDrops?.count ?? 0) + earlyDrops.count, held: scopedDrops?.held }) + droppedEvents.set(scope, { count: (scopedDrops?.count ?? 0) + earlyDrops.count, held: scopedDrops?.held || earlyDrops.held }) } const retry = (configUnresolved && configScope === scope) || droppedEvents.get(scope)?.held || @@ -2774,7 +2780,7 @@ export namespace Telemetry { /** Returns true once telemetry is enabled for the calling project's config. */ export function isEnabled(): boolean { if (!initDone || !enabled) return false - return configScope === (TelemetryConfig.instanceDirectory() ?? configDirectory ?? telemetryWorkingDirectory()) + return configScope === resolveScope().scope } // altimate_change start — first-run health instrumentation (see the startup_ready, event_loop_stall @@ -2928,11 +2934,9 @@ export namespace Telemetry { export function track(event: Event) { // Membership is decided when events are tracked, never by whichever // project happens to initialize before the next flush. - const directory = TelemetryConfig.instanceDirectory() ?? configDirectory ?? - (event.type === "event_loop_stall" ? configScope : undefined) - const cwd = directory === undefined ? telemetryWorkingDirectory() : undefined + const caller = resolveScope(event.type === "event_loop_stall") // Keep events from an inaccessible directory unassigned until exit. - const scope = directory ?? (cwd === undefined ? null : configScope === undefined ? undefined : cwd) + const scope = caller.directory ?? (caller.scope === undefined ? null : configScope === undefined ? undefined : caller.scope) if (scope === configScope && initDone && !enabled && !configUnresolved) return // altimate_change start — stamp the client trace of the turn the event's own session is // running, now: the event is serialised at flush time, when that turn may be over. Only an @@ -3049,10 +3053,9 @@ export namespace Telemetry { } } } catch { - // altimate_change — no write-back during shutdown. The buffer is cleared a few lines later - // regardless, so re-inserting here does not save these events; it only leaves them to be - // shipped by whatever lifecycle comes next, under a different launch id. - if (shuttingDown) return + // altimate_change — only process exit drops unsent retries. A project handoff + // can retain them for the same scope without extending the transport deadline. + if (shuttingDown && !retainPendingOnShutdown) return // Re-add events that haven't been retried yet to avoid data loss const retriable = events.filter((e) => !sent.has(e) && !(e as any)._retried) // altimate_change — a batch never attempted (an earlier one failed) keeps its retry. @@ -3095,7 +3098,7 @@ export namespace Telemetry { // `timeoutMs` bounds the flush from the inside. Racing shutdown() against an external timer // does NOT cancel it: the losing promise keeps running and resets module state after the // caller has already moved on. Exit paths pass a budget so the fetch itself is aborted. - export async function shutdown(opts?: { timeoutMs?: number; preserveUnresolved?: boolean }) { + export async function shutdown(opts?: { timeoutMs?: number; preservePending?: boolean }) { if (shutdownPromise) { // An earlier caller is mid-flush, possibly on the default 10s budget. Returning its promise // unchanged would silently ignore this caller's deadline and make the exit path wait past @@ -3113,13 +3116,13 @@ export namespace Telemetry { if (timer) clearTimeout(timer) return } - shutdownPromise = doShutdown(opts?.timeoutMs, opts?.preserveUnresolved).finally(() => { + shutdownPromise = doShutdown(opts?.timeoutMs, opts?.preservePending).finally(() => { shutdownPromise = undefined }) return shutdownPromise } - async function doShutdown(timeoutMs?: number, preserveUnresolved?: boolean) { + async function doShutdown(timeoutMs?: number, preservePending?: boolean) { const initPromiseAtShutdown = initPromise // Wait for init to complete so we know whether telemetry is enabled // and have a valid endpoint to flush to. init() is fire-and-forget @@ -3142,6 +3145,7 @@ export namespace Telemetry { // in mid-request is not abandoned and cannot write back into a buffer we are about to clear. const deadline = Date.now() + (timeoutMs ?? REQUEST_TIMEOUT_MS) shuttingDown = true + retainPendingOnShutdown = Boolean(preservePending) if (inFlightFlush) { // Bounded: a flush already in flight uses the DEFAULT request timeout, so awaiting it // unbounded could burn 10s before the bounded flush below even starts — well past the 5s @@ -3170,20 +3174,21 @@ export namespace Telemetry { await inFlightFlush.catch(() => {}) } } - // Whatever the drain left of the shared deadline, never below a floor that lets the request - // actually be made. - await flush(Math.max(250, deadline - Date.now())) + // Spend the remaining budget on a final flush if there is time. At process exit, reserve + // a small floor for the last attempt because there is no later lifecycle to retry it. + const remaining = deadline - Date.now() + if (!preservePending || remaining >= 250) await flush(Math.max(250, remaining)) inFlightFlush = undefined shuttingDown = false + retainPendingOnShutdown = false enabled = false appInsights = undefined - if (!preserveUnresolved) { + if (!preservePending) { configUnresolved = false configScope = undefined buffer = [] droppedEvents.clear() } else if (!configUnresolved) { - clearScope(configScope) configScope = undefined } sessionId = "" diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 5a18c2a7b0..8361ac3232 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -2796,7 +2796,7 @@ export namespace SessionPrompt { }) Telemetry.endSession(sessionID, telemetryTurn) // altimate_change — after the row, this turn only } - await Telemetry.shutdown({ preserveUnresolved: true }) + await Telemetry.shutdown({ preservePending: true }) // altimate_change end // altimate_change start — resolve callbacks from this prompt generation only for (const item of orderedMessageStream(readMessageOrder())) { diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index c71802f22d..2860ef27c3 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -283,7 +283,7 @@ describe("telemetry opt-out", () => { process.env.OPENCODE_CONFIG_CONTENT = "{" trackStartup() await Telemetry.init() - await Telemetry.shutdown({ preserveUnresolved: true }) + await Telemetry.shutdown({ preservePending: true }) expect(fetchSpy).not.toHaveBeenCalled() const credentialsPath = path.join(home, ".altimate", "altimate.json") @@ -313,13 +313,62 @@ describe("telemetry opt-out", () => { await Telemetry.refreshIdentity() expect(fetchSpy).toHaveBeenCalledTimes(callsBeforeSwitch) rmSync(credentialsPath) - await Telemetry.shutdown({ preserveUnresolved: true }) + await Telemetry.shutdown({ preservePending: true }) await Telemetry.init() await Telemetry.flush() expect(names).toEqual(["error", "startup_ready"]) }) + test.each(["queued", "in-flight"] as const)("a timed-out handoff keeps the %s batch for its own project", async (state) => { + rmSync(path.join(home, ".altimate", "altimate.json")) + const names = recordIngestion() + const ingest = fetchSpy.getMockImplementation()! + let timedOut = false + let notifyStarted!: () => void + const started = new Promise((resolve) => { notifyStarted = resolve }) + fetchSpy.mockImplementation(Object.assign( + (url: Parameters[0], request?: Parameters[1]) => { + if (timedOut) return ingest(url, request) + notifyStarted() + return new Promise((_, reject) => { + request?.signal?.addEventListener("abort", () => { + timedOut = true + reject(new Error("ingestion timed out")) + }, { once: true }) + }) + }, + { preconnect: fetch.preconnect }, + )) + configSpy.mockResolvedValue({}) + await Telemetry.init() + Telemetry.track({ + type: "error", + timestamp: Date.now(), + error_name: "OutgoingProject", + error_message: "test", + context: "test", + session_id: "", + }) + + if (state === "in-flight") { + void Telemetry.flush() + await started + } + const other = path.join(home, "other") + mkdirSync(other) + Telemetry.setConfigDirectory(other) + await Telemetry.init() + await Telemetry.flush() + expect(timedOut).toBe(true) + expect(names).toEqual([]) + + Telemetry.setConfigDirectory(home) + await Telemetry.init() + await Telemetry.flush() + expect(names).toEqual(["error"]) + }) + test("a missing working directory leaves telemetry unresolved without throwing", async () => { const names = recordIngestion() Telemetry.setConfigDirectory(undefined) @@ -349,7 +398,7 @@ describe("telemetry opt-out", () => { process.env.OPENCODE_CONFIG_CONTENT = "{" await Telemetry.init() trackStartup() - await Telemetry.shutdown({ preserveUnresolved: true }) + await Telemetry.shutdown({ preservePending: true }) rmSync(path.join(home, ".altimate", "altimate.json")) const other = path.join(home, "other") @@ -360,7 +409,7 @@ describe("telemetry opt-out", () => { await Telemetry.init() await Telemetry.flush() expect(names).toEqual([]) - await Telemetry.shutdown({ preserveUnresolved: true }) + await Telemetry.shutdown({ preservePending: true }) Telemetry.setConfigDirectory(home) configSpy.mockResolvedValue({}) From 3866ab0a4efa2b6b0372688d0f6ae10e43164add Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:31:33 -0800 Subject: [PATCH 20/63] test: observe identity lookup before transport starts --- .../opencode/test/altimate/telemetry/opt-out.test.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 2860ef27c3..bd6b47e9c9 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -8,6 +8,7 @@ import { Auth } from "../../../src/auth" import { Config } from "../../../src/config/config" import { Telemetry } from "../../../src/altimate/telemetry" import { TelemetryConfig } from "../../../src/altimate/telemetry/config-state" +import { TelemetryIdentity } from "../../../src/altimate/telemetry/identity" const CS = "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://ingest.example.invalid/" const ENV = [ @@ -310,8 +311,14 @@ describe("telemetry opt-out", () => { Telemetry.setConfigDirectory(home) writeFileSync(credentialsPath, credentials) expect(Telemetry.isEnabled()).toBe(false) - await Telemetry.refreshIdentity() - expect(fetchSpy).toHaveBeenCalledTimes(callsBeforeSwitch) + const lookup = spyOn(TelemetryIdentity, "resolveWithOutcome").mockResolvedValue({ outcome: "none" }) + try { + await Telemetry.refreshIdentity() + expect(lookup).not.toHaveBeenCalled() + expect(fetchSpy).toHaveBeenCalledTimes(callsBeforeSwitch) + } finally { + lookup.mockRestore() + } rmSync(credentialsPath) await Telemetry.shutdown({ preservePending: true }) From 7f119a9c743ceab546d014e623040404fa8af07d Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:37:03 -0800 Subject: [PATCH 21/63] test: use the scoped config fixture for telemetry recovery --- packages/opencode/test/config/config.test.ts | 124 +++++++++---------- 1 file changed, 58 insertions(+), 66 deletions(-) diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index f186a80ece..dffad8fc73 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -719,17 +719,7 @@ for (const failure of ["account", "organization"] as const) { ) } -test("telemetry sends held events after an organization config fetch recovers", async () => { - const directory = await tmpdir() - const savedSink = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING - const savedOptOut = process.env.ALTIMATE_TELEMETRY_DISABLED - const savedLegacyOptOut = process.env.OPENCODE_DISABLE_TELEMETRY - const savedCliOptOut = process.env.ALTIMATE_CLI_DISABLE_TELEMETRY - process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = - "InstrumentationKey=test;IngestionEndpoint=https://ingest.example.invalid/" - delete process.env.ALTIMATE_TELEMETRY_DISABLED - delete process.env.OPENCODE_DISABLE_TELEMETRY - delete process.env.ALTIMATE_CLI_DISABLE_TELEMETRY +{ let recovered = false let orgLoads = 0 const account = Layer.mock(Account.Service)({ @@ -747,61 +737,63 @@ test("telemetry sends held events after an organization config fetch recovers", }), token: () => Effect.succeed(Option.none()), }) - const events: string[] = [] - await Telemetry.shutdown() - const fetchSpy = spyOn(globalThis, "fetch").mockImplementation(Object.assign(async (url: Parameters[0], request?: Parameters[1]) => { - if (url !== "https://ingest.example.invalid/v2/track") throw new Error("Unexpected telemetry request") - for (const envelope of JSON.parse(String(request?.body))) events.push(envelope.data.baseData.name) - return new Response(null, { status: 204 }) - }, { preconnect: fetch.preconnect })) - // Exercise the real per-instance config cache with only its account service replaced. - const context = { directory: directory.path, worktree: directory.path } as InstanceContext - const program = Config.Service.use((service) => Effect.promise(async () => { - const config = spyOn(Config, "get").mockImplementation((retry?: boolean) => - Effect.runPromise(provideCurrentInstance( - service.get(retry), - context, - )), - ) - try { - const track = () => Telemetry.track({ - type: "startup_ready", timestamp: Date.now(), session_id: "", - command: "run", surface: "run", duration_ms: 1, fresh_install: false, - }) - track() - await Telemetry.init() - track() - await Telemetry.refreshIdentity() - await Telemetry.flush() - const telemetryCalls = fetchSpy.mock.calls.filter(([url]) => /\/(v2\/track|users\/me)$/.test(String(url))) - expect(telemetryCalls).toEqual([]) - expect(orgLoads).toBe(1) - - recovered = true - await Telemetry.init() - await Telemetry.flush() - expect(events).toEqual(["startup_ready", "startup_ready"]) - expect(orgLoads).toBe(2) - } finally { - await Telemetry.shutdown() - config.mockRestore() - } - })) - try { - await Effect.runPromise(program.pipe(Effect.scoped, Effect.provide(configLayer({ account })))) - } finally { - fetchSpy.mockRestore() - if (savedSink === undefined) delete process.env.APPLICATIONINSIGHTS_CONNECTION_STRING - else process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = savedSink - if (savedOptOut === undefined) delete process.env.ALTIMATE_TELEMETRY_DISABLED - else process.env.ALTIMATE_TELEMETRY_DISABLED = savedOptOut - if (savedLegacyOptOut === undefined) delete process.env.OPENCODE_DISABLE_TELEMETRY - else process.env.OPENCODE_DISABLE_TELEMETRY = savedLegacyOptOut - if (savedCliOptOut === undefined) delete process.env.ALTIMATE_CLI_DISABLE_TELEMETRY - else process.env.ALTIMATE_CLI_DISABLE_TELEMETRY = savedCliOptOut - await directory[Symbol.asyncDispose]() - } -}) + configIt({ account }).instance("telemetry sends held events after an organization config fetch recovers", () => + Effect.gen(function* () { + const context = (yield* InstanceRef)! + const service = yield* Config.Service + yield* withProcessEnvs( + { + APPLICATIONINSIGHTS_CONNECTION_STRING: "InstrumentationKey=test;IngestionEndpoint=https://ingest.example.invalid/", + ALTIMATE_TELEMETRY_DISABLED: undefined, + ALTIMATE_CLI_DISABLE_TELEMETRY: undefined, + OPENCODE_DISABLE_TELEMETRY: undefined, + }, + Effect.promise(async () => { + const events: string[] = [] + await Telemetry.shutdown() + Telemetry.setConfigDirectory(context.directory) + const fetchSpy = spyOn(globalThis, "fetch").mockImplementation(Object.assign( + async (url: Parameters[0], request?: Parameters[1]) => { + if (url !== "https://ingest.example.invalid/v2/track") throw new Error("Unexpected telemetry request") + for (const envelope of JSON.parse(String(request?.body))) events.push(envelope.data.baseData.name) + return new Response(null, { status: 204 }) + }, + { preconnect: fetch.preconnect }, + )) + // Bridge the Promise facade to the same scoped service for each telemetry init. + const config = spyOn(Config, "get").mockImplementation((retry?: boolean) => + Effect.runPromise(provideCurrentInstance(service.get(retry), context)), + ) + try { + const track = () => Telemetry.track({ + type: "startup_ready", timestamp: Date.now(), session_id: "", + command: "run", surface: "run", duration_ms: 1, fresh_install: false, + }) + track() + await Telemetry.init() + track() + await Telemetry.refreshIdentity() + await Telemetry.flush() + const telemetryCalls = fetchSpy.mock.calls.filter(([url]) => /\/(v2\/track|users\/me)$/.test(String(url))) + expect(telemetryCalls).toEqual([]) + expect(orgLoads).toBe(1) + + recovered = true + await Telemetry.init() + await Telemetry.flush() + expect(events).toEqual(["startup_ready", "startup_ready"]) + expect(orgLoads).toBe(2) + } finally { + await Telemetry.shutdown() + Telemetry.setConfigDirectory(undefined) + config.mockRestore() + fetchSpy.mockRestore() + } + }), + ) + }), + ) +} { let loads = 0 From 4fcf5c063b3a134bd5996eca6ffa8c4b0eefc690 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Fri, 20 Nov 2026 23:37:54 -0800 Subject: [PATCH 22/63] docs: clarify lifetime of retained telemetry batches --- packages/opencode/src/altimate/telemetry/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index dbd97aa7a1..31943e658a 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -3055,6 +3055,7 @@ export namespace Telemetry { } catch { // altimate_change — only process exit drops unsent retries. A project handoff // can retain them for the same scope without extending the transport deadline. + // They can retry when that scope is active again. Process exit clears any still queued. if (shuttingDown && !retainPendingOnShutdown) return // Re-add events that haven't been retried yet to avoid data loss const retriable = events.filter((e) => !sent.has(e) && !(e as any)._retried) From 0abc0bf078dfdba90edef77bf2b0dc9cae4f4251 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 02:28:24 -0800 Subject: [PATCH 23/63] refactor: replace per-project telemetry scopes with one process gate - Drop scoped buffers, scope-switch shutdown and handoffs; keep main's lifecycle. - One gate: pending holds events, enabled sends, disabled drops for the rest of the process. - Unreadable config holds events and retries at most every 30 s; exit while unresolved sends nothing. - Revert the auth store and global config tracking the gate does not need. Co-Authored-By: Claude Opus 5.5 --- docs/docs/reference/telemetry.md | 2 +- .../opencode/src/altimate/debug/collect.ts | 2 +- .../opencode/src/altimate/plugin/altimate.ts | 33 ++- .../src/altimate/telemetry/config-state.ts | 22 +- .../opencode/src/altimate/telemetry/index.ts | 243 +++++++----------- packages/opencode/src/auth/index.ts | 48 +--- packages/opencode/src/config/config.ts | 132 ++-------- packages/opencode/src/session/prompt.ts | 2 +- .../test/altimate/telemetry/opt-out.test.ts | 241 ++++++----------- packages/opencode/test/config/config.test.ts | 118 +-------- packages/opencode/test/preload.ts | 6 + .../test/upstream/altimate-features.test.ts | 2 +- 12 files changed, 253 insertions(+), 598 deletions(-) diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index 6e75de17d5..32ea12c636 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -184,7 +184,7 @@ export ALTIMATE_TELEMETRY_DISABLED=true `ALTIMATE_CLI_DISABLE_TELEMETRY` and its older spelling `OPENCODE_DISABLE_TELEMETRY` are also supported. Each variable accepts `1` or `true` (case-insensitive). -When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. If startup cannot determine the config setting, it suppresses telemetry. This includes startup before a configured remote source that could set the flag has been loaded. +When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. Until the CLI can read the setting (for example at startup, before the project config or a configured remote source that could set the flag has loaded), it sends nothing; see [Privacy](#privacy). Once a process reads the setting as disabled, that process sends nothing more, even for another project it serves. ### Test runs are excluded diff --git a/packages/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index 95ed707797..529be13089 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -98,7 +98,7 @@ async function telemetryFacts(network: boolean): Promise { if (!network) return { enabled: false, checked: false, reason: "not started with --no-network" } try { await Telemetry.init() - return Telemetry.isEnabled() ? { enabled: true } : { enabled: false, reason: "disabled in config" } + return Telemetry.isEnabled() ? { enabled: true } : { enabled: false, reason: "disabled in config, or config not readable" } } catch { return { enabled: false, checked: false, reason: "could not be determined" } } diff --git a/packages/opencode/src/altimate/plugin/altimate.ts b/packages/opencode/src/altimate/plugin/altimate.ts index 40f4ae3b60..650b6c43be 100644 --- a/packages/opencode/src/altimate/plugin/altimate.ts +++ b/packages/opencode/src/altimate/plugin/altimate.ts @@ -1,7 +1,6 @@ import type { Hooks, PluginInput } from "@opencode-ai/plugin" import { createServer } from "http" import { randomBytes } from "crypto" -import path from "path" import open from "open" import { AltimateApi } from "../api/client" // altimate_change — onboarding telemetry for the gateway sign-in funnel @@ -79,20 +78,30 @@ const log = Log.create({ service: "altimate-plugin" }) /** `directory`: the project the command acts on, whose config may opt out; the process's working * directory when the command has none (`auth login`). */ export async function buildCliContext(machineIdPath?: string, directory?: string): Promise { - // altimate_change start — apply the same opt-out to the auth URL’s machine ID + // altimate_change start — honour both telemetry opt-out gates, mirroring + // telemetry/index.ts::doInit: + // 1. the opt-out env vars (TelemetryConfig.disablingEnvironmentVariable) + // 2. config.telemetry.disabled; a config that cannot be fully resolved omits the id let disabled = Boolean(TelemetryConfig.disablingEnvironmentVariable()) if (!disabled) { - const instance = TelemetryConfig.instanceDirectory() - const differentProject = instance && directory && path.resolve(directory) !== instance - const state = differentProject - ? undefined - : await TelemetryConfig.loadedState().catch(() => instance ? "unreadable" : undefined) - if (state) { - disabled = state !== "enabled" + // Server routes run inside Instance.provide(), so the full config resolves during an + // ordinary browser authorize(). + const loaded = await TelemetryConfig.loadedState().catch(() => undefined) + if (loaded) { + disabled = loaded !== "enabled" + } else if (TelemetryConfig.instanceDirectory()) { + disabled = true } else { - const local = await TelemetryConfig.disabledState(directory) - if (local === "enabled") await Telemetry.init().catch(() => {}) - disabled = local !== "enabled" || !Telemetry.isEnabled() + // The paths that skip instance bootstrap: `altimate auth login ` and the + // create-and-link hand-off of `altimate-code link`. Read `telemetry.disabled` + // from the config files directly: an opt-out there, or files that cannot be + // read (an opt-out may be behind them), omit the id. Only a config that + // readably leaves telemetry on defers to the telemetry module's own state + // (no sink, test runner). + const state = await TelemetryConfig.disabledState(directory) + if (state === "enabled") await Telemetry.init().catch(() => {}) + disabled = state !== "enabled" || !Telemetry.isEnabled() + log.info("cli_context: no instance, read the opt-out from the files", { state, enabled: !disabled }) } } let machineId = "" diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 33f956e10c..9aa446de46 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -65,33 +65,33 @@ async function hasWellKnownAuth(): Promise { throw error } } - const parsed = Auth.parseStore(contents) - if (!parsed || parsed.incomplete) throw new Error("Unresolved auth store") - return parsed.hasWellKnown + // Unparseable: a well-known entry may be behind it. `Config` would load without its remote config. + const parsed: unknown = JSON.parse(contents) + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Unreadable auth store") + return Object.values(parsed).some( + (entry) => entry && typeof entry === "object" && (entry as { type?: unknown }).type === "wellknown", + ) } export function instanceDirectory(): string | undefined { return Effect.runSync(attach(InstanceRef))?.directory } +/** The opt-out from the full config; throws where `Config` cannot load (outside an Instance). */ export async function loadedState(retry = false): Promise { const config = await Config.get(retry) if (Config.telemetryConfigUnresolved(config)) return "unreadable" - // Auth.all() can return an empty store when its read or parse fails. - try { - await hasWellKnownAuth() - } catch { - return "unreadable" - } + // Auth.all() returns an empty store when its read or parse fails, hiding well-known remote config. + await hasWellKnownAuth() return config.telemetry?.disabled ? "disabled" : "enabled" } +/** The opt-out as the caller can best read it: the full config inside an Instance (a failed load can + * hide remote settings, so it is `unreadable`), the files on disk for commands that have none yet. */ export async function resolve(directory?: string, retry = false): Promise { try { return await loadedState(retry) } catch { - // A failed full load can hide remote settings. The local probe is only for - // commands that have no instance to load yet. return instanceDirectory() ? "unreadable" : disabledState(directory) } } diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 31943e658a..cc0b4f22cb 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -15,7 +15,6 @@ import fs from "fs" import path from "path" import os from "os" import { fileLog } from "@/altimate/util/file-log" -import { Filesystem } from "@/util/filesystem" const log = Log.create({ service: "telemetry" }) @@ -217,14 +216,6 @@ const PATH_RULES = { } // altimate_change end -function telemetryWorkingDirectory(): string | undefined { - try { - return process.cwd() - } catch { - return undefined - } -} - export namespace Telemetry { const FLUSH_INTERVAL_MS = 5_000 const MAX_BUFFER_SIZE = 200 @@ -2295,9 +2286,7 @@ export namespace Telemetry { } let enabled = false - let buffer: { event: Event; scope?: string | null; held?: boolean }[] = [] - let configScope: string | undefined - let reinitScope: string | undefined + let buffer: Event[] = [] let flushTimer: ReturnType | undefined // altimate_change — who the machine is signed in as (backend user uuid + tenant), for the // funnel join with web events. Resolved off the stored credential in doInit(); see identity.ts. @@ -2318,15 +2307,32 @@ export namespace Telemetry { // once by the stamp comparison; the backoff only throttles retries of the unchanged one. const IDENTITY_RETRY_MS = 60_000 let identityRetryAt = 0 // 0: no retry pending + // altimate_change start — process-wide opt-out gate. Events are tracked while the opt-out is + // unknown (CLI startup, before config can be read) but nothing leaves until an init resolves the + // config to enabled. An opt-out (env or config) makes it `disabled` for the rest of the process, + // so a later init never sends what an earlier one refused. Unlike `enabled`, it survives the + // per-session shutdown; it is never reset outside tests. + let gate: "pending" | "enabled" | "disabled" = "pending" + // While the config is unreadable, re-resolve it at most this often (each try reloads the config). + const CONFIG_RETRY_MS = 30_000 + let configRetry: { at: number; instance: boolean } | undefined + /** Test seam: forget the process-wide opt-out decision and the events held for it. */ + export function resetGateForTest() { + gate = "pending" + configRetry = undefined + buffer = [] + droppedEvents = 0 + } + /** Test seam: end the unreadable-config retry backoff so the next init() re-resolves. */ + export function retryConfigNowForTest() { + if (configRetry) configRetry.at = 0 + } + // altimate_change end // altimate_change — the project the command will run in, for reading the config without an // Instance: the CLI initialises telemetry before a command changes into its `--dir` or project. let configDirectory: string | undefined export function setConfigDirectory(directory: string | undefined) { - try { - configDirectory = directory === undefined ? undefined : Filesystem.resolve(directory) - } catch { - configDirectory = directory === undefined ? undefined : path.resolve(directory) - } + configDirectory = directory } let machineId = "" let sessionId = "" @@ -2339,11 +2345,8 @@ export namespace Telemetry { let nextTurn = 0 // altimate_change end let appInsights: AppInsightsConfig | undefined - // Remember evicted scopes without letting overflow accounting grow unbounded. - const droppedEvents = new Map() + let droppedEvents = 0 let initPromise: Promise | undefined - // altimate_change — unresolved config holds events for the next init call. - let configUnresolved = false let initDone = false // altimate_change — shutdown needs to cancel a flush already in flight, not just stop waiting // for it: `flush()` chains through inFlightFlush, so a timed-out drain still had its final @@ -2352,7 +2355,6 @@ export namespace Telemetry { // cleared and ship them under the NEXT lifecycle. let activeFlushAbort: AbortController | undefined let shuttingDown = false - let retainPendingOnShutdown = false // altimate_change — in-flight shutdown, declared with the rest of the module state so init() // above can consult it. See shutdown() for why concurrent shutdowns must be serialized. let shutdownPromise: Promise | undefined @@ -2501,17 +2503,9 @@ export namespace Telemetry { const DEFAULT_CONNECTION_STRING = "InstrumentationKey=5095f5e6-477e-4262-b7ae-2118de18550d;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=6564474f-329b-4b7d-849e-e70cb4181294" - function resolveScope(processWide = false) { - const instance = TelemetryConfig.instanceDirectory() - const directory = instance ?? (processWide ? configScope : undefined) ?? configDirectory - return { instance, directory, scope: directory ?? telemetryWorkingDirectory() } - } - // Deduplicates concurrent calls: non-awaited init() in middleware/worker // won't race with await init() in session prompt. export function init(): Promise { - const { instance, scope } = resolveScope() - if (scope === undefined) return Promise.resolve() // altimate_change start — never re-init across an in-flight shutdown. // // session/prompt.ts init()s at the start of every session loop and shutdown()s at the end, so a @@ -2526,15 +2520,12 @@ export namespace Telemetry { // Chaining onto shutdownPromise keeps the generations separate: callers arriving mid-shutdown // wait for the new init rather than joining the dying one. if (shutdownPromise) { - if (reinitPromise && reinitScope !== scope) return reinitPromise.then(() => init()) if (!reinitPromise) { - reinitScope = scope reinitPromise = shutdownPromise .catch(() => {}) - .then(() => doInit(scope)) + .then(doInit) .finally(() => { reinitPromise = undefined - reinitScope = undefined }) // Publish it as initPromise too. Without this, a caller arriving after the shutdown had // settled — but before this chained doInit() finished — saw an empty initPromise and @@ -2550,69 +2541,44 @@ export namespace Telemetry { } return reinitPromise } - if (initPromise && configScope !== scope) { - return shutdown({ preservePending: true, timeoutMs: EXIT_FLUSH_BUDGET_MS }).then(() => init()) - } - if (!initDone && initPromise && instance) { - // A session can join the middleware init while its local probe is still running. - // Retry once from the session's context when the probe could not resolve config. - const pending = initPromise - return pending.then(() => { - if (initPromise !== pending) return initPromise - if (!shutdownPromise && configUnresolved) return init() - }) - } - if (initDone && configUnresolved) { - initPromise = undefined - initDone = false + // While the config stays unreadable, retry at most every CONFIG_RETRY_MS. The first init inside + // an Instance is not throttled by an earlier one outside it: it reads the full config, which the + // instance-less probe could not. + if (!initPromise && gate === "pending" && configRetry && Date.now() < configRetry.at) { + if (configRetry.instance || !TelemetryConfig.instanceDirectory()) return Promise.resolve() } - return (initPromise ??= doInit(scope)) + return (initPromise ??= doInit()) // altimate_change end } - function clearScope(scope: string | undefined) { - buffer = buffer.filter((entry) => entry.scope !== scope) - droppedEvents.delete(scope) - } - - async function doInit(scope: string) { - // Events tracked before the CLI selects its config directory belong to the - // first scope it resolves. Later scopes must resolve their own opt-out. - for (const entry of buffer) { - if (entry.scope === undefined) entry.scope = scope - } - const earlyDrops = droppedEvents.get(undefined) - if (earlyDrops) { - const scopedDrops = droppedEvents.get(scope) - droppedEvents.delete(undefined) - droppedEvents.set(scope, { count: (scopedDrops?.count ?? 0) + earlyDrops.count, held: scopedDrops?.held || earlyDrops.held }) - } - const retry = (configUnresolved && configScope === scope) || - droppedEvents.get(scope)?.held || - buffer.some((entry) => entry.scope === scope && entry.held) - configScope = scope - configUnresolved = false + async function doInit() { + // altimate_change — an unreadable config leaves this init unfinished, so the next init() retries. + let unresolved = false try { - // altimate_change start — hold bounded startup events until the opt-out is resolved. - if (TelemetryConfig.disablingEnvironmentVariable()) { + // altimate_change start — resolve the opt-out before anything can be sent. Env vars first, + // then the config: the full one inside an Instance, the files on disk outside one. + if (gate === "disabled" || TelemetryConfig.disablingEnvironmentVariable()) { + gate = "disabled" buffer = [] - droppedEvents.clear() + droppedEvents = 0 return } - const state = await TelemetryConfig.resolve(scope, retry) - if (state === "unreadable") { - configUnresolved = true - const drops = droppedEvents.get(scope) - if (drops) drops.held = true - for (const entry of buffer) { - if (entry.scope === scope) entry.held = true - } + const instance = Boolean(TelemetryConfig.instanceDirectory()) + const state = await TelemetryConfig.resolve(configDirectory, configRetry !== undefined) + if (state === "disabled") { + gate = "disabled" + buffer = [] + droppedEvents = 0 return } - if (state === "disabled") { - clearScope(scope) + if (state === "unreadable") { + // An opted-out user may be behind it: hold the buffer (capped) and send nothing. + unresolved = true + configRetry = { at: Date.now() + CONFIG_RETRY_MS, instance } return } + gate = "enabled" + configRetry = undefined // altimate_change end // App Insights: env var overrides default (for dev/testing), otherwise use the baked-in key. // The baked-in key is refused under a test runner so suites never ship to the production @@ -2623,13 +2589,13 @@ export namespace Telemetry { // and active-machine metric by ~33%. const explicit = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING if (!explicit && isAutomatedRun()) { - clearScope(scope) + buffer = [] return } const connectionString = explicit ?? DEFAULT_CONNECTION_STRING const cfg = parseConnectionString(connectionString) if (!cfg) { - clearScope(scope) + buffer = [] return } appInsights = cfg @@ -2656,14 +2622,15 @@ export namespace Telemetry { // altimate_change start — first-run health: drain anchor events that were tracked before init // finished (first_launch always is) instead of leaving them to the 5 s interval a startup freeze // would block. The stall watcher starts in `finally`, telemetry or not. - if (droppedEvents.has(scope) || buffer.some(({ event, scope: owner }) => - owner === scope && (retry || ANCHOR_EVENTS.has(event.type)), - )) void Telemetry.flush().catch(() => {}) + if (buffer.some((event) => ANCHOR_EVENTS.has(event.type))) void Telemetry.flush().catch(() => {}) // altimate_change end } catch { - clearScope(scope) + buffer = [] } finally { - initDone = true + // altimate_change start — unresolved: stay pre-init so events keep buffering and init() retries + if (unresolved) initPromise = undefined + initDone = !unresolved + // altimate_change end // altimate_change start — the stall watcher also writes each stall to opencode.log, which `debug bundle` // reads, so it runs whether or not telemetry is on; with telemetry off its events are dropped by `track`. startLoopMonitor() @@ -2721,9 +2688,10 @@ export namespace Telemetry { const generation = ++identityGeneration identityStamp = TelemetryIdentity.credentialStamp() identityRetryAt = 0 + // altimate_change — no account lookup (a backend request) once this lifecycle has ended return TelemetryIdentity.resolveWithOutcome({ ...opts, - canSend: () => generation === identityGeneration && !shutdownPromise, + canSend: () => generation === identityGeneration && gate === "enabled" && !shutdownPromise, }) .then(({ identity: resolved, outcome }) => { if (generation !== identityGeneration) return @@ -2741,11 +2709,8 @@ export namespace Telemetry { * Does nothing while telemetry is disabled. */ export async function refreshIdentity(): Promise { // Opted out (or not initialised): no lookup; an enabled init resolves from the stored credential. - if (!isEnabled() || shutdownPromise) return - // A refresh queued behind a flush belongs to the init that started it. - const startedUnder = initPromise + if (!enabled) return await flush() - if (!isEnabled() || shutdownPromise || initPromise !== startedUnder) return identity = undefined await resolveIdentity({ refresh: true }) } @@ -2777,10 +2742,9 @@ export namespace Telemetry { return { sessionId, projectId } } - /** Returns true once telemetry is enabled for the calling project's config. */ + /** Returns true only after init() has completed and telemetry is enabled. */ export function isEnabled(): boolean { - if (!initDone || !enabled) return false - return configScope === resolveScope().scope + return initDone && enabled } // altimate_change start — first-run health instrumentation (see the startup_ready, event_loop_stall @@ -2932,12 +2896,10 @@ export namespace Telemetry { // altimate_change end export function track(event: Event) { - // Membership is decided when events are tracked, never by whichever - // project happens to initialize before the next flush. - const caller = resolveScope(event.type === "event_loop_stall") - // Keep events from an inaccessible directory unassigned until exit. - const scope = caller.directory ?? (caller.scope === undefined ? null : configScope === undefined ? undefined : caller.scope) - if (scope === configScope && initDone && !enabled && !configUnresolved) return + // Before init completes: buffer (flushed once init enables, or cleared if disabled). + // After init completed and disabled telemetry: drop silently. + // altimate_change — opted out (env or config): drop. Unresolved config keeps initDone false, so it buffers. + if (gate === "disabled" || (initDone && !enabled)) return // altimate_change start — stamp the client trace of the turn the event's own session is // running, now: the event is serialised at flush time, when that turn may be over. Only an // explicit per-event `session_id` is used — the process-global session can be another one. @@ -2950,24 +2912,16 @@ export namespace Telemetry { // loop's rows, tool rows and memory rows carry the turn's; workspace rows carry their own) or it // carries none. A process-wide or per-session fallback kept attributing cancelled turns' rows to // their replacements. - buffer.push({ event, scope, held: scope === configScope && configUnresolved }) + buffer.push(event) if (buffer.length > MAX_BUFFER_SIZE) { - const dropped = buffer.shift()! - const owner = dropped.scope - if (owner !== null) { - const previous = droppedEvents.get(owner) - droppedEvents.delete(owner) - droppedEvents.set(owner, { count: (previous?.count ?? 0) + 1, held: previous?.held || dropped.held }) - if (droppedEvents.size > MAX_BUFFER_SIZE) { - droppedEvents.delete(droppedEvents.keys().next().value) - } - } + buffer.shift() + droppedEvents++ } // altimate_change start — anchor events flush immediately. A frozen-then-killed process otherwise // dies with its buffer: the 5 s interval cannot fire while the loop is blocked, and the stall // report itself would be the first thing lost. if (event.type === "first_launch" && !event.is_upgrade) freshInstall = true - if (scope === configScope && initDone && enabled && ANCHOR_EVENTS.has(event.type)) void Telemetry.flush().catch(() => {}) + if (initDone && enabled && ANCHOR_EVENTS.has(event.type)) void Telemetry.flush().catch(() => {}) // altimate_change end } @@ -2998,7 +2952,7 @@ export namespace Telemetry { // change on disk and re-resolve (cheap: two stats, and the cache answers unless the key changed). const who = identity const mid = machineId - if (enabled && !shuttingDown) { + if (enabled) { const stamp = TelemetryIdentity.credentialStamp() const retryDue = identityRetryAt !== 0 && Date.now() >= identityRetryAt if (stamp !== identityStamp || retryDue) { @@ -3007,24 +2961,21 @@ export namespace Telemetry { } } // altimate_change end - if (!enabled || !appInsights) return + // altimate_change — nothing leaves until an init resolved the opt-out to enabled + if (gate !== "enabled" || !enabled || buffer.length === 0 || !appInsights) return - const scope = configScope - const events = buffer.filter((entry) => entry.scope === scope).map(({ event }) => event) - const dropped = droppedEvents.get(scope)?.count - if (events.length === 0 && !dropped) return - buffer = buffer.filter((entry) => entry.scope !== scope) + const events = buffer.splice(0, buffer.length) - droppedEvents.delete(scope) - if (dropped) { + if (droppedEvents > 0) { events.push({ type: "error", timestamp: Date.now(), session_id: sessionId, error_name: "TelemetryBufferOverflow", - error_message: `${dropped} events dropped due to buffer overflow`, + error_message: `${droppedEvents} events dropped due to buffer overflow`, context: "telemetry", } as Event) + droppedEvents = 0 } const controller = new AbortController() @@ -3053,10 +3004,10 @@ export namespace Telemetry { } } } catch { - // altimate_change — only process exit drops unsent retries. A project handoff - // can retain them for the same scope without extending the transport deadline. - // They can retry when that scope is active again. Process exit clears any still queued. - if (shuttingDown && !retainPendingOnShutdown) return + // altimate_change — no write-back during shutdown. The buffer is cleared a few lines later + // regardless, so re-inserting here does not save these events; it only leaves them to be + // shipped by whatever lifecycle comes next, under a different launch id. + if (shuttingDown) return // Re-add events that haven't been retried yet to avoid data loss const retriable = events.filter((e) => !sent.has(e) && !(e as any)._retried) // altimate_change — a batch never attempted (an earlier one failed) keeps its retry. @@ -3064,7 +3015,7 @@ export namespace Telemetry { if (attempted.has(e)) (e as any)._retried = true } const space = Math.max(0, MAX_BUFFER_SIZE - buffer.length) - buffer.unshift(...retriable.slice(0, space).map((event) => ({ event, scope }))) + buffer.unshift(...retriable.slice(0, space)) } finally { clearTimeout(timeout) if (activeFlushAbort === controller) activeFlushAbort = undefined @@ -3099,7 +3050,7 @@ export namespace Telemetry { // `timeoutMs` bounds the flush from the inside. Racing shutdown() against an external timer // does NOT cancel it: the losing promise keeps running and resets module state after the // caller has already moved on. Exit paths pass a budget so the fetch itself is aborted. - export async function shutdown(opts?: { timeoutMs?: number; preservePending?: boolean }) { + export async function shutdown(opts?: { timeoutMs?: number }) { if (shutdownPromise) { // An earlier caller is mid-flush, possibly on the default 10s budget. Returning its promise // unchanged would silently ignore this caller's deadline and make the exit path wait past @@ -3117,13 +3068,13 @@ export namespace Telemetry { if (timer) clearTimeout(timer) return } - shutdownPromise = doShutdown(opts?.timeoutMs, opts?.preservePending).finally(() => { + shutdownPromise = doShutdown(opts?.timeoutMs).finally(() => { shutdownPromise = undefined }) return shutdownPromise } - async function doShutdown(timeoutMs?: number, preservePending?: boolean) { + async function doShutdown(timeoutMs?: number) { const initPromiseAtShutdown = initPromise // Wait for init to complete so we know whether telemetry is enabled // and have a valid endpoint to flush to. init() is fire-and-forget @@ -3146,7 +3097,6 @@ export namespace Telemetry { // in mid-request is not abandoned and cannot write back into a buffer we are about to clear. const deadline = Date.now() + (timeoutMs ?? REQUEST_TIMEOUT_MS) shuttingDown = true - retainPendingOnShutdown = Boolean(preservePending) if (inFlightFlush) { // Bounded: a flush already in flight uses the DEFAULT request timeout, so awaiting it // unbounded could burn 10s before the bounded flush below even starts — well past the 5s @@ -3175,23 +3125,20 @@ export namespace Telemetry { await inFlightFlush.catch(() => {}) } } - // Spend the remaining budget on a final flush if there is time. At process exit, reserve - // a small floor for the last attempt because there is no later lifecycle to retry it. - const remaining = deadline - Date.now() - if (!preservePending || remaining >= 250) await flush(Math.max(250, remaining)) + // Whatever the drain left of the shared deadline, never below a floor that lets the request + // actually be made. + await flush(Math.max(250, deadline - Date.now())) inFlightFlush = undefined shuttingDown = false - retainPendingOnShutdown = false enabled = false appInsights = undefined - if (!preservePending) { - configUnresolved = false - configScope = undefined + // altimate_change start — while the opt-out is unresolved nothing was flushed: keep the events + // for a later init in this process to send or drop. At process exit they go with the process. + if (gate !== "pending") { buffer = [] - droppedEvents.clear() - } else if (!configUnresolved) { - configScope = undefined + droppedEvents = 0 } + // altimate_change end sessionId = "" projectId = "" machineId = "" diff --git a/packages/opencode/src/auth/index.ts b/packages/opencode/src/auth/index.ts index ef7a2a8946..c06d17254d 100644 --- a/packages/opencode/src/auth/index.ts +++ b/packages/opencode/src/auth/index.ts @@ -67,31 +67,6 @@ export interface Interface { export class Service extends Context.Service()("@opencode/Auth.cli") {} // altimate_change end -// altimate_change start — Config needs to know when a tolerant auth read may hide remote config. -const incompleteStores = new WeakSet>() - -export function configSourcesUnresolved(store: Record): boolean { - return incompleteStores.has(store) -} - -// Both the normal loader and the local telemetry probe need the same validation. -const decodeWellKnown = Schema.decodeUnknownOption(WellKnown) -export function parseStore(text: string) { - try { - const parsed: unknown = JSON.parse(text) - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return - const entries = parsed as Record - const wellKnown = Object.values(entries).filter( - (entry) => entry && typeof entry === "object" && "type" in entry && entry.type === "wellknown", - ) - const incomplete = wellKnown.some((entry) => decodeWellKnown(entry)._tag === "None") - return { entries, hasWellKnown: wellKnown.length > 0, incomplete } - } catch { - return - } -} -// altimate_change end - export const layer = Layer.effect( Service, Effect.gen(function* () { @@ -99,25 +74,14 @@ export const layer = Layer.effect( const decode = Schema.decodeUnknownOption(Info) const all = Effect.fn("Auth.all")(function* () { - // altimate_change start — preserve unreadable stores and invalid well-known entries for Config. - const inline = process.env.OPENCODE_AUTH_CONTENT - const provided = inline ? parseStore(inline) : undefined - if (provided) { - const store = provided.entries as Record - if (provided.incomplete) incompleteStores.add(store) - return store + if (process.env.OPENCODE_AUTH_CONTENT) { + try { + return JSON.parse(process.env.OPENCODE_AUTH_CONTENT) + } catch (err) {} } - let incomplete = Boolean(inline) - const text = yield* fsys.readFileStringSafe(file).pipe(Effect.catch(() => { - incomplete = true - return Effect.succeed(undefined) - })) - const disk = text === undefined ? undefined : parseStore(text) - const store = Record.filterMap(disk?.entries ?? {}, (value) => Result.fromOption(decode(value), () => undefined)) - if (incomplete || (text !== undefined && (!disk || disk.incomplete))) incompleteStores.add(store) - return store - // altimate_change end + const data = (yield* fsys.readJson(file).pipe(Effect.orElseSucceed(() => ({})))) as Record + return Record.filterMap(data, (value) => Result.fromOption(decode(value), () => undefined)) }) const get = Effect.fn("Auth.get")(function* (providerID: string) { diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index fe4378be12..54ddbd449e 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -2,6 +2,7 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { httpClient } from "@opencode-ai/core/effect/layer-node-platform" import { serviceUse } from "@opencode-ai/core/effect/service-use" import path from "path" +import { pathToFileURL } from "url" import os from "os" import { mergeDeep } from "remeda" // altimate_change - use fork-branded global paths so config loads from ~/.config/altimate-code @@ -21,7 +22,7 @@ import { isRecord } from "@/util/record" import type { ConsoleState } from "@opencode-ai/core/v1/config/console-state" import { FSUtil } from "@opencode-ai/core/fs-util" import { InstanceState } from "@/effect/instance-state" -import { Cause, Context, Duration, Effect, Exit, Fiber, Layer, Option, Schema } from "effect" // altimate_change — classify retryable remote failures +import { Context, Duration, Effect, Exit, Fiber, Layer, Option, Schema } from "effect" // altimate_change start — upstream_fix: invalidate Config's per-instance cache after writes import { ScopedCache } from "effect" // altimate_change end @@ -47,14 +48,12 @@ import { ConfigVariable } from "./variable" import { Npm } from "@opencode-ai/core/npm" import { withTransientReadRetry } from "@/util/effect-http-client" // altimate_change start — makeRuntime for the restored Promise wrappers (see bottom of file) -import { attach, makeRuntime } from "@/effect/run-service" -import { InstanceRef } from "@/effect/instance-ref" +import { makeRuntime } from "@/effect/run-service" // altimate_change end -// altimate_change start — defer telemetry when any config layer was unavailable -type UnresolvedTelemetrySources = { auth: boolean; global: boolean; organization: boolean } -const configsWithUnresolvedTelemetry = new WeakMap() - +// altimate_change start — loaded configs whose organization remote config, which may set +// `telemetry.disabled`, could not be read: the opt-out is unknown. +const configsWithUnresolvedTelemetry = new WeakSet() export function telemetryConfigUnresolved(config: Info): boolean { return configsWithUnresolvedTelemetry.has(config) } @@ -271,7 +270,7 @@ type State = { } export interface Interface { - readonly get: (retryTelemetry?: boolean) => Effect.Effect // altimate_change — retry partial telemetry config + readonly get: (retryTelemetry?: boolean) => Effect.Effect // altimate_change — reload an unresolved opt-out readonly getGlobal: () => Effect.Effect readonly getConsoleState: () => Effect.Effect readonly update: (config: Info) => Effect.Effect @@ -335,13 +334,6 @@ export const layer = Layer.effect( const env = yield* Env.Service const npmSvc = yield* Npm.Service const http = yield* HttpClient.HttpClient - // altimate_change start — preserve remote failure origin without changing the public error. - const remoteLoadFailures = new WeakSet() - const recordRemoteFailure = (cause: Cause.Cause) => Effect.sync(() => { - const failure = Cause.squash(cause) - if (failure && typeof failure === "object") remoteLoadFailures.add(failure) - }) - // altimate_change end const readConfigFile = (filepath: string) => fs.readFileStringSafe(filepath).pipe(Effect.orDie) @@ -438,10 +430,7 @@ export const layer = Layer.effect( return yield* loadConfig(text, { path: filepath }, env) }) - // altimate_change — the legacy loader can return partial config after an unreadable TOML file. - const incompleteGlobals = new WeakSet() - // altimate_change — telemetry can recheck local files without migrating legacy config. - const loadGlobal = Effect.fnUntraced(function* (env?: Record, migrateLegacy = true) { + const loadGlobal = Effect.fnUntraced(function* (env?: Record) { let result: Info = {} // Seed the default global config with the schema for editor completion, but avoid writing when the user // explicitly routes config through env-provided paths or content. @@ -465,31 +454,19 @@ export const layer = Layer.effect( const legacy = path.join(Global.Path.config, "config") if (existsSync(legacy)) { - // altimate_change — a failed migration can still leave the parsed configuration usable. - let parsedLegacy = false yield* Effect.promise(() => - // altimate_change start — read again on retry so a repaired TOML file replaces a failed load. - fsNode.readFile(legacy, "utf8") - .then(async (text) => { - const legacyConfig = Bun.TOML.parse(text) as Omit & { provider?: string } - const { provider, model, ...rest } = legacyConfig - // altimate_change end + import(pathToFileURL(legacy).href, { with: { type: "toml" } }) + .then(async (mod) => { + const { provider, model, ...rest } = mod.default if (provider && model) result.model = `${provider}/${model}` // altimate_change start — altimate config schema URL result["$schema"] = "https://altimate.ai/config.json" // altimate_change end result = mergeConfig(result, rest) - // altimate_change — only read and parse failures leave the config unresolved. - parsedLegacy = true - if (!migrateLegacy) return await fsNode.writeFile(path.join(Global.Path.config, "config.json"), JSON.stringify(result, null, 2)) await fsNode.unlink(legacy) }) - // altimate_change start — preserve the failure for the telemetry gate - .catch(() => { - if (!parsedLegacy) incompleteGlobals.add(result) - }), - // altimate_change end + .catch(() => {}), ) } @@ -501,13 +478,7 @@ export const layer = Layer.effect( Effect.tapError((error) => Effect.logError("failed to load global config, using defaults", { error: String(error) }), ), - // altimate_change start — a global fallback can hide an opt-out - Effect.orElseSucceed((): Info => { - const fallback: Info = {} - incompleteGlobals.add(fallback) - return fallback - }), - // altimate_change end + Effect.orElseSucceed((): Info => ({})), ), Duration.infinity, ) @@ -596,10 +567,7 @@ export const layer = Layer.effect( } for (const [key, value] of Object.entries(auth)) { - // altimate_change start — classify fetch, decode, and schema failures as remote for retry backoff. - if (value.type !== "wellknown") continue - yield* Effect.gen(function* () { - // altimate_change end + if (value.type === "wellknown") { const url = key.replace(/\/+$/, "") authEnv[value.key] = value.token const wellknownURL = `${url}/.well-known/opencode` @@ -644,9 +612,7 @@ export const layer = Layer.effect( ) yield* merge(source, next, "global") yield* Effect.logDebug("loaded remote config from well-known", { url }) - // altimate_change start — retain the original error for other config consumers. - }).pipe(Effect.tapCause(recordRemoteFailure)) - // altimate_change end + } } const global = Object.keys(authEnv).length ? yield* loadGlobal(authEnv) : yield* getGlobal() @@ -725,7 +691,7 @@ export const layer = Layer.effect( yield* Effect.logDebug("loaded custom config from OPENCODE_CONFIG_CONTENT") } - // altimate_change start — preserve resolution status for the telemetry opt-out gate + // altimate_change start — an organization config that could not be read may opt out of telemetry let orgConfigUnresolved = false const activeAccount = Option.getOrUndefined( yield* accountSvc.active().pipe( @@ -766,14 +732,13 @@ export const layer = Layer.effect( } }).pipe( Effect.withSpan("Config.loadActiveOrgConfig"), - // altimate_change start — telemetry must distinguish a partial config from a successful load + // altimate_change start — mark the config unresolved for the telemetry opt-out Effect.catch((err) => { orgConfigUnresolved = true return Effect.logDebug("failed to fetch remote account config", { error: err instanceof Error ? err.message : String(err), }) }), - Effect.tapCause(recordRemoteFailure), // altimate_change end ) } @@ -947,16 +912,8 @@ export const layer = Layer.effect( } // altimate_change end - // altimate_change start — associate the status with this resolved config object - const unresolved = { - auth: Auth.configSourcesUnresolved(auth), - global: incompleteGlobals.has(global), - organization: orgConfigUnresolved, - } - if (unresolved.auth || unresolved.global || unresolved.organization) { - configsWithUnresolvedTelemetry.set(result, unresolved) - } - // altimate_change end + // altimate_change — a source that could set `telemetry.disabled` was not read + if (orgConfigUnresolved) configsWithUnresolvedTelemetry.add(result) return { config: result, @@ -989,54 +946,16 @@ export const layer = Layer.effect( }), ) - // altimate_change start — back off only for the same unresolved remote-config result. - // A refreshed cache or a repaired local config can recover on the next call. - const telemetryRetryAt = new WeakMap() - const TELEMETRY_RETRY_MS = 30_000 - function remoteRetryKey(result: Exit.Exit): object | undefined { - if (Exit.isSuccess(result)) { - return configsWithUnresolvedTelemetry.get(result.value)?.organization ? result.value : undefined - } - const failure = Cause.squash(result.cause) - if (failure && typeof failure === "object" && remoteLoadFailures.has(failure)) return failure - } - - const localTelemetrySourcesReady = Effect.fnUntraced(function* (sources: UnresolvedTelemetrySources) { - if (!sources.auth && !sources.global) return true - - // Recheck local data before invalidating the merged result. An unreadable - // local layer cannot be repaired by fetching the remote configuration again. - const auth = yield* Effect.exit(authSvc.all()) - if (Exit.isFailure(auth) || Auth.configSourcesUnresolved(auth.value)) return false - if (!sources.global) return true - - const authEnv: Record = {} - for (const value of Object.values(auth.value)) { - if (value.type === "wellknown") authEnv[value.key] = value.token - } - const global = yield* Effect.exit(loadGlobal(authEnv, false)) - return Exit.isSuccess(global) && !incompleteGlobals.has(global.value) - }) - + // altimate_change start — `retryTelemetry`: reload a config whose telemetry opt-out could not be + // resolved (or that failed to load), so a source that has recovered is read. The caller throttles. const get = Effect.fn("Config.get")(function* (retryTelemetry = false) { const read = InstanceState.use(state, (s) => s.config) if (!retryTelemetry || !(yield* InstanceState.has(state))) return yield* read const cached = yield* Effect.exit(read) - const sources = Exit.isSuccess(cached) ? configsWithUnresolvedTelemetry.get(cached.value) : undefined - if (Exit.isSuccess(cached) && (!sources || !(yield* localTelemetrySourcesReady(sources)))) return cached.value - - const remote = remoteRetryKey(cached) - if (remote && performance.now() < (telemetryRetryAt.get(remote) ?? 0)) return yield* cached - - // A failed local read can have come from the global cache. A known remote - // failure cannot, so keep a readable global cache in that case. - const reloadGlobal = Exit.isFailure(cached) ? !remote : sources?.global - if (reloadGlobal) yield* invalidateGlobal + if (Exit.isSuccess(cached) && !configsWithUnresolvedTelemetry.has(cached.value)) return cached.value + yield* invalidateGlobal yield* InstanceState.invalidate(state) - const retried = yield* Effect.exit(read) - const retryKey = remoteRetryKey(retried) - if (retryKey) telemetryRetryAt.set(retryKey, performance.now() + TELEMETRY_RETRY_MS) - return yield* retried + return yield* read }) // altimate_change end @@ -1146,9 +1065,8 @@ export const node = LayerNode.make(layer, () => [FSUtil.node, Auth.node, Account // call `await Config.get()` etc. The makeRuntime bridge's `attach()` reads WorkspaceContext + // the current fiber's InstanceRef, so these reads stay bound to the active workspace/instance. const { runPromise: runConfig } = makeRuntime(Service, defaultLayer) +// altimate_change — `retryTelemetry`: see Service.get export async function get(retryTelemetry = false) { - // Reject before building the runtime and opening its database without an instance. - if (!Effect.runSync(attach(InstanceRef))) throw new Error("InstanceRef not provided") return runConfig((svc) => svc.get(retryTelemetry)) } export async function getGlobal() { diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 8361ac3232..93187d0201 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -2796,7 +2796,7 @@ export namespace SessionPrompt { }) Telemetry.endSession(sessionID, telemetryTurn) // altimate_change — after the row, this turn only } - await Telemetry.shutdown({ preservePending: true }) + await Telemetry.shutdown() // altimate_change end // altimate_change start — resolve callbacks from this prompt generation only for (const item of orderedMessageStream(readMessageOrder())) { diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index bd6b47e9c9..096384fcb0 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -1,6 +1,6 @@ import { Database as SQLite } from "bun:sqlite" import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test" -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs" +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs" import os from "os" import path from "path" import { Database } from "@opencode-ai/core/database/database" @@ -8,7 +8,8 @@ import { Auth } from "../../../src/auth" import { Config } from "../../../src/config/config" import { Telemetry } from "../../../src/altimate/telemetry" import { TelemetryConfig } from "../../../src/altimate/telemetry/config-state" -import { TelemetryIdentity } from "../../../src/altimate/telemetry/identity" +import { Instance } from "../../../src/project/instance" +import { tmpdir } from "../../fixture/fixture" const CS = "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://ingest.example.invalid/" const ENV = [ @@ -39,6 +40,7 @@ describe("telemetry opt-out", () => { beforeEach(async () => { await Telemetry.shutdown() + Telemetry.resetGateForTest() home = mkdtempSync(path.join(os.tmpdir(), "telemetry-opt-out-")) mkdirSync(path.join(home, ".altimate")) // Simulate a previously signed-in installation with a machine ID. @@ -70,6 +72,7 @@ describe("telemetry opt-out", () => { afterEach(async () => { await Telemetry.shutdown() + Telemetry.resetGateForTest() Telemetry.setConfigDirectory(undefined) fetchSpy.mockRestore() configSpy.mockRestore() @@ -256,223 +259,137 @@ describe("telemetry opt-out", () => { const names: string[] = [] fetchSpy.mockImplementation(Object.assign(async (url: Parameters[0], request?: Parameters[1]) => { if (url !== "https://ingest.example.invalid/v2/track") throw new Error("Unexpected telemetry request") - for (const envelope of JSON.parse(String(request?.body))) names.push(envelope.data.baseData.name) + for (const envelope of JSON.parse(String(request?.body))) { + names.push(envelope.data.baseData.properties?.error_name ?? envelope.data.baseData.name) + } return new Response(null, { status: 204 }) }, { preconnect: fetch.preconnect })) return names } - test("a later init sends held startup events exactly once", async () => { - const names = recordIngestion() - process.env.OPENCODE_CONFIG_CONTENT = "{" - trackStartup() - await Telemetry.init() - await Telemetry.refreshIdentity() - await Telemetry.flush() - expect(fetchSpy).not.toHaveBeenCalled() + function errorEvent(name: string) { + return { type: "error", timestamp: Date.now(), session_id: "", error_name: name, error_message: "test", context: "test" } as const + } + /** No signed-in account, so the only requests are ingestion. */ + function signOut() { rmSync(path.join(home, ".altimate", "altimate.json")) - configSpy.mockResolvedValue({ telemetry: { disabled: false } }) - await Telemetry.init() - await Telemetry.flush() - await Telemetry.shutdown() - expect(names).toEqual(["startup_ready"]) - }) + } - test("only the owning project can release a held startup event", async () => { + test("an unreadable config holds startup events; a later enabled init sends them once", async () => { const names = recordIngestion() + signOut() process.env.OPENCODE_CONFIG_CONTENT = "{" trackStartup() await Telemetry.init() - await Telemetry.shutdown({ preservePending: true }) - expect(fetchSpy).not.toHaveBeenCalled() - - const credentialsPath = path.join(home, ".altimate", "altimate.json") - const credentials = readFileSync(credentialsPath) - rmSync(credentialsPath) - const other = path.join(home, "other") - mkdirSync(other) - Telemetry.setConfigDirectory(other) - configSpy.mockResolvedValue({}) - Telemetry.track({ - type: "error", - timestamp: Date.now(), - error_name: "OtherProject", - error_message: "test", - context: "test", - session_id: "", - }) - await Telemetry.init() await Telemetry.flush() - expect(names).toEqual(["error"]) - await Telemetry.refreshIdentity() - const callsBeforeSwitch = fetchSpy.mock.calls.length - - Telemetry.setConfigDirectory(home) - writeFileSync(credentialsPath, credentials) expect(Telemetry.isEnabled()).toBe(false) - const lookup = spyOn(TelemetryIdentity, "resolveWithOutcome").mockResolvedValue({ outcome: "none" }) - try { - await Telemetry.refreshIdentity() - expect(lookup).not.toHaveBeenCalled() - expect(fetchSpy).toHaveBeenCalledTimes(callsBeforeSwitch) - } finally { - lookup.mockRestore() - } - rmSync(credentialsPath) - await Telemetry.shutdown({ preservePending: true }) - - await Telemetry.init() - await Telemetry.flush() - expect(names).toEqual(["error", "startup_ready"]) - }) + expect(fetchSpy).not.toHaveBeenCalled() - test.each(["queued", "in-flight"] as const)("a timed-out handoff keeps the %s batch for its own project", async (state) => { - rmSync(path.join(home, ".altimate", "altimate.json")) - const names = recordIngestion() - const ingest = fetchSpy.getMockImplementation()! - let timedOut = false - let notifyStarted!: () => void - const started = new Promise((resolve) => { notifyStarted = resolve }) - fetchSpy.mockImplementation(Object.assign( - (url: Parameters[0], request?: Parameters[1]) => { - if (timedOut) return ingest(url, request) - notifyStarted() - return new Promise((_, reject) => { - request?.signal?.addEventListener("abort", () => { - timedOut = true - reject(new Error("ingestion timed out")) - }, { once: true }) - }) - }, - { preconnect: fetch.preconnect }, - )) configSpy.mockResolvedValue({}) + // While unreadable, init() re-resolves the config at most every 30 s. + const reads = configSpy.mock.calls.length await Telemetry.init() - Telemetry.track({ - type: "error", - timestamp: Date.now(), - error_name: "OutgoingProject", - error_message: "test", - context: "test", - session_id: "", - }) - - if (state === "in-flight") { - void Telemetry.flush() - await started - } - const other = path.join(home, "other") - mkdirSync(other) - Telemetry.setConfigDirectory(other) - await Telemetry.init() - await Telemetry.flush() - expect(timedOut).toBe(true) - expect(names).toEqual([]) - - Telemetry.setConfigDirectory(home) - await Telemetry.init() - await Telemetry.flush() - expect(names).toEqual(["error"]) - }) - - test("a missing working directory leaves telemetry unresolved without throwing", async () => { - const names = recordIngestion() - Telemetry.setConfigDirectory(undefined) - const cwd = spyOn(process, "cwd").mockImplementation(() => { - throw new Error("working directory deleted") - }) - try { - trackStartup() - await Telemetry.init() - await Telemetry.flush() - expect(Telemetry.isEnabled()).toBe(false) - expect(fetchSpy).not.toHaveBeenCalled() - } finally { - cwd.mockRestore() - } + expect(configSpy.mock.calls.length).toBe(reads) + expect(fetchSpy).not.toHaveBeenCalled() - rmSync(path.join(home, ".altimate", "altimate.json")) - Telemetry.setConfigDirectory(home) - configSpy.mockResolvedValue({}) + Telemetry.retryConfigNowForTest() await Telemetry.init() + expect(Telemetry.isEnabled()).toBe(true) await Telemetry.flush() - expect(names).toEqual([]) + await Telemetry.shutdown() + expect(names).toEqual(["startup_ready"]) }) - test("even a fully evicted project keeps its own overflow count", async () => { + test("a session shutdown while unresolved keeps held events for a later init", async () => { const names = recordIngestion() + signOut() process.env.OPENCODE_CONFIG_CONTENT = "{" - await Telemetry.init() trackStartup() - await Telemetry.shutdown({ preservePending: true }) - - rmSync(path.join(home, ".altimate", "altimate.json")) - const other = path.join(home, "other") - mkdirSync(other) - Telemetry.setConfigDirectory(other) - for (let i = 0; i < 200; i++) trackStartup() - configSpy.mockResolvedValue({ telemetry: { disabled: true } }) - await Telemetry.init() - await Telemetry.flush() - expect(names).toEqual([]) - await Telemetry.shutdown({ preservePending: true }) - - Telemetry.setConfigDirectory(home) - configSpy.mockResolvedValue({}) await Telemetry.init() - await Telemetry.flush() - expect(names).toEqual(["error"]) - expect(String(fetchSpy.mock.calls.at(-1)?.[1]?.body)).toContain("TelemetryBufferOverflow") - }) + await Telemetry.shutdown() + expect(fetchSpy).not.toHaveBeenCalled() - test("a process-wide stall keeps the active scope outside its instance context", async () => { - const names = recordIngestion() - rmSync(path.join(home, ".altimate", "altimate.json")) configSpy.mockResolvedValue({}) + Telemetry.retryConfigNowForTest() await Telemetry.init() - - Telemetry.setConfigDirectory(undefined) - const stall = Telemetry.loopStallFor(1500, 0, 1000, "main") - expect(stall).toBeDefined() - Telemetry.track(stall!) await Telemetry.flush() - expect(names).toEqual(["event_loop_stall"]) + expect(names).toEqual(["startup_ready"]) }) - test("resolution to disabled discards held startup events", async () => { + test("an unreadable config that resolves to disabled sends nothing, then stays off for the process", async () => { const names = recordIngestion() process.env.OPENCODE_CONFIG_CONTENT = "{" trackStartup() await Telemetry.init() configSpy.mockResolvedValue({ telemetry: { disabled: true } }) + Telemetry.retryConfigNowForTest() await Telemetry.init() await Telemetry.flush() await Telemetry.refreshIdentity() + expect(Telemetry.isEnabled()).toBe(false) expect(fetchSpy).not.toHaveBeenCalled() + // Another session of the same process whose config reads as enabled. await Telemetry.shutdown() - rmSync(path.join(home, ".altimate", "altimate.json")) + signOut() configSpy.mockResolvedValue({}) + trackStartup() await Telemetry.init() await Telemetry.flush() expect(names).toEqual([]) }) - test("exit while unresolved never sends and clears held events", async () => { - const names = recordIngestion() + test("exit while unresolved sends nothing", async () => { process.env.OPENCODE_CONFIG_CONTENT = "{" trackStartup() await Telemetry.init() trackStartup() - await Telemetry.shutdown() + await Telemetry.shutdown({ timeoutMs: Telemetry.EXIT_FLUSH_BUDGET_MS }) expect(fetchSpy).not.toHaveBeenCalled() + }) - rmSync(path.join(home, ".altimate", "altimate.json")) + test("two opted-in projects in one process share one lifecycle and lose no events", async () => { + const names = recordIngestion() + signOut() configSpy.mockResolvedValue({}) - await Telemetry.init() + await using a = await tmpdir({ git: true }) + await using b = await tmpdir({ git: true }) + const enabledDuringTurns: boolean[] = [] + let releaseA!: () => void + const aMidTurn = new Promise((resolve) => (releaseA = resolve)) + let markAStarted!: () => void + const aStarted = new Promise((resolve) => (markAStarted = resolve)) + + const turnA = Instance.provide({ + directory: a.path, + fn: async () => { + await Telemetry.init() + Telemetry.track(errorEvent("A1")) + markAStarted() + await aMidTurn + // B's turn started meanwhile: A's telemetry is still on. + enabledDuringTurns.push(Telemetry.isEnabled()) + Telemetry.track(errorEvent("A2")) + }, + }) + await aStarted + await Instance.provide({ + directory: b.path, + fn: async () => { + await Telemetry.init() + enabledDuringTurns.push(Telemetry.isEnabled()) + Telemetry.track(errorEvent("B1")) + }, + }) + releaseA() + await turnA await Telemetry.flush() - expect(names).toEqual([]) + + expect(enabledDuringTurns).toEqual([true, true]) + // B joined the running lifecycle: no shutdown and re-init, so the config was resolved once. + expect(configSpy).toHaveBeenCalledTimes(1) + expect(names.sort()).toEqual(["A1", "A2", "B1"]) }) test("malformed auth prevents an otherwise loaded config from enabling telemetry", async () => { diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index dffad8fc73..34b40ecfb3 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -751,6 +751,7 @@ for (const failure of ["account", "organization"] as const) { Effect.promise(async () => { const events: string[] = [] await Telemetry.shutdown() + Telemetry.resetGateForTest() Telemetry.setConfigDirectory(context.directory) const fetchSpy = spyOn(globalThis, "fetch").mockImplementation(Object.assign( async (url: Parameters[0], request?: Parameters[1]) => { @@ -778,7 +779,12 @@ for (const failure of ["account", "organization"] as const) { expect(telemetryCalls).toEqual([]) expect(orgLoads).toBe(1) + // Retries are throttled while the config stays unreadable. + await Telemetry.init() + expect(orgLoads).toBe(1) + recovered = true + Telemetry.retryConfigNowForTest() await Telemetry.init() await Telemetry.flush() expect(events).toEqual(["startup_ready", "startup_ready"]) @@ -795,118 +801,6 @@ for (const failure of ["account", "organization"] as const) { ) } -{ - let loads = 0 - let available = false - const account = Layer.mock(Account.Service)({ - active: () => Effect.suspend(() => { - loads++ - if (available) return Effect.succeed(Option.none()) - return Effect.fail(new AccountServiceError({ message: "Organization unavailable" })) - }), - }) - configIt({ account }).instance("repeated telemetry retries back off while account config remains unavailable", () => - Effect.gen(function* () { - expect(Config.telemetryConfigUnresolved(yield* Config.use.get())).toBe(true) - expect(Config.telemetryConfigUnresolved(yield* Config.use.get(true))).toBe(true) - expect(Config.telemetryConfigUnresolved(yield* Config.use.get(true))).toBe(true) - expect(loads).toBe(2) - - available = true - yield* Config.use.invalidate() - expect(Config.telemetryConfigUnresolved(yield* Config.use.get(true))).toBe(false) - expect(loads).toBe(3) - }), - ) -} - -for (const [format, body] of [ - ["JSON", "{"], - ["schema", JSON.stringify({ config: { telemetry: { disabled: "invalid" } } })], -]) { - let requests = 0 - const client = HttpClient.make((request) => { - requests++ - return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body, { - headers: { "content-type": "application/json" }, - }))) - }) - configIt({ auth: wellKnownAuth("https://config.example.invalid"), client }).instance( - `invalid well-known config ${format} backs off on repeated telemetry retries`, - () => - Effect.gen(function* () { - expect(Exit.isFailure(yield* Config.use.get().pipe(Effect.exit))).toBe(true) - expect(Exit.isFailure(yield* Config.use.get(true).pipe(Effect.exit))).toBe(true) - expect(Exit.isFailure(yield* Config.use.get(true).pipe(Effect.exit))).toBe(true) - expect(requests).toBe(2) - }), - ) -} - -{ - let requests = 0 - const account = Layer.mock(Account.Service)({ - active: () => Effect.succeed(Option.some({ - id: AccountID.make("invalid-config-account"), - email: "user@example.com", - url: "https://control.example.invalid", - active_org_id: OrgID.make("org"), - })), - config: () => Effect.sync(() => { - requests++ - return Option.some({ telemetry: { disabled: "invalid" } }) - }), - token: () => Effect.succeed(Option.none()), - }) - configIt({ account }).instance("invalid organization config schema backs off on repeated telemetry retries", () => - Effect.gen(function* () { - expect(Exit.isFailure(yield* Config.use.get().pipe(Effect.exit))).toBe(true) - expect(Exit.isFailure(yield* Config.use.get(true).pipe(Effect.exit))).toBe(true) - expect(Exit.isFailure(yield* Config.use.get(true).pipe(Effect.exit))).toBe(true) - expect(requests).toBe(2) - }), - ) -} - -for (const localSource of ["auth", "global"] as const) { - let requests = 0 - const account = Layer.mock(Account.Service)({ - active: () => Effect.succeed(Option.some({ - id: AccountID.make("local-config-account"), - email: "user@example.com", - url: "https://control.example.invalid", - active_org_id: OrgID.make("org"), - })), - config: () => Effect.sync(() => { - requests++ - return Option.none() - }), - token: () => Effect.succeed(Option.none()), - }) - configIt({ account, auth: Auth.defaultLayer }).instance( - `an unreadable ${localSource} source recovers without refetching org config until repaired`, - () => - withGlobalConfig({}, ({ dir }) => - withProcessEnv( - "OPENCODE_AUTH_CONTENT", - localSource === "auth" ? "{" : "{}", - Effect.gen(function* () { - const legacy = path.join(dir, "config") - if (localSource === "global") yield* FSUtil.use.writeWithDirs(legacy, "broken = [") - expect(Config.telemetryConfigUnresolved(yield* Config.use.get())).toBe(true) - expect(Config.telemetryConfigUnresolved(yield* Config.use.get(true))).toBe(true) - expect(requests).toBe(1) - - if (localSource === "global") yield* FSUtil.use.writeWithDirs(legacy, "[telemetry]\ndisabled = false") - else process.env.OPENCODE_AUTH_CONTENT = "{}" - expect(Config.telemetryConfigUnresolved(yield* Config.use.get(true))).toBe(false) - expect(requests).toBe(2) - }), - ), - ), - ) -} - it.instance("a telemetry retry reloads a repaired config after a cached load failure", () => Effect.gen(function* () { const { directory } = yield* TestInstance diff --git a/packages/opencode/test/preload.ts b/packages/opencode/test/preload.ts index 1367e86df2..9c8abd76c4 100644 --- a/packages/opencode/test/preload.ts +++ b/packages/opencode/test/preload.ts @@ -158,6 +158,12 @@ let runningAtStart = new Set>() beforeEach(() => { runningAtStart = new Set(runningSyncs().map(([, sync]) => sync)) }) +// Telemetry's opt-out gate is process-wide and outlives shutdown(); files share a process, so each +// test starts from a fresh launch's state. +beforeEach(async () => { + const { Telemetry } = await import("../src/altimate/telemetry") + Telemetry.resetGateForTest() +}) afterEach(() => { const left = runningSyncs().filter(([, sync]) => !reportedSyncs.has(sync)) if (left.length === 0) return diff --git a/packages/opencode/test/upstream/altimate-features.test.ts b/packages/opencode/test/upstream/altimate-features.test.ts index b501c340a2..4336d93733 100644 --- a/packages/opencode/test/upstream/altimate-features.test.ts +++ b/packages/opencode/test/upstream/altimate-features.test.ts @@ -401,7 +401,7 @@ describe("altimate features: telemetry fail-safe init", () => { test("telemetry can resolve the opt-out before an Instance exists", async () => { const init = await readSrc("altimate", "telemetry", "index.ts") const config = await readSrc("altimate", "telemetry", "config-state.ts") - expect(init).toContain("await TelemetryConfig.resolve(scope, retry)") + expect(init).toContain("await TelemetryConfig.resolve(configDirectory") expect(config).toMatch(/try\s*\{\s*return await loadedState\(retry\)/) expect(config).toContain('return instanceDirectory() ? "unreadable" : disabledState(directory)') expect(config).toContain("ALTIMATE_TELEMETRY_DISABLED") From 5f0781732e1f49343eef05e88b61ce85e88de8aa Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 03:09:21 -0800 Subject: [PATCH 24/63] fix: let the TUI main thread adopt the worker telemetry opt-out - The main thread loads no project, so a remote or org config left its startup events held until exit; it now takes the worker's resolved answer. - Apply the unreadable-config retry throttle in every gate state. - Keep a running enabled lifecycle across the test reset; test the track guard. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/telemetry/index.ts | 40 ++++++++-- packages/opencode/src/cli/cmd/tui.ts | 7 ++ packages/opencode/src/cli/tui/worker.ts | 12 ++- .../test/altimate/telemetry/opt-out.test.ts | 75 +++++++++++++++++++ .../test/upstream/altimate-features.test.ts | 8 ++ 5 files changed, 134 insertions(+), 8 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index cc0b4f22cb..6a1ab2de94 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2316,13 +2316,40 @@ export namespace Telemetry { // While the config is unreadable, re-resolve it at most this often (each try reloads the config). const CONFIG_RETRY_MS = 30_000 let configRetry: { at: number; instance: boolean } | undefined - /** Test seam: forget the process-wide opt-out decision and the events held for it. */ + // An enabled opt-out resolved by another thread of this launch (the TUI worker), used by the next init. + let adopted: "enabled" | undefined + /** The opt-out as this thread has resolved it. */ + export function optOutState() { + return gate + } + /** Take the opt-out another thread of this launch resolved: the TUI main thread never loads a project, + * so where its own probe cannot read the config (a remote or organization config) it uses the + * worker's answer. Does nothing once this thread has decided, or while the other has not. */ + export function adoptOptOut(state: "pending" | "enabled" | "disabled"): Promise { + if (gate !== "pending" || state === "pending") return Promise.resolve() + if (state === "disabled") { + gate = "disabled" + buffer = [] + droppedEvents = 0 + return Promise.resolve() + } + adopted = "enabled" + return (initPromise ?? Promise.resolve()).catch(() => {}).then(() => init()) + } + /** Test seam: forget the process-wide opt-out decision and the events held for it. A lifecycle a + * test left running and enabled keeps its decision, so it goes on sending as it did before the gate. */ export function resetGateForTest() { - gate = "pending" configRetry = undefined + adopted = undefined + if (initDone && enabled) return + gate = "pending" buffer = [] droppedEvents = 0 } + /** Test seam. */ + export function bufferedCountForTest() { + return buffer.length + } /** Test seam: end the unreadable-config retry backoff so the next init() re-resolves. */ export function retryConfigNowForTest() { if (configRetry) configRetry.at = 0 @@ -2543,8 +2570,8 @@ export namespace Telemetry { } // While the config stays unreadable, retry at most every CONFIG_RETRY_MS. The first init inside // an Instance is not throttled by an earlier one outside it: it reads the full config, which the - // instance-less probe could not. - if (!initPromise && gate === "pending" && configRetry && Date.now() < configRetry.at) { + // instance-less probe could not. An opt-out adopted from another thread needs no read. + if (!initPromise && !adopted && configRetry && Date.now() < configRetry.at) { if (configRetry.instance || !TelemetryConfig.instanceDirectory()) return Promise.resolve() } return (initPromise ??= doInit()) @@ -2564,7 +2591,7 @@ export namespace Telemetry { return } const instance = Boolean(TelemetryConfig.instanceDirectory()) - const state = await TelemetryConfig.resolve(configDirectory, configRetry !== undefined) + const state = adopted ?? (await TelemetryConfig.resolve(configDirectory, configRetry !== undefined)) if (state === "disabled") { gate = "disabled" buffer = [] @@ -2961,8 +2988,7 @@ export namespace Telemetry { } } // altimate_change end - // altimate_change — nothing leaves until an init resolved the opt-out to enabled - if (gate !== "enabled" || !enabled || buffer.length === 0 || !appInsights) return + if (!enabled || buffer.length === 0 || !appInsights) return const events = buffer.splice(0, buffer.length) diff --git a/packages/opencode/src/cli/cmd/tui.ts b/packages/opencode/src/cli/cmd/tui.ts index 05cdde12ce..c24a6857ca 100644 --- a/packages/opencode/src/cli/cmd/tui.ts +++ b/packages/opencode/src/cli/cmd/tui.ts @@ -214,6 +214,13 @@ export const TuiThreadCommand = cmd({ } as WorkerOptions) // altimate_change end const client = Rpc.client(worker) + // altimate_change start — this thread loads no project, so where its own read of the opt-out + // stays unresolved (a remote or organization config), it takes the worker's answer + client + .call("telemetryOptOut", undefined) + .then(async (state) => Telemetry.adoptOptOut(await state)) + .catch(() => {}) + // altimate_change end const reload = () => { client.call("reload", undefined).catch(() => {}) } diff --git a/packages/opencode/src/cli/tui/worker.ts b/packages/opencode/src/cli/tui/worker.ts index f0d8daa516..a2b2599f56 100644 --- a/packages/opencode/src/cli/tui/worker.ts +++ b/packages/opencode/src/cli/tui/worker.ts @@ -78,6 +78,8 @@ const traceConsumer = new TraceConsumer() // a trace that never persists. So the event chain starts with this promise. loadConfig reads // Config.get() (a facade needing an Instance on the canonical ALS the bare worker lacks at init), so // load the project instance for the worker's cwd first; best-effort fallback otherwise. +// altimate_change — this thread's telemetry init inside the project instance; see rpc.telemetryOptOut +let telemetryInit: Promise | undefined const traceReady: Promise = (async () => { // altimate_change start — the datamate heal writes altimate-code.json; let it finish // before InstanceRuntime.load/Config.get() read (and cache) the config, so the first @@ -91,7 +93,7 @@ const traceReady: Promise = (async () => { // context, so doInit()'s Config.get() can see a `telemetry.disabled` opt-out. init() is // idempotent and drains the anchor events (event_loop_stall) buffered since boot as soon as // it enables; if the instance fails to load, the first prompt initialises telemetry as before. - Telemetry.init().catch(() => {}) + telemetryInit = Telemetry.init().catch(() => {}) // altimate_change end return traceConsumer.loadConfig() }) @@ -136,6 +138,14 @@ const pendingRequests = new Map() // altimate_change end export const rpc = { + // altimate_change start — the opt-out as resolved from the project's full config, for the main + // thread, which loads no project and so cannot read a remote or organization config itself. + async telemetryOptOut() { + await traceReady.catch(() => {}) + await telemetryInit + return Telemetry.optOutState() + }, + // altimate_change end // altimate_change start — no consent token: an explicit picker selection always registers if needed async registerAltimateBase() { return altimateBaseRegistration.register() diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 096384fcb0..a4d05cf9f3 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -349,6 +349,81 @@ describe("telemetry opt-out", () => { expect(fetchSpy).not.toHaveBeenCalled() }) + function wellKnownAuth() { + process.env.OPENCODE_AUTH_CONTENT = JSON.stringify({ + "https://config.example.invalid": { type: "wellknown", key: "TEST_CONFIG_TOKEN", token: "test-token" }, + }) + } + + test("a thread that cannot read a remote config sends its held events once the worker resolves enabled", async () => { + const names = recordIngestion() + signOut() + wellKnownAuth() + trackStartup() + await Telemetry.init() + await Telemetry.flush() + expect(Telemetry.optOutState()).toBe("pending") + expect(fetchSpy).not.toHaveBeenCalled() + + await Telemetry.adoptOptOut("pending") + expect(Telemetry.optOutState()).toBe("pending") + await Telemetry.adoptOptOut("enabled") + expect(Telemetry.isEnabled()).toBe(true) + await Telemetry.flush() + expect(names).toEqual(["startup_ready"]) + }) + + test("an opt-out resolved by the worker drops the held events and stays off", async () => { + const names = recordIngestion() + signOut() + wellKnownAuth() + trackStartup() + await Telemetry.init() + await Telemetry.adoptOptOut("disabled") + await Telemetry.adoptOptOut("enabled") + trackStartup() + await Telemetry.init() + await Telemetry.flush() + await Telemetry.shutdown() + expect(Telemetry.optOutState()).toBe("disabled") + expect(names).toEqual([]) + }) + + test("an env opt-out wins over an enabled answer from the worker", async () => { + signOut() + wellKnownAuth() + trackStartup() + await Telemetry.init() + process.env.ALTIMATE_TELEMETRY_DISABLED = "1" + await Telemetry.adoptOptOut("enabled") + await Telemetry.flush() + await Telemetry.shutdown() + expect(Telemetry.optOutState()).toBe("disabled") + expect(fetchSpy).not.toHaveBeenCalled() + }) + + test("the retry throttle still applies after an earlier session enabled telemetry", async () => { + recordIngestion() + signOut() + configSpy.mockResolvedValue({}) + await Telemetry.init() + await Telemetry.shutdown() + + configSpy.mockRejectedValue(new Error("InstanceRef not provided")) + process.env.OPENCODE_CONFIG_CONTENT = "{" + const reads = configSpy.mock.calls.length + for (let i = 0; i < 5; i++) await Telemetry.init() + expect(configSpy.mock.calls.length - reads).toBe(1) + }) + + test("after an opt-out, events tracked between sessions are not even buffered", async () => { + configSpy.mockResolvedValue({ telemetry: { disabled: true } }) + await Telemetry.init() + await Telemetry.shutdown() + for (let i = 0; i < 5; i++) trackStartup() + expect(Telemetry.bufferedCountForTest()).toBe(0) + }) + test("two opted-in projects in one process share one lifecycle and lose no events", async () => { const names = recordIngestion() signOut() diff --git a/packages/opencode/test/upstream/altimate-features.test.ts b/packages/opencode/test/upstream/altimate-features.test.ts index 4336d93733..2076bd0309 100644 --- a/packages/opencode/test/upstream/altimate-features.test.ts +++ b/packages/opencode/test/upstream/altimate-features.test.ts @@ -407,6 +407,14 @@ describe("altimate features: telemetry fail-safe init", () => { expect(config).toContain("ALTIMATE_TELEMETRY_DISABLED") }) + test("the TUI main thread adopts the worker's resolved opt-out", async () => { + const tui = await readSrc("cli", "cmd", "tui.ts") + const worker = await readSrc("cli", "tui", "worker.ts") + expect(tui).toMatch(/\.call\("telemetryOptOut", undefined\)\s*\.then\(async \(state\) => Telemetry\.adoptOptOut\(await state\)\)/) + expect(worker).toMatch(/async telemetryOptOut\(\) \{[\s\S]*?await telemetryInit\s*return Telemetry\.optOutState\(\)/) + expect(worker).toContain("telemetryInit = Telemetry.init()") + }) + test("telemetry/index.ts no longer reads the account; identity comes from the stored credential", async () => { const src = await readSrc("altimate", "telemetry", "index.ts") // The hashed account email left with the user-identity change: events carry the backend From 9971ca73bdee3d0e69c799ab77228f6937da88b5 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 03:23:37 -0800 Subject: [PATCH 25/63] fix: keep telemetry opt-out retries off the session path - A retry inside a project runs in the background, capped at 5 s. - tool report-event resolves a pending opt-out inside its project. - buildCliContext honours an opt-out this process already resolved. - The worker hands over its opt-out once its init settles; test the new branches. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/plugin/altimate.ts | 3 +- .../opencode/src/altimate/telemetry/index.ts | 32 ++++++++++++-- packages/opencode/src/cli/cmd/tool.ts | 8 ++++ packages/opencode/src/cli/tui/worker.ts | 7 +--- .../test/altimate/altimate-plugin.test.ts | 38 +++++++++++++++++ .../test/altimate/telemetry/opt-out.test.ts | 42 +++++++++++++++++++ .../test/upstream/altimate-features.test.ts | 12 ++++-- 7 files changed, 129 insertions(+), 13 deletions(-) diff --git a/packages/opencode/src/altimate/plugin/altimate.ts b/packages/opencode/src/altimate/plugin/altimate.ts index 650b6c43be..9d0d070074 100644 --- a/packages/opencode/src/altimate/plugin/altimate.ts +++ b/packages/opencode/src/altimate/plugin/altimate.ts @@ -82,7 +82,8 @@ export async function buildCliContext(machineIdPath?: string, directory?: string // telemetry/index.ts::doInit: // 1. the opt-out env vars (TelemetryConfig.disablingEnvironmentVariable) // 2. config.telemetry.disabled; a config that cannot be fully resolved omits the id - let disabled = Boolean(TelemetryConfig.disablingEnvironmentVariable()) + // A project this process already resolved as opted out stops it for every project it serves. + let disabled = Boolean(TelemetryConfig.disablingEnvironmentVariable()) || Telemetry.optOutState() === "disabled" if (!disabled) { // Server routes run inside Instance.provide(), so the full config resolves during an // ordinary browser authorize(). diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 6a1ab2de94..3965abe7cc 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2315,6 +2315,7 @@ export namespace Telemetry { let gate: "pending" | "enabled" | "disabled" = "pending" // While the config is unreadable, re-resolve it at most this often (each try reloads the config). const CONFIG_RETRY_MS = 30_000 + const CONFIG_RETRY_TIMEOUT_MS = 5_000 let configRetry: { at: number; instance: boolean } | undefined // An enabled opt-out resolved by another thread of this launch (the TUI worker), used by the next init. let adopted: "enabled" | undefined @@ -2322,6 +2323,11 @@ export namespace Telemetry { export function optOutState() { return gate } + /** The opt-out once this thread's running init has settled (for another thread to adopt). */ + export async function settledOptOutState() { + await initPromise?.catch(() => {}) + return gate + } /** Take the opt-out another thread of this launch resolved: the TUI main thread never loads a project, * so where its own probe cannot read the config (a remote or organization config) it uses the * worker's answer. Does nothing once this thread has decided, or while the other has not. */ @@ -2571,13 +2577,31 @@ export namespace Telemetry { // While the config stays unreadable, retry at most every CONFIG_RETRY_MS. The first init inside // an Instance is not throttled by an earlier one outside it: it reads the full config, which the // instance-less probe could not. An opt-out adopted from another thread needs no read. - if (!initPromise && !adopted && configRetry && Date.now() < configRetry.at) { - if (configRetry.instance || !TelemetryConfig.instanceDirectory()) return Promise.resolve() + // A retry of an Instance read reloads the full config (remote fetches included), so it runs + // in the background, bounded by CONFIG_RETRY_TIMEOUT_MS: a session start never waits on it. + let background = false + if (!initPromise && !adopted && configRetry) { + const inInstance = Boolean(TelemetryConfig.instanceDirectory()) + if (Date.now() < configRetry.at && (configRetry.instance || !inInstance)) return Promise.resolve() + background = configRetry.instance } - return (initPromise ??= doInit()) + initPromise ??= doInit() + return background ? Promise.resolve() : initPromise // altimate_change end } + // altimate_change start — a retry is bounded: a remote that hangs counts as still unreadable + function readOptOut(): Promise { + const read = TelemetryConfig.resolve(configDirectory, configRetry !== undefined) + if (!configRetry) return read + let timer: ReturnType | undefined + const timeout = new Promise((resolve) => { + timer = setTimeout(() => resolve("unreadable"), CONFIG_RETRY_TIMEOUT_MS) + }) + return Promise.race([read, timeout]).finally(() => clearTimeout(timer)) + } + // altimate_change end + async function doInit() { // altimate_change — an unreadable config leaves this init unfinished, so the next init() retries. let unresolved = false @@ -2591,7 +2615,7 @@ export namespace Telemetry { return } const instance = Boolean(TelemetryConfig.instanceDirectory()) - const state = adopted ?? (await TelemetryConfig.resolve(configDirectory, configRetry !== undefined)) + const state = adopted ?? (await readOptOut()) if (state === "disabled") { gate = "disabled" buffer = [] diff --git a/packages/opencode/src/cli/cmd/tool.ts b/packages/opencode/src/cli/cmd/tool.ts index 43389f4e3d..f113de5b72 100644 --- a/packages/opencode/src/cli/cmd/tool.ts +++ b/packages/opencode/src/cli/cmd/tool.ts @@ -368,6 +368,14 @@ const ToolReportEventCommand = cmd({ // Flushed, or dropped under the opt-out, when the CLI exits. const { Telemetry } = await import("../../altimate/telemetry") Telemetry.track(event) + // altimate_change start — this command loads no project, and the files alone cannot settle a + // remote or organization opt-out; resolve it from the project's full config, or the event would + // be held and dropped at exit + await Telemetry.init().catch(() => {}) + if (Telemetry.optOutState() === "pending") { + await bootstrap(process.cwd(), () => Telemetry.init()).catch(() => {}) + } + // altimate_change end }, }) diff --git a/packages/opencode/src/cli/tui/worker.ts b/packages/opencode/src/cli/tui/worker.ts index a2b2599f56..2732928b81 100644 --- a/packages/opencode/src/cli/tui/worker.ts +++ b/packages/opencode/src/cli/tui/worker.ts @@ -78,8 +78,6 @@ const traceConsumer = new TraceConsumer() // a trace that never persists. So the event chain starts with this promise. loadConfig reads // Config.get() (a facade needing an Instance on the canonical ALS the bare worker lacks at init), so // load the project instance for the worker's cwd first; best-effort fallback otherwise. -// altimate_change — this thread's telemetry init inside the project instance; see rpc.telemetryOptOut -let telemetryInit: Promise | undefined const traceReady: Promise = (async () => { // altimate_change start — the datamate heal writes altimate-code.json; let it finish // before InstanceRuntime.load/Config.get() read (and cache) the config, so the first @@ -93,7 +91,7 @@ const traceReady: Promise = (async () => { // context, so doInit()'s Config.get() can see a `telemetry.disabled` opt-out. init() is // idempotent and drains the anchor events (event_loop_stall) buffered since boot as soon as // it enables; if the instance fails to load, the first prompt initialises telemetry as before. - telemetryInit = Telemetry.init().catch(() => {}) + Telemetry.init().catch(() => {}) // altimate_change end return traceConsumer.loadConfig() }) @@ -142,8 +140,7 @@ export const rpc = { // thread, which loads no project and so cannot read a remote or organization config itself. async telemetryOptOut() { await traceReady.catch(() => {}) - await telemetryInit - return Telemetry.optOutState() + return Telemetry.settledOptOutState() }, // altimate_change end // altimate_change start — no consent token: an explicit picker selection always registers if needed diff --git a/packages/opencode/test/altimate/altimate-plugin.test.ts b/packages/opencode/test/altimate/altimate-plugin.test.ts index 3993fce4f2..85a1188e2a 100644 --- a/packages/opencode/test/altimate/altimate-plugin.test.ts +++ b/packages/opencode/test/altimate/altimate-plugin.test.ts @@ -8,6 +8,7 @@ import { Config } from "../../src/config/config" import { Telemetry } from "../../src/altimate/telemetry" import os from "os" import { tmpdir } from "../fixture/fixture" +import { Instance } from "../../src/project/instance" const VALID_UUID = "550e8400-e29b-41d4-a716-446655440000" @@ -101,6 +102,43 @@ describe("buildCliContext", () => { expect(ctx["v"]).toBe(1) }) + async function contextHasMachineId(directory?: string) { + await using dir = await tmpdir() + const idPath = path.join(dir.path, "machine-id") + fs.writeFileSync(idPath, VALID_UUID, "utf8") + const read = () => buildCliContext(idPath) + const encoded = directory ? await Instance.provide({ directory, fn: read }) : await read() + const ctx = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")) as Record + return Object.prototype.hasOwnProperty.call(ctx, "machine_id") + } + + test("omits machine_id once this process resolved an opt-out, even if this config is enabled", async () => { + delete process.env.ALTIMATE_TELEMETRY_DISABLED + await Telemetry.adoptOptOut("disabled") + expect(await contextHasMachineId()).toBe(false) + }) + + test("inside a project, omits machine_id when a remote config source could not be read", async () => { + delete process.env.ALTIMATE_TELEMETRY_DISABLED + await using project = await tmpdir({ git: true }) + const unresolved = spyOn(Config, "telemetryConfigUnresolved").mockReturnValue(true) + try { + expect(await contextHasMachineId(project.path)).toBe(false) + } finally { + unresolved.mockRestore() + } + expect(await contextHasMachineId(project.path)).toBe(true) + }) + + test("inside a project, omits machine_id when the full config fails to load", async () => { + delete process.env.ALTIMATE_TELEMETRY_DISABLED + await using project = await tmpdir({ git: true }) + cfg.mockImplementation((async () => { + throw new Error("config failed to load") + }) as never) + expect(await contextHasMachineId(project.path)).toBe(false) + }) + test("omits machine_id when config.telemetry.disabled is set", async () => { delete process.env.ALTIMATE_TELEMETRY_DISABLED cfg.mockImplementation((async () => ({ telemetry: { disabled: true } })) as never) diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index a4d05cf9f3..c4bc8a25f6 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -402,6 +402,48 @@ describe("telemetry opt-out", () => { expect(fetchSpy).not.toHaveBeenCalled() }) + test("the state handed to another thread waits for this thread's running init", async () => { + signOut() + let release!: (value: Awaited>) => void + configSpy.mockImplementation(() => new Promise((resolve) => (release = resolve))) + void Telemetry.init() + const settled = Telemetry.settledOptOutState() + await Bun.sleep(10) + expect(Telemetry.optOutState()).toBe("pending") + release({ telemetry: { disabled: true } }) + expect(await settled).toBe("disabled") + }) + + test("a retry inside a project never holds up the session that triggers it", async () => { + signOut() + await using dir = await tmpdir({ git: true }) + configSpy.mockResolvedValue({}) + const unresolved = spyOn(Config, "telemetryConfigUnresolved").mockReturnValue(true) + try { + await Instance.provide({ + directory: dir.path, + fn: async () => { + await Telemetry.init() + expect(Telemetry.optOutState()).toBe("pending") + + let release!: (value: Awaited>) => void + configSpy.mockImplementation(() => new Promise((resolve) => (release = resolve))) + Telemetry.retryConfigNowForTest() + let returned = false + await Telemetry.init().then(() => (returned = true)) + // The reload is still running, yet the caller already went on. + expect(returned).toBe(true) + expect(Telemetry.optOutState()).toBe("pending") + unresolved.mockReturnValue(false) + release({}) + expect(await Telemetry.settledOptOutState()).toBe("enabled") + }, + }) + } finally { + unresolved.mockRestore() + } + }) + test("the retry throttle still applies after an earlier session enabled telemetry", async () => { recordIngestion() signOut() diff --git a/packages/opencode/test/upstream/altimate-features.test.ts b/packages/opencode/test/upstream/altimate-features.test.ts index 2076bd0309..e9f263d31c 100644 --- a/packages/opencode/test/upstream/altimate-features.test.ts +++ b/packages/opencode/test/upstream/altimate-features.test.ts @@ -401,7 +401,7 @@ describe("altimate features: telemetry fail-safe init", () => { test("telemetry can resolve the opt-out before an Instance exists", async () => { const init = await readSrc("altimate", "telemetry", "index.ts") const config = await readSrc("altimate", "telemetry", "config-state.ts") - expect(init).toContain("await TelemetryConfig.resolve(configDirectory") + expect(init).toContain("TelemetryConfig.resolve(configDirectory") expect(config).toMatch(/try\s*\{\s*return await loadedState\(retry\)/) expect(config).toContain('return instanceDirectory() ? "unreadable" : disabledState(directory)') expect(config).toContain("ALTIMATE_TELEMETRY_DISABLED") @@ -411,8 +411,14 @@ describe("altimate features: telemetry fail-safe init", () => { const tui = await readSrc("cli", "cmd", "tui.ts") const worker = await readSrc("cli", "tui", "worker.ts") expect(tui).toMatch(/\.call\("telemetryOptOut", undefined\)\s*\.then\(async \(state\) => Telemetry\.adoptOptOut\(await state\)\)/) - expect(worker).toMatch(/async telemetryOptOut\(\) \{[\s\S]*?await telemetryInit\s*return Telemetry\.optOutState\(\)/) - expect(worker).toContain("telemetryInit = Telemetry.init()") + expect(worker).toMatch(/async telemetryOptOut\(\) \{[\s\S]*?return Telemetry\.settledOptOutState\(\)/) + }) + + test("tool report-event resolves a pending opt-out inside its project before exit", async () => { + const tool = await readSrc("cli", "cmd", "tool.ts") + expect(tool).toMatch( + /if \(Telemetry\.optOutState\(\) === "pending"\) \{\s*await bootstrap\(process\.cwd\(\), \(\) => Telemetry\.init\(\)\)/, + ) }) test("telemetry/index.ts no longer reads the account; identity comes from the stored credential", async () => { From 03a8d6709a9ea51fdbd04741f57091df24f1dadb Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 03:43:06 -0800 Subject: [PATCH 26/63] fix: read closed account databases and stop telemetry config reloads - Read a WAL account DB without side files as immutable, so opted-in users are not held. - Telemetry retries read the cached config instead of reloading it. - Revert the report-event bootstrap; push later worker decisions to the TUI. - Held events keep their session and project; an adopted opt-out wins a race. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/telemetry/config-state.ts | 19 ++-- .../opencode/src/altimate/telemetry/index.ts | 61 ++++++------ packages/opencode/src/cli/cmd/tool.ts | 8 -- packages/opencode/src/cli/cmd/tui.ts | 3 + packages/opencode/src/cli/tui/worker.ts | 3 + packages/opencode/src/config/config.ts | 20 +--- .../test/altimate/telemetry/opt-out.test.ts | 97 ++++++++++++++----- packages/opencode/test/config/config.test.ts | 28 ++---- .../test/upstream/altimate-features.test.ts | 12 +-- 9 files changed, 143 insertions(+), 108 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 9aa446de46..8dbe8c900b 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -78,19 +78,20 @@ export function instanceDirectory(): string | undefined { } /** The opt-out from the full config; throws where `Config` cannot load (outside an Instance). */ -export async function loadedState(retry = false): Promise { - const config = await Config.get(retry) +export async function loadedState(): Promise { + const config = await Config.get() if (Config.telemetryConfigUnresolved(config)) return "unreadable" // Auth.all() returns an empty store when its read or parse fails, hiding well-known remote config. + // Called only for that throw (an unparseable auth file); its result does not matter here. await hasWellKnownAuth() return config.telemetry?.disabled ? "disabled" : "enabled" } /** The opt-out as the caller can best read it: the full config inside an Instance (a failed load can * hide remote settings, so it is `unreadable`), the files on disk for commands that have none yet. */ -export async function resolve(directory?: string, retry = false): Promise { +export async function resolve(directory?: string): Promise { try { - return await loadedState(retry) + return await loadedState() } catch { return instanceDirectory() ? "unreadable" : disabledState(directory) } @@ -118,11 +119,17 @@ async function remoteMayDisable(local: boolean | undefined): Promise { await header.close() } - const db = new SQLite(dbPath, { readonly: true }) + // A read-only open of a WAL database needs its -wal/-shm files, which SQLite removes when the last + // connection closes cleanly (Linux, Windows). Without a -wal file every change is in the main file and + // no writer is attached, so read it as immutable (which reports its journal mode as "delete"). + const immutable = !existsSync(`${dbPath}-wal`) + const db = immutable + ? new SQLite(`file:${dbPath}?immutable=1`, { readonly: true }) + : new SQLite(dbPath, { readonly: true }) try { db.exec("PRAGMA busy_timeout = 0") // If the journal mode changed since the header read, defer to the full loader. - if (db.query<{ journal_mode: string }, []>("PRAGMA journal_mode").get()?.journal_mode !== "wal") return true + if (!immutable && db.query<{ journal_mode: string }, []>("PRAGMA journal_mode").get()?.journal_mode !== "wal") return true const tables = db.query<{ count: number }, []>( "SELECT count(*) AS count FROM sqlite_schema WHERE name IN ('account', 'account_state') AND type = 'table'", ).get() diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 3965abe7cc..40f58ee43b 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2313,16 +2313,26 @@ export namespace Telemetry { // so a later init never sends what an earlier one refused. Unlike `enabled`, it survives the // per-session shutdown; it is never reset outside tests. let gate: "pending" | "enabled" | "disabled" = "pending" - // While the config is unreadable, re-resolve it at most this often (each try reloads the config). + // While the config is unreadable, re-resolve it at most this often. const CONFIG_RETRY_MS = 30_000 - const CONFIG_RETRY_TIMEOUT_MS = 5_000 let configRetry: { at: number; instance: boolean } | undefined // An enabled opt-out resolved by another thread of this launch (the TUI worker), used by the next init. let adopted: "enabled" | undefined + const decisionListeners = new Set<(state: "enabled" | "disabled") => void>() + function decide(next: "enabled" | "disabled") { + if (gate === next) return + gate = next + for (const listener of decisionListeners) listener(next) + } /** The opt-out as this thread has resolved it. */ export function optOutState() { return gate } + /** Called each time this thread decides the opt-out, for another thread to adopt. */ + export function onOptOutDecided(listener: (state: "enabled" | "disabled") => void): () => void { + decisionListeners.add(listener) + return () => decisionListeners.delete(listener) + } /** The opt-out once this thread's running init has settled (for another thread to adopt). */ export async function settledOptOutState() { await initPromise?.catch(() => {}) @@ -2334,7 +2344,7 @@ export namespace Telemetry { export function adoptOptOut(state: "pending" | "enabled" | "disabled"): Promise { if (gate !== "pending" || state === "pending") return Promise.resolve() if (state === "disabled") { - gate = "disabled" + decide("disabled") buffer = [] droppedEvents = 0 return Promise.resolve() @@ -2576,32 +2586,15 @@ export namespace Telemetry { } // While the config stays unreadable, retry at most every CONFIG_RETRY_MS. The first init inside // an Instance is not throttled by an earlier one outside it: it reads the full config, which the - // instance-less probe could not. An opt-out adopted from another thread needs no read. - // A retry of an Instance read reloads the full config (remote fetches included), so it runs - // in the background, bounded by CONFIG_RETRY_TIMEOUT_MS: a session start never waits on it. - let background = false - if (!initPromise && !adopted && configRetry) { - const inInstance = Boolean(TelemetryConfig.instanceDirectory()) - if (Date.now() < configRetry.at && (configRetry.instance || !inInstance)) return Promise.resolve() - background = configRetry.instance + // instance-less probe could not. An opt-out adopted from another thread needs no read. Inside an + // Instance a retry reads the Instance's cached config, which its own reloads keep current. + if (!initPromise && !adopted && configRetry && Date.now() < configRetry.at) { + if (configRetry.instance || !TelemetryConfig.instanceDirectory()) return Promise.resolve() } - initPromise ??= doInit() - return background ? Promise.resolve() : initPromise + return (initPromise ??= doInit()) // altimate_change end } - // altimate_change start — a retry is bounded: a remote that hangs counts as still unreadable - function readOptOut(): Promise { - const read = TelemetryConfig.resolve(configDirectory, configRetry !== undefined) - if (!configRetry) return read - let timer: ReturnType | undefined - const timeout = new Promise((resolve) => { - timer = setTimeout(() => resolve("unreadable"), CONFIG_RETRY_TIMEOUT_MS) - }) - return Promise.race([read, timeout]).finally(() => clearTimeout(timer)) - } - // altimate_change end - async function doInit() { // altimate_change — an unreadable config leaves this init unfinished, so the next init() retries. let unresolved = false @@ -2609,15 +2602,16 @@ export namespace Telemetry { // altimate_change start — resolve the opt-out before anything can be sent. Env vars first, // then the config: the full one inside an Instance, the files on disk outside one. if (gate === "disabled" || TelemetryConfig.disablingEnvironmentVariable()) { - gate = "disabled" + decide("disabled") buffer = [] droppedEvents = 0 return } const instance = Boolean(TelemetryConfig.instanceDirectory()) - const state = adopted ?? (await readOptOut()) - if (state === "disabled") { - gate = "disabled" + const state = adopted ?? (await TelemetryConfig.resolve(configDirectory)) + // Another thread's opt-out may have been adopted while the read ran: it still wins. + if (state === "disabled" || optOutState() === "disabled") { + decide("disabled") buffer = [] droppedEvents = 0 return @@ -2628,7 +2622,7 @@ export namespace Telemetry { configRetry = { at: Date.now() + CONFIG_RETRY_MS, instance } return } - gate = "enabled" + decide("enabled") configRetry = undefined // altimate_change end // App Insights: env var overrides default (for dev/testing), otherwise use the baked-in key. @@ -2958,6 +2952,13 @@ export namespace Telemetry { const eventSession = (event as { session_id?: unknown }).session_id const operationId = typeof eventSession === "string" ? TraceContext.activeTraceId(eventSession) : undefined if (operationId) (event as any)._operation_id = operationId + // An event held while the opt-out is unknown can outlive this session: it keeps the session and + // project it was tracked under instead of taking the next one's at flush. + if (gate === "pending") { + const held = event as { session_id?: unknown; project_id?: unknown } + if (held.session_id === undefined && sessionId) held.session_id = sessionId + if (held.project_id === undefined && projectId) held.project_id = projectId + } // altimate_change end // altimate_change — no ambient workspace stamping: a row names its workspace itself (the prompt // loop's rows, tool rows and memory rows carry the turn's; workspace rows carry their own) or it diff --git a/packages/opencode/src/cli/cmd/tool.ts b/packages/opencode/src/cli/cmd/tool.ts index f113de5b72..43389f4e3d 100644 --- a/packages/opencode/src/cli/cmd/tool.ts +++ b/packages/opencode/src/cli/cmd/tool.ts @@ -368,14 +368,6 @@ const ToolReportEventCommand = cmd({ // Flushed, or dropped under the opt-out, when the CLI exits. const { Telemetry } = await import("../../altimate/telemetry") Telemetry.track(event) - // altimate_change start — this command loads no project, and the files alone cannot settle a - // remote or organization opt-out; resolve it from the project's full config, or the event would - // be held and dropped at exit - await Telemetry.init().catch(() => {}) - if (Telemetry.optOutState() === "pending") { - await bootstrap(process.cwd(), () => Telemetry.init()).catch(() => {}) - } - // altimate_change end }, }) diff --git a/packages/opencode/src/cli/cmd/tui.ts b/packages/opencode/src/cli/cmd/tui.ts index c24a6857ca..f279007664 100644 --- a/packages/opencode/src/cli/cmd/tui.ts +++ b/packages/opencode/src/cli/cmd/tui.ts @@ -216,6 +216,9 @@ export const TuiThreadCommand = cmd({ const client = Rpc.client(worker) // altimate_change start — this thread loads no project, so where its own read of the opt-out // stays unresolved (a remote or organization config), it takes the worker's answer + client.on<"enabled" | "disabled">("telemetry.optOut", (state) => { + Telemetry.adoptOptOut(state).catch(() => {}) + }) client .call("telemetryOptOut", undefined) .then(async (state) => Telemetry.adoptOptOut(await state)) diff --git a/packages/opencode/src/cli/tui/worker.ts b/packages/opencode/src/cli/tui/worker.ts index 2732928b81..d1da2a7c3b 100644 --- a/packages/opencode/src/cli/tui/worker.ts +++ b/packages/opencode/src/cli/tui/worker.ts @@ -135,6 +135,9 @@ const altimateBaseRegistration = FreeTierConsent.createRegistrationGate({ const pendingRequests = new Map() // altimate_change end +// altimate_change — a decision made after the main thread first asked (a later init) is pushed to it +Telemetry.onOptOutDecided((state) => Rpc.emit("telemetry.optOut", state)) + export const rpc = { // altimate_change start — the opt-out as resolved from the project's full config, for the main // thread, which loads no project and so cannot read a remote or organization config itself. diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 54ddbd449e..ff210c4e9f 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -270,7 +270,7 @@ type State = { } export interface Interface { - readonly get: (retryTelemetry?: boolean) => Effect.Effect // altimate_change — reload an unresolved opt-out + readonly get: () => Effect.Effect readonly getGlobal: () => Effect.Effect readonly getConsoleState: () => Effect.Effect readonly update: (config: Info) => Effect.Effect @@ -946,18 +946,9 @@ export const layer = Layer.effect( }), ) - // altimate_change start — `retryTelemetry`: reload a config whose telemetry opt-out could not be - // resolved (or that failed to load), so a source that has recovered is read. The caller throttles. - const get = Effect.fn("Config.get")(function* (retryTelemetry = false) { - const read = InstanceState.use(state, (s) => s.config) - if (!retryTelemetry || !(yield* InstanceState.has(state))) return yield* read - const cached = yield* Effect.exit(read) - if (Exit.isSuccess(cached) && !configsWithUnresolvedTelemetry.has(cached.value)) return cached.value - yield* invalidateGlobal - yield* InstanceState.invalidate(state) - return yield* read + const get = Effect.fn("Config.get")(function* () { + return yield* InstanceState.use(state, (s) => s.config) }) - // altimate_change end const directories = Effect.fn("Config.directories")(function* () { return yield* InstanceState.use(state, (s) => s.directories) @@ -1065,9 +1056,8 @@ export const node = LayerNode.make(layer, () => [FSUtil.node, Auth.node, Account // call `await Config.get()` etc. The makeRuntime bridge's `attach()` reads WorkspaceContext + // the current fiber's InstanceRef, so these reads stay bound to the active workspace/instance. const { runPromise: runConfig } = makeRuntime(Service, defaultLayer) -// altimate_change — `retryTelemetry`: see Service.get -export async function get(retryTelemetry = false) { - return runConfig((svc) => svc.get(retryTelemetry)) +export async function get() { + return runConfig((svc) => svc.get()) } export async function getGlobal() { return runConfig((svc) => svc.getGlobal()) diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index c4bc8a25f6..f2e7e58fd7 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -414,36 +414,87 @@ describe("telemetry opt-out", () => { expect(await settled).toBe("disabled") }) - test("a retry inside a project never holds up the session that triggers it", async () => { + test("a cleanly closed account database without WAL side files reads like any other", async () => { + const dbPath = path.join(home, "account.db") + databaseSpy.mockReturnValue(dbPath) + const db = new SQLite(dbPath) + db.exec(` + PRAGMA journal_mode = WAL; + CREATE TABLE account (id TEXT PRIMARY KEY); + CREATE TABLE account_state (id INTEGER PRIMARY KEY, active_account_id TEXT, active_org_id TEXT); + INSERT INTO account VALUES ('account'); + INSERT INTO account_state VALUES (1, 'account', NULL); + `) + db.close() + // SQLite removes these when the last connection closes on Linux and Windows. + rmSync(`${dbPath}-wal`, { force: true }) + rmSync(`${dbPath}-shm`, { force: true }) + expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + + const writer = new SQLite(dbPath) + writer.exec("UPDATE account_state SET active_org_id = 'org'") + writer.close() + rmSync(`${dbPath}-wal`, { force: true }) + rmSync(`${dbPath}-shm`, { force: true }) + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") + }) + + test("events held across a session keep the session and project they were tracked under", async () => { + const recorded: Array<{ session_id: string; project_id: string }> = [] + fetchSpy.mockImplementation(Object.assign(async (_url: Parameters[0], request?: Parameters[1]) => { + for (const envelope of JSON.parse(String(request?.body))) { + recorded.push({ session_id: envelope.tags["ai.session.id"], project_id: envelope.data.baseData.properties.project_id }) + } + return new Response(null, { status: 204 }) + }, { preconnect: fetch.preconnect })) signOut() - await using dir = await tmpdir({ git: true }) + process.env.OPENCODE_CONFIG_CONTENT = "{" + await Telemetry.init() + Telemetry.setContext({ sessionId: "session-a", projectId: "project-a" }) + // An event that names no session of its own (an MCP or stall event) takes the process's. + const { session_id: _omitted, ...sessionless } = errorEvent("Held") + Telemetry.track(sessionless as unknown as Telemetry.Event) + await Telemetry.shutdown() + + Telemetry.setContext({ sessionId: "session-b", projectId: "project-b" }) configSpy.mockResolvedValue({}) - const unresolved = spyOn(Config, "telemetryConfigUnresolved").mockReturnValue(true) + Telemetry.retryConfigNowForTest() + await Telemetry.init() + await Telemetry.flush() + expect(recorded.map((p) => [p.session_id, p.project_id])).toEqual([["session-a", "project-a"]]) + }) + + test("each opt-out decision is announced once, for another thread to adopt", async () => { + const decisions: string[] = [] + const stop = Telemetry.onOptOutDecided((state) => decisions.push(state)) try { - await Instance.provide({ - directory: dir.path, - fn: async () => { - await Telemetry.init() - expect(Telemetry.optOutState()).toBe("pending") - - let release!: (value: Awaited>) => void - configSpy.mockImplementation(() => new Promise((resolve) => (release = resolve))) - Telemetry.retryConfigNowForTest() - let returned = false - await Telemetry.init().then(() => (returned = true)) - // The reload is still running, yet the caller already went on. - expect(returned).toBe(true) - expect(Telemetry.optOutState()).toBe("pending") - unresolved.mockReturnValue(false) - release({}) - expect(await Telemetry.settledOptOutState()).toBe("enabled") - }, - }) + signOut() + configSpy.mockResolvedValue({}) + await Telemetry.init() + await Telemetry.shutdown() + await Telemetry.init() + expect(decisions).toEqual(["enabled"]) } finally { - unresolved.mockRestore() + stop() } }) + test("an opt-out adopted while this thread's own read runs still wins", async () => { + const names = recordIngestion() + signOut() + let release!: (value: Awaited>) => void + configSpy.mockImplementation(() => new Promise((resolve) => (release = resolve))) + trackStartup() + const init = Telemetry.init() + await Bun.sleep(10) + await Telemetry.adoptOptOut("disabled") + release({}) + await init + await Telemetry.flush() + expect(Telemetry.optOutState()).toBe("disabled") + expect(names).toEqual([]) + }) + test("the retry throttle still applies after an earlier session enabled telemetry", async () => { recordIngestion() signOut() diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 34b40ecfb3..23841d1dc2 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -762,8 +762,8 @@ for (const failure of ["account", "organization"] as const) { { preconnect: fetch.preconnect }, )) // Bridge the Promise facade to the same scoped service for each telemetry init. - const config = spyOn(Config, "get").mockImplementation((retry?: boolean) => - Effect.runPromise(provideCurrentInstance(service.get(retry), context)), + const config = spyOn(Config, "get").mockImplementation(() => + Effect.runPromise(provideCurrentInstance(service.get(), context)), ) try { const track = () => Telemetry.track({ @@ -783,9 +783,17 @@ for (const failure of ["account", "organization"] as const) { await Telemetry.init() expect(orgLoads).toBe(1) + // A due retry reads the Instance's cached config: telemetry never forces a refetch. recovered = true Telemetry.retryConfigNowForTest() await Telemetry.init() + expect(orgLoads).toBe(1) + expect(events).toEqual([]) + + // Once the app reloads its config, the next retry reads the recovered one. + await Effect.runPromise(provideCurrentInstance(service.invalidate(), context)) + Telemetry.retryConfigNowForTest() + await Telemetry.init() await Telemetry.flush() expect(events).toEqual(["startup_ready", "startup_ready"]) expect(orgLoads).toBe(2) @@ -801,22 +809,6 @@ for (const failure of ["account", "organization"] as const) { ) } -it.instance("a telemetry retry reloads a repaired config after a cached load failure", () => - Effect.gen(function* () { - const { directory } = yield* TestInstance - const configPath = path.join(directory, "opencode.json") - yield* FSUtil.use.writeWithDirs(configPath, "{") - const failed = yield* Config.use.get().pipe(Effect.exit) - expect(Exit.isFailure(failed)).toBe(true) - const failedRetry = yield* Config.use.get(true).pipe(Effect.exit) - expect(Exit.isFailure(failedRetry)).toBe(true) - - yield* FSUtil.use.writeWithDirs(configPath, JSON.stringify({ telemetry: { disabled: true } })) - const recovered = yield* Config.use.get(true) - expect(recovered.telemetry?.disabled).toBe(true) - }), -) - it.instance("validates config schema and throws on invalid fields", () => Effect.gen(function* () { const test = yield* TestInstance diff --git a/packages/opencode/test/upstream/altimate-features.test.ts b/packages/opencode/test/upstream/altimate-features.test.ts index e9f263d31c..d3dff60f59 100644 --- a/packages/opencode/test/upstream/altimate-features.test.ts +++ b/packages/opencode/test/upstream/altimate-features.test.ts @@ -402,7 +402,7 @@ describe("altimate features: telemetry fail-safe init", () => { const init = await readSrc("altimate", "telemetry", "index.ts") const config = await readSrc("altimate", "telemetry", "config-state.ts") expect(init).toContain("TelemetryConfig.resolve(configDirectory") - expect(config).toMatch(/try\s*\{\s*return await loadedState\(retry\)/) + expect(config).toMatch(/try\s*\{\s*return await loadedState\(\)/) expect(config).toContain('return instanceDirectory() ? "unreadable" : disabledState(directory)') expect(config).toContain("ALTIMATE_TELEMETRY_DISABLED") }) @@ -412,13 +412,9 @@ describe("altimate features: telemetry fail-safe init", () => { const worker = await readSrc("cli", "tui", "worker.ts") expect(tui).toMatch(/\.call\("telemetryOptOut", undefined\)\s*\.then\(async \(state\) => Telemetry\.adoptOptOut\(await state\)\)/) expect(worker).toMatch(/async telemetryOptOut\(\) \{[\s\S]*?return Telemetry\.settledOptOutState\(\)/) - }) - - test("tool report-event resolves a pending opt-out inside its project before exit", async () => { - const tool = await readSrc("cli", "cmd", "tool.ts") - expect(tool).toMatch( - /if \(Telemetry\.optOutState\(\) === "pending"\) \{\s*await bootstrap\(process\.cwd\(\), \(\) => Telemetry\.init\(\)\)/, - ) + // A decision the worker makes later (a later init) reaches the main thread too. + expect(worker).toContain('Telemetry.onOptOutDecided((state) => Rpc.emit("telemetry.optOut", state))') + expect(tui).toMatch(/client\.on<[^>]*>\("telemetry\.optOut", \(state\) => \{\s*Telemetry\.adoptOptOut\(state\)/) }) test("telemetry/index.ts no longer reads the account; identity comes from the stored credential", async () => { From 44a0c434892a9bfdaa1c96a516b21f8163ea7c89 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 03:56:09 -0800 Subject: [PATCH 27/63] fix: let a later telemetry opt-out stop a running lifecycle - A worker opt-out now stops a TUI main thread that already enabled telemetry. - Only the init that owns initPromise unpublishes it after an unreadable read. - Escape the account database path in its SQLite URI. - Log when telemetry is held; document the project-level opt-out timing; add tests. Co-Authored-By: Claude Opus 5.5 --- docs/docs/reference/security-faq.md | 2 +- docs/docs/reference/telemetry.md | 2 +- .../src/altimate/telemetry/config-state.ts | 3 +- .../opencode/src/altimate/telemetry/index.ts | 27 ++++++++-- .../test/altimate/telemetry/opt-out.test.ts | 53 +++++++++++++++++++ 5 files changed, 80 insertions(+), 7 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index 052c528591..c3f668bbd0 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -183,7 +183,7 @@ No code, queries, file paths, or personal information is included. This event he The install scripts (`altimate.sh/install`, `install.ps1`), the npm postinstall, and the VS Code extension's installer send nothing themselves and contact no telemetry endpoint. They only record the version and installer name to a local file that the CLI reads on its next run, so the opt-out above decides whether anything is ever transmitted. -The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. +The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables and the global config are honoured process-wide from the start. ## What happens when I authenticate via a well-known URL? diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index 32ea12c636..74b66545f2 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -184,7 +184,7 @@ export ALTIMATE_TELEMETRY_DISABLED=true `ALTIMATE_CLI_DISABLE_TELEMETRY` and its older spelling `OPENCODE_DISABLE_TELEMETRY` are also supported. Each variable accepts `1` or `true` (case-insensitive). -When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. Until the CLI can read the setting (for example at startup, before the project config or a configured remote source that could set the flag has loaded), it sends nothing; see [Privacy](#privacy). Once a process reads the setting as disabled, that process sends nothing more, even for another project it serves. +When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. Until the CLI can read the setting (for example at startup, before the project config or a configured remote source that could set the flag has loaded), it sends nothing; see [Privacy](#privacy). Once a process reads the setting as disabled, that process sends nothing more, even for another project it serves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables and the global config are honoured process-wide from the start. ### Test runs are excluded diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 8dbe8c900b..f7907b83c6 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -2,6 +2,7 @@ import { Database as SQLite } from "bun:sqlite" import path from "path" import fs from "fs/promises" import { existsSync } from "fs" +import { pathToFileURL } from "url" import * as Effect from "effect/Effect" import { InstanceRef } from "@/effect/instance-ref" import { attach } from "@/effect/run-service" @@ -124,7 +125,7 @@ async function remoteMayDisable(local: boolean | undefined): Promise { // no writer is attached, so read it as immutable (which reports its journal mode as "delete"). const immutable = !existsSync(`${dbPath}-wal`) const db = immutable - ? new SQLite(`file:${dbPath}?immutable=1`, { readonly: true }) + ? new SQLite(`${pathToFileURL(dbPath).href}?immutable=1`, { readonly: true }) // escapes `#`, `?`, `%` : new SQLite(dbPath, { readonly: true }) try { db.exec("PRAGMA busy_timeout = 0") diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 40f58ee43b..379d37ffbf 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2342,13 +2342,19 @@ export namespace Telemetry { * so where its own probe cannot read the config (a remote or organization config) it uses the * worker's answer. Does nothing once this thread has decided, or while the other has not. */ export function adoptOptOut(state: "pending" | "enabled" | "disabled"): Promise { - if (gate !== "pending" || state === "pending") return Promise.resolve() + if (state === "pending" || gate === "disabled") return Promise.resolve() if (state === "disabled") { + // An opt-out wins even after this thread enabled telemetry (a config reload in the worker): + // stop the running lifecycle too, so nothing more is sent from this process. decide("disabled") buffer = [] droppedEvents = 0 + enabled = false + if (flushTimer) clearInterval(flushTimer) + flushTimer = undefined return Promise.resolve() } + if (gate !== "pending") return Promise.resolve() adopted = "enabled" return (initPromise ?? Promise.resolve()).catch(() => {}).then(() => init()) } @@ -2564,12 +2570,14 @@ export namespace Telemetry { // wait for the new init rather than joining the dying one. if (shutdownPromise) { if (!reinitPromise) { - reinitPromise = shutdownPromise + const chained: Promise = shutdownPromise .catch(() => {}) .then(doInit) + .then(() => releaseUnresolved(chained)) // altimate_change — see releaseUnresolved .finally(() => { reinitPromise = undefined }) + reinitPromise = chained // Publish it as initPromise too. Without this, a caller arriving after the shutdown had // settled — but before this chained doInit() finished — saw an empty initPromise and // started a SECOND one, replacing the flush timer and racing over the buffer. @@ -2591,10 +2599,21 @@ export namespace Telemetry { if (!initPromise && !adopted && configRetry && Date.now() < configRetry.at) { if (configRetry.instance || !TelemetryConfig.instanceDirectory()) return Promise.resolve() } - return (initPromise ??= doInit()) + if (!initPromise) { + const started: Promise = doInit().then(() => releaseUnresolved(started)) + initPromise = started + } + return initPromise // altimate_change end } + // altimate_change start — an init left unresolved stays pre-init so the next init() retries; only + // the init that still owns initPromise unpublishes it (not a re-init published during a shutdown) + function releaseUnresolved(owner: Promise) { + if (!initDone && initPromise === owner) initPromise = undefined + } + // altimate_change end + async function doInit() { // altimate_change — an unreadable config leaves this init unfinished, so the next init() retries. let unresolved = false @@ -2620,6 +2639,7 @@ export namespace Telemetry { // An opted-out user may be behind it: hold the buffer (capped) and send nothing. unresolved = true configRetry = { at: Date.now() + CONFIG_RETRY_MS, instance } + log.info("telemetry held: opt-out unresolved", { instance }) return } decide("enabled") @@ -2673,7 +2693,6 @@ export namespace Telemetry { buffer = [] } finally { // altimate_change start — unresolved: stay pre-init so events keep buffering and init() retries - if (unresolved) initPromise = undefined initDone = !unresolved // altimate_change end // altimate_change start — the stall watcher also writes each stall to opencode.log, which `debug bundle` diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index f2e7e58fd7..9df49041dd 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -495,6 +495,59 @@ describe("telemetry opt-out", () => { expect(names).toEqual([]) }) + test("a later opt-out from the worker stops telemetry this thread already enabled", async () => { + const names = recordIngestion() + signOut() + configSpy.mockResolvedValue({}) + await Telemetry.init() + expect(Telemetry.isEnabled()).toBe(true) + await Telemetry.adoptOptOut("disabled") + trackStartup() + await Telemetry.flush() + await Telemetry.shutdown() + expect(Telemetry.isEnabled()).toBe(false) + expect(names).toEqual([]) + }) + + test("the first init inside a project is not held back by an earlier unreadable read outside one", async () => { + const names = recordIngestion() + signOut() + process.env.OPENCODE_CONFIG_CONTENT = "{" + trackStartup() + await Telemetry.init() + expect(Telemetry.optOutState()).toBe("pending") + + // Within the 30 s backoff: a read outside a project is throttled, one inside a project is not. + configSpy.mockResolvedValue({}) + await Telemetry.init() + expect(Telemetry.optOutState()).toBe("pending") + await using dir = await tmpdir({ git: true }) + await Instance.provide({ directory: dir.path, fn: () => Telemetry.init() }) + expect(Telemetry.optOutState()).toBe("enabled") + await Telemetry.flush() + expect(names).toEqual(["startup_ready"]) + }) + + test("an unresolved init settling during a shutdown leaves the re-init published", async () => { + signOut() + let release!: (value: Awaited>) => void + configSpy.mockImplementation(() => new Promise((resolve) => (release = resolve))) + void Telemetry.init() + await Bun.sleep(10) + const shutdown = Telemetry.shutdown() + const reinit = Telemetry.init() + // The first read now comes back unreadable while the shutdown waits for it. + const unresolved = spyOn(Config, "telemetryConfigUnresolved").mockReturnValue(true) + configSpy.mockResolvedValue({}) + release({}) + await shutdown + unresolved.mockRestore() + // A caller arriving now joins the re-init instead of starting a second one. + expect(Telemetry.init()).toBe(reinit) + await reinit + expect(Telemetry.optOutState()).toBe("enabled") + }) + test("the retry throttle still applies after an earlier session enabled telemetry", async () => { recordIngestion() signOut() From e9bbfcdec98c32789c572866553f56e196cfb341 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 04:09:00 -0800 Subject: [PATCH 28/63] fix: scope the telemetry retry throttle to instance-less reads - Inside an Instance every init reads the cached config, so one project never holds up another. - Keep held events at shutdown while a retry is outstanding; warn when telemetry is held. - Treat an immutable account-DB read as unknown if a writer attached; remove old marker files. - Preload resets the gate without importing telemetry. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/telemetry/config-state.ts | 8 +++- .../opencode/src/altimate/telemetry/index.ts | 46 +++++++++++++------ .../test/altimate/telemetry/opt-out.test.ts | 40 +++++++++++++++- packages/opencode/test/preload.ts | 9 ++-- 4 files changed, 83 insertions(+), 20 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index f7907b83c6..f7bda1e296 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -134,14 +134,18 @@ async function remoteMayDisable(local: boolean | undefined): Promise { const tables = db.query<{ count: number }, []>( "SELECT count(*) AS count FROM sqlite_schema WHERE name IN ('account', 'account_state') AND type = 'table'", ).get() - if (tables?.count !== 2) return false // A pre-migration database cannot select an organization. + // An immutable read is a snapshot: a writer that attached since (a -wal file appeared) may have + // selected an organization, so the answer is unknown. + const writerAttached = () => immutable && existsSync(`${dbPath}-wal`) + if (tables?.count !== 2) return writerAttached() // A pre-migration database cannot select an organization. const modern = db.query("SELECT 1 FROM pragma_table_info('account_state') WHERE name = 'active_org_id'").get() // The earlier schema stored the selected org on the account row. The migration // copies that value into account_state, so it can still enable remote config. const orgColumn = modern ? "account_state.active_org_id" : "account.selected_org_id" - return db.query(`SELECT 1 FROM account_state + const selected = db.query(`SELECT 1 FROM account_state JOIN account ON account.id = account_state.active_account_id WHERE account_state.id = 1 AND ${orgColumn} IS NOT NULL`).get() !== null + return selected || writerAttached() } finally { db.close() } diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 379d37ffbf..52fefc6cbc 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2315,7 +2315,7 @@ export namespace Telemetry { let gate: "pending" | "enabled" | "disabled" = "pending" // While the config is unreadable, re-resolve it at most this often. const CONFIG_RETRY_MS = 30_000 - let configRetry: { at: number; instance: boolean } | undefined + let configRetry: { at: number } | undefined // An enabled opt-out resolved by another thread of this launch (the TUI worker), used by the next init. let adopted: "enabled" | undefined const decisionListeners = new Set<(state: "enabled" | "disabled") => void>() @@ -2363,6 +2363,7 @@ export namespace Telemetry { export function resetGateForTest() { configRetry = undefined adopted = undefined + legacyMarkersRemoved = false if (initDone && enabled) return gate = "pending" buffer = [] @@ -2372,6 +2373,8 @@ export namespace Telemetry { export function bufferedCountForTest() { return buffer.length } + // The test preload resets the gate between tests through this, without importing this module. + ;(globalThis as Record)[Symbol.for("altimate.telemetry.resetGateForTest")] = resetGateForTest /** Test seam: end the unreadable-config retry backoff so the next init() re-resolves. */ export function retryConfigNowForTest() { if (configRetry) configRetry.at = 0 @@ -2592,12 +2595,12 @@ export namespace Telemetry { } return reinitPromise } - // While the config stays unreadable, retry at most every CONFIG_RETRY_MS. The first init inside - // an Instance is not throttled by an earlier one outside it: it reads the full config, which the - // instance-less probe could not. An opt-out adopted from another thread needs no read. Inside an - // Instance a retry reads the Instance's cached config, which its own reloads keep current. - if (!initPromise && !adopted && configRetry && Date.now() < configRetry.at) { - if (configRetry.instance || !TelemetryConfig.instanceDirectory()) return Promise.resolve() + // While the config stays unreadable, re-read the files outside an Instance at most every + // CONFIG_RETRY_MS. Inside an Instance a read is the Instance's cached config (its own reloads keep + // it current), so every init reads it: one project's unreadable config never holds up another's. + // An opt-out adopted from another thread needs no read. + if (!initPromise && !adopted && configRetry && Date.now() < configRetry.at && !TelemetryConfig.instanceDirectory()) { + return Promise.resolve() } if (!initPromise) { const started: Promise = doInit().then(() => releaseUnresolved(started)) @@ -2614,7 +2617,23 @@ export namespace Telemetry { } // altimate_change end + // altimate_change start — the opt-out marker files earlier versions wrote are no longer read + let legacyMarkersRemoved = false + function removeLegacyOptOutMarkers() { + if (legacyMarkersRemoved) return + legacyMarkersRemoved = true + for (const name of ["telemetry-opted-out", "telemetry-opted-out.sending"]) { + try { + fs.rmSync(path.join(os.homedir(), ".altimate", name), { force: true, recursive: true }) + } catch { + // Best effort: a leftover marker is harmless. + } + } + } + // altimate_change end + async function doInit() { + removeLegacyOptOutMarkers() // altimate_change // altimate_change — an unreadable config leaves this init unfinished, so the next init() retries. let unresolved = false try { @@ -2626,7 +2645,6 @@ export namespace Telemetry { droppedEvents = 0 return } - const instance = Boolean(TelemetryConfig.instanceDirectory()) const state = adopted ?? (await TelemetryConfig.resolve(configDirectory)) // Another thread's opt-out may have been adopted while the read ran: it still wins. if (state === "disabled" || optOutState() === "disabled") { @@ -2638,8 +2656,9 @@ export namespace Telemetry { if (state === "unreadable") { // An opted-out user may be behind it: hold the buffer (capped) and send nothing. unresolved = true - configRetry = { at: Date.now() + CONFIG_RETRY_MS, instance } - log.info("telemetry held: opt-out unresolved", { instance }) + configRetry = { at: Date.now() + CONFIG_RETRY_MS } + // A warning: a corrupt auth file or a failed organization config fetch holds telemetry this way. + log.warn("telemetry held: opt-out unresolved", { instance: Boolean(TelemetryConfig.instanceDirectory()) }) return } decide("enabled") @@ -3202,9 +3221,10 @@ export namespace Telemetry { shuttingDown = false enabled = false appInsights = undefined - // altimate_change start — while the opt-out is unresolved nothing was flushed: keep the events - // for a later init in this process to send or drop. At process exit they go with the process. - if (gate !== "pending") { + // altimate_change start — while the opt-out is unresolved (no decision yet, or this session's read + // failed) nothing was flushed: keep the events for a later init in this process to send or drop. + // At process exit they go with the process. + if (gate !== "pending" && !configRetry) { buffer = [] droppedEvents = 0 } diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 9df49041dd..fbb789a3bb 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -1,6 +1,6 @@ import { Database as SQLite } from "bun:sqlite" import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test" -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs" +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs" import os from "os" import path from "path" import { Database } from "@opencode-ai/core/database/database" @@ -548,6 +548,44 @@ describe("telemetry opt-out", () => { expect(Telemetry.optOutState()).toBe("enabled") }) + test("one project's unreadable config never holds up an opted-in project's next session", async () => { + const names = recordIngestion() + signOut() + await using a = await tmpdir({ git: true }) + await using b = await tmpdir({ git: true }) + const unresolvedConfig = {} as Awaited> + configSpy.mockImplementation(async () => (TelemetryConfig.instanceDirectory() === b.path ? unresolvedConfig : {})) + const unresolved = spyOn(Config, "telemetryConfigUnresolved").mockImplementation((config) => config === unresolvedConfig) + try { + await Instance.provide({ directory: a.path, fn: () => Telemetry.init() }) + await Telemetry.shutdown() + await Instance.provide({ directory: b.path, fn: () => Telemetry.init() }) + await Telemetry.shutdown() + // Within 30 s of B's failed read, A's next session still starts telemetry and sends its events. + await Instance.provide({ + directory: a.path, + fn: async () => { + await Telemetry.init() + expect(Telemetry.isEnabled()).toBe(true) + Telemetry.track(errorEvent("A")) + await Telemetry.flush() + }, + }) + expect(names).toEqual(["A"]) + } finally { + unresolved.mockRestore() + } + }) + + test("the opt-out marker files earlier versions wrote are removed", async () => { + const markers = ["telemetry-opted-out", "telemetry-opted-out.sending"].map((name) => path.join(home, ".altimate", name)) + for (const marker of markers) writeFileSync(marker, "") + signOut() + configSpy.mockResolvedValue({}) + await Telemetry.init() + expect(markers.filter((marker) => existsSync(marker))).toEqual([]) + }) + test("the retry throttle still applies after an earlier session enabled telemetry", async () => { recordIngestion() signOut() diff --git a/packages/opencode/test/preload.ts b/packages/opencode/test/preload.ts index 9c8abd76c4..5ea81cf482 100644 --- a/packages/opencode/test/preload.ts +++ b/packages/opencode/test/preload.ts @@ -159,10 +159,11 @@ beforeEach(() => { runningAtStart = new Set(runningSyncs().map(([, sync]) => sync)) }) // Telemetry's opt-out gate is process-wide and outlives shutdown(); files share a process, so each -// test starts from a fresh launch's state. -beforeEach(async () => { - const { Telemetry } = await import("../src/altimate/telemetry") - Telemetry.resetGateForTest() +// test starts from a fresh launch's state. Only once a test has loaded telemetry: importing it here +// would change module load order for files that mock its dependencies. +beforeEach(() => { + const reset = (globalThis as Record void) | undefined>)[Symbol.for("altimate.telemetry.resetGateForTest")] + reset?.() }) afterEach(() => { const left = runningSyncs().filter(([, sync]) => !reportedSyncs.has(sync)) From 15a3c30fcb5599c3dbc8b05a7a2583af86b903cb Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 04:19:49 -0800 Subject: [PATCH 29/63] fix: drop an unresolved project's held telemetry at its shutdown - Keep held events past shutdown only while the gate is undecided; stamp ids while not initialised. - An adopted opt-out aborts the batch in flight. - A managed telemetry setting settles the startup read even with an org selected. - Legacy marker cleanup uses the test-isolated home. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/telemetry/config-state.ts | 7 +- .../opencode/src/altimate/telemetry/index.ts | 13 +-- .../test/altimate/telemetry/opt-out.test.ts | 82 +++++++++++++++++++ packages/opencode/test/config/config.test.ts | 2 +- 4 files changed, 96 insertions(+), 8 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index f7bda1e296..74f0240cef 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -157,9 +157,13 @@ export async function disabledState(directory: string = process.cwd()): Promise< // Any source that fails to read, parse or validate fails Config's whole load, so the answer // is unknown however the other sources set it. let unknown = false + // Managed config is merged after the remote and organization configs, so a setting there wins. + let readingManaged = false + let managedSetting = false const take = (data: unknown) => { const disabled = (data as { telemetry?: { disabled?: unknown } } | undefined)?.telemetry?.disabled if (disabled === undefined) return + if (readingManaged) managedSetting = true if (typeof disabled !== "boolean") unknown = true else value = disabled } @@ -216,6 +220,7 @@ export async function disabledState(directory: string = process.cwd()): Promise< const inline = flagEnv("OPENCODE_CONFIG_CONTENT") if (inline) await readText(inline, "OPENCODE_CONFIG_CONTENT", directory) + readingManaged = true const managedDir = ConfigManaged.managedConfigDir() if (existsSync(managedDir)) for (const file of DIR_FILES) await readFile(path.join(managedDir, file)) const managed = await ConfigManaged.readManagedPreferences().catch(() => { @@ -225,7 +230,7 @@ export async function disabledState(directory: string = process.cwd()): Promise< if (managed) await readText(managed.text, managed.source, path.dirname(managed.source)) if (unknown) return "unreadable" - if (await remoteMayDisable(value)) return "unreadable" + if (!managedSetting && (await remoteMayDisable(value))) return "unreadable" return value === true ? "disabled" : "enabled" } catch { return "unreadable" diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 52fefc6cbc..3c83fb6537 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -15,6 +15,7 @@ import fs from "fs" import path from "path" import os from "os" import { fileLog } from "@/altimate/util/file-log" +import { Global } from "../../global" // altimate_change — test-isolated home for the legacy marker cleanup const log = Log.create({ service: "telemetry" }) @@ -2352,6 +2353,7 @@ export namespace Telemetry { enabled = false if (flushTimer) clearInterval(flushTimer) flushTimer = undefined + activeFlushAbort?.abort() // a batch already taken must not post after the opt-out return Promise.resolve() } if (gate !== "pending") return Promise.resolve() @@ -2624,7 +2626,7 @@ export namespace Telemetry { legacyMarkersRemoved = true for (const name of ["telemetry-opted-out", "telemetry-opted-out.sending"]) { try { - fs.rmSync(path.join(os.homedir(), ".altimate", name), { force: true, recursive: true }) + fs.rmSync(path.join(Global.Path.home, ".altimate", name), { force: true, recursive: true }) } catch { // Best effort: a leftover marker is harmless. } @@ -2992,7 +2994,7 @@ export namespace Telemetry { if (operationId) (event as any)._operation_id = operationId // An event held while the opt-out is unknown can outlive this session: it keeps the session and // project it was tracked under instead of taking the next one's at flush. - if (gate === "pending") { + if (!initDone) { const held = event as { session_id?: unknown; project_id?: unknown } if (held.session_id === undefined && sessionId) held.session_id = sessionId if (held.project_id === undefined && projectId) held.project_id = projectId @@ -3221,10 +3223,9 @@ export namespace Telemetry { shuttingDown = false enabled = false appInsights = undefined - // altimate_change start — while the opt-out is unresolved (no decision yet, or this session's read - // failed) nothing was flushed: keep the events for a later init in this process to send or drop. - // At process exit they go with the process. - if (gate !== "pending" && !configRetry) { + // altimate_change start — while the opt-out is undecided nothing was flushed: keep the events for a + // later init in this process to send or drop. At process exit they go with the process. + if (gate !== "pending") { buffer = [] droppedEvents = 0 } diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index fbb789a3bb..ca9508aee9 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -6,6 +6,7 @@ import path from "path" import { Database } from "@opencode-ai/core/database/database" import { Auth } from "../../../src/auth" import { Config } from "../../../src/config/config" +import { ConfigManaged } from "../../../src/config/managed" import { Telemetry } from "../../../src/altimate/telemetry" import { TelemetryConfig } from "../../../src/altimate/telemetry/config-state" import { Instance } from "../../../src/project/instance" @@ -577,6 +578,87 @@ describe("telemetry opt-out", () => { } }) + test("a project whose opt-out never resolved does not have its events sent under another project", async () => { + const names = recordIngestion() + signOut() + await using a = await tmpdir({ git: true }) + await using b = await tmpdir({ git: true }) + const unresolvedConfig = {} as Awaited> + configSpy.mockImplementation(async () => (TelemetryConfig.instanceDirectory() === b.path ? unresolvedConfig : {})) + const unresolved = spyOn(Config, "telemetryConfigUnresolved").mockImplementation((config) => config === unresolvedConfig) + try { + await Instance.provide({ directory: a.path, fn: () => Telemetry.init() }) + await Telemetry.shutdown() + await Instance.provide({ + directory: b.path, + fn: async () => { + await Telemetry.init() + Telemetry.track(errorEvent("B")) + }, + }) + await Telemetry.shutdown() + await Instance.provide({ directory: a.path, fn: () => Telemetry.init() }) + await Telemetry.flush() + expect(names).toEqual([]) + } finally { + unresolved.mockRestore() + } + }) + + test("a managed telemetry setting settles the startup read even with an organization selected", async () => { + const dbPath = path.join(home, "account.db") + const db = new SQLite(dbPath) + db.exec(` + PRAGMA journal_mode = WAL; + CREATE TABLE account (id TEXT PRIMARY KEY); + CREATE TABLE account_state (id INTEGER PRIMARY KEY, active_account_id TEXT, active_org_id TEXT); + INSERT INTO account VALUES ('account'); + INSERT INTO account_state VALUES (1, 'account', 'org'); + `) + db.close() + databaseSpy.mockReturnValue(dbPath) + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") + + const managed = path.join(home, "managed") + mkdirSync(managed) + const managedDir = spyOn(ConfigManaged, "managedConfigDir").mockReturnValue(managed) + try { + writeFileSync(path.join(managed, "altimate-code.json"), '{ "telemetry": { "disabled": false } }') + expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + writeFileSync(path.join(managed, "altimate-code.json"), '{ "telemetry": { "disabled": true } }') + expect(await TelemetryConfig.disabledState(home)).toBe("disabled") + } finally { + managedDir.mockRestore() + } + }) + + test("an opt-out adopted mid-flush aborts the batch already in flight", async () => { + signOut() + let aborted = false + let started!: () => void + const inFlight = new Promise((resolve) => (started = resolve)) + fetchSpy.mockImplementation(Object.assign( + (_url: Parameters[0], request?: Parameters[1]) => { + started() + return new Promise((_, reject) => { + request?.signal?.addEventListener("abort", () => { + aborted = true + reject(new Error("aborted")) + }, { once: true }) + }) + }, + { preconnect: fetch.preconnect }, + )) + configSpy.mockResolvedValue({}) + await Telemetry.init() + trackStartup() + const flushing = Telemetry.flush() + await inFlight + await Telemetry.adoptOptOut("disabled") + await flushing + expect(aborted).toBe(true) + }) + test("the opt-out marker files earlier versions wrote are removed", async () => { const markers = ["telemetry-opted-out", "telemetry-opted-out.sending"].map((name) => path.join(home, ".altimate", name)) for (const marker of markers) writeFileSync(marker, "") diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 23841d1dc2..de5ab414e7 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -779,7 +779,7 @@ for (const failure of ["account", "organization"] as const) { expect(telemetryCalls).toEqual([]) expect(orgLoads).toBe(1) - // Retries are throttled while the config stays unreadable. + // A repeat init inside the Instance reads its cached config: no second org fetch. await Telemetry.init() expect(orgLoads).toBe(1) From aff76838db302babf95cd04e5932d6e11df9d2a0 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 04:29:14 -0800 Subject: [PATCH 30/63] fix: settle a pending telemetry opt-out when a command loads its project - bootstrap() reads the full config when the startup read left the opt-out open. - A project whose own read failed drops its held events at session end. - Fall back to the auth file when OPENCODE_AUTH_CONTENT does not parse, as Auth does. - Warn once per hold; tests wait on the read instead of sleeping. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/telemetry/config-state.ts | 19 ++++- .../opencode/src/altimate/telemetry/index.ts | 22 +++++- packages/opencode/src/cli/bootstrap.ts | 9 ++- .../test/altimate/telemetry/opt-out.test.ts | 78 +++++++++++++++++-- 4 files changed, 113 insertions(+), 15 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 74f0240cef..50abd9535e 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -56,18 +56,29 @@ export function disablingEnvironmentVariable(): string | undefined { ) } +function parseJson(text: string): unknown { + try { + return JSON.parse(text) + } catch { + return undefined + } +} + async function hasWellKnownAuth(): Promise { - let contents = process.env.OPENCODE_AUTH_CONTENT - if (!contents) { + // As Auth reads it: OPENCODE_AUTH_CONTENT when it parses, otherwise the auth file. + const inline = process.env.OPENCODE_AUTH_CONTENT + let parsed: unknown = inline ? parseJson(inline) : undefined + if (parsed === undefined) { + let contents: string try { contents = await fs.readFile(Auth.filepath(), "utf8") } catch (error) { if ((error as NodeJS.ErrnoException)?.code === "ENOENT") return false throw error } + // Unparseable: a well-known entry may be behind it. `Config` would load without its remote config. + parsed = JSON.parse(contents) } - // Unparseable: a well-known entry may be behind it. `Config` would load without its remote config. - const parsed: unknown = JSON.parse(contents) if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Unreadable auth store") return Object.values(parsed).some( (entry) => entry && typeof entry === "object" && (entry as { type?: unknown }).type === "wellknown", diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 3c83fb6537..1d4eec86b1 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2317,6 +2317,9 @@ export namespace Telemetry { // While the config is unreadable, re-resolve it at most this often. const CONFIG_RETRY_MS = 30_000 let configRetry: { at: number } | undefined + // A project's own read (inside an Instance) came back unreadable: its held events are not kept past + // its session, where another project's decision could send them. + let unresolvedInProject = false // An enabled opt-out resolved by another thread of this launch (the TUI worker), used by the next init. let adopted: "enabled" | undefined const decisionListeners = new Set<(state: "enabled" | "disabled") => void>() @@ -2329,6 +2332,10 @@ export namespace Telemetry { export function optOutState() { return gate } + /** An init ran and could not settle the opt-out: a later init with more config (inside a project) may. */ + export function awaitingConfig() { + return gate === "pending" && configRetry !== undefined + } /** Called each time this thread decides the opt-out, for another thread to adopt. */ export function onOptOutDecided(listener: (state: "enabled" | "disabled") => void): () => void { decisionListeners.add(listener) @@ -2364,6 +2371,7 @@ export namespace Telemetry { * test left running and enabled keeps its decision, so it goes on sending as it did before the gate. */ export function resetGateForTest() { configRetry = undefined + unresolvedInProject = false adopted = undefined legacyMarkersRemoved = false if (initDone && enabled) return @@ -2658,13 +2666,17 @@ export namespace Telemetry { if (state === "unreadable") { // An opted-out user may be behind it: hold the buffer (capped) and send nothing. unresolved = true + const inProject = Boolean(TelemetryConfig.instanceDirectory()) + // A warning, once per hold: a corrupt auth file or a failed organization config fetch holds + // telemetry this way. + if (!configRetry) log.warn("telemetry held: opt-out unresolved", { instance: inProject }) configRetry = { at: Date.now() + CONFIG_RETRY_MS } - // A warning: a corrupt auth file or a failed organization config fetch holds telemetry this way. - log.warn("telemetry held: opt-out unresolved", { instance: Boolean(TelemetryConfig.instanceDirectory()) }) + if (inProject) unresolvedInProject = true return } decide("enabled") configRetry = undefined + unresolvedInProject = false // altimate_change end // App Insights: env var overrides default (for dev/testing), otherwise use the baked-in key. // The baked-in key is refused under a test runner so suites never ship to the production @@ -3224,8 +3236,10 @@ export namespace Telemetry { enabled = false appInsights = undefined // altimate_change start — while the opt-out is undecided nothing was flushed: keep the events for a - // later init in this process to send or drop. At process exit they go with the process. - if (gate !== "pending") { + // later init in this process to send or drop. At process exit they go with the process. Not when a + // project's own read failed: another project's decision must not send that project's events. + if (gate !== "pending" || unresolvedInProject) { + unresolvedInProject = false buffer = [] droppedEvents = 0 } diff --git a/packages/opencode/src/cli/bootstrap.ts b/packages/opencode/src/cli/bootstrap.ts index e955396528..0307f7a9f9 100644 --- a/packages/opencode/src/cli/bootstrap.ts +++ b/packages/opencode/src/cli/bootstrap.ts @@ -9,6 +9,7 @@ import { InstanceRuntime } from "../project/instance-runtime" // not provided" — silently disabling session tracing and breaking `skill list`/`create`/`test`. import { Instance } from "../project/instance" // altimate_change end +import { Telemetry } from "../altimate/telemetry" // altimate_change — settle a pending opt-out in the project export async function bootstrap(directory: string, cb: () => Promise) { // altimate_change start — upstream_fix: load the instance, then restore the loaded ctx on the @@ -16,7 +17,13 @@ export async function bootstrap(directory: string, cb: () => Promise) { // ALS, which left every plain-async facade reader without an instance). See import note above. const ctx = await InstanceRuntime.load({ directory }) try { - return await Instance.restore(ctx, cb) + return await Instance.restore(ctx, async () => { + // The CLI's startup telemetry init ran before this project loaded; if it could not settle the + // opt-out (a remote or organization config), read it here from the full config, so a command + // that starts no session does not drop an opted-in user's events. + if (Telemetry.awaitingConfig()) await Telemetry.init().catch(() => {}) + return cb() + }) } finally { await InstanceRuntime.disposeInstance(ctx) } diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index ca9508aee9..8a7c213306 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -10,6 +10,7 @@ import { ConfigManaged } from "../../../src/config/managed" import { Telemetry } from "../../../src/altimate/telemetry" import { TelemetryConfig } from "../../../src/altimate/telemetry/config-state" import { Instance } from "../../../src/project/instance" +import { bootstrap } from "../../../src/cli/bootstrap" import { tmpdir } from "../../fixture/fixture" const CS = "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://ingest.example.invalid/" @@ -268,6 +269,17 @@ describe("telemetry opt-out", () => { return names } + /** Make the next config read wait for the caller; resolves once that read has started. */ + function holdConfigRead(capture: (resolve: (value: Awaited>) => void) => void) { + let started!: () => void + const reading = new Promise((resolve) => (started = resolve)) + configSpy.mockImplementation(() => { + started() + return new Promise(capture) + }) + return reading + } + function errorEvent(name: string) { return { type: "error", timestamp: Date.now(), session_id: "", error_name: name, error_message: "test", context: "test" } as const } @@ -406,10 +418,10 @@ describe("telemetry opt-out", () => { test("the state handed to another thread waits for this thread's running init", async () => { signOut() let release!: (value: Awaited>) => void - configSpy.mockImplementation(() => new Promise((resolve) => (release = resolve))) + const reading = holdConfigRead((resolve) => (release = resolve)) void Telemetry.init() const settled = Telemetry.settledOptOutState() - await Bun.sleep(10) + await reading expect(Telemetry.optOutState()).toBe("pending") release({ telemetry: { disabled: true } }) expect(await settled).toBe("disabled") @@ -484,10 +496,10 @@ describe("telemetry opt-out", () => { const names = recordIngestion() signOut() let release!: (value: Awaited>) => void - configSpy.mockImplementation(() => new Promise((resolve) => (release = resolve))) + const reading = holdConfigRead((resolve) => (release = resolve)) trackStartup() const init = Telemetry.init() - await Bun.sleep(10) + await reading await Telemetry.adoptOptOut("disabled") release({}) await init @@ -532,9 +544,9 @@ describe("telemetry opt-out", () => { test("an unresolved init settling during a shutdown leaves the re-init published", async () => { signOut() let release!: (value: Awaited>) => void - configSpy.mockImplementation(() => new Promise((resolve) => (release = resolve))) + const reading = holdConfigRead((resolve) => (release = resolve)) void Telemetry.init() - await Bun.sleep(10) + await reading const shutdown = Telemetry.shutdown() const reinit = Telemetry.init() // The first read now comes back unreadable while the shutdown waits for it. @@ -659,6 +671,60 @@ describe("telemetry opt-out", () => { expect(aborted).toBe(true) }) + test("a command that loads a project settles an opt-out the startup read left open", async () => { + const names = recordIngestion() + signOut() + process.env.OPENCODE_CONFIG_CONTENT = "{" + trackStartup() + await Telemetry.init() + expect(Telemetry.awaitingConfig()).toBe(true) + + // The project's own load reads the real config; give it a readable one. + delete process.env.OPENCODE_CONFIG_CONTENT + configSpy.mockResolvedValue({}) + await using dir = await tmpdir({ git: true }) + await bootstrap(dir.path, async () => { + expect(Telemetry.optOutState()).toBe("enabled") + }) + await Telemetry.flush() + expect(names).toEqual(["startup_ready"]) + }) + + test("a project left unresolved drops its held events before another project decides", async () => { + const names = recordIngestion() + signOut() + await using a = await tmpdir({ git: true }) + await using b = await tmpdir({ git: true }) + const unresolvedConfig = {} as Awaited> + configSpy.mockImplementation(async () => (TelemetryConfig.instanceDirectory() === b.path ? unresolvedConfig : {})) + const unresolved = spyOn(Config, "telemetryConfigUnresolved").mockImplementation((config) => config === unresolvedConfig) + try { + await Instance.provide({ + directory: b.path, + fn: async () => { + await Telemetry.init() + Telemetry.track(errorEvent("B")) + }, + }) + await Telemetry.shutdown() + expect(Telemetry.optOutState()).toBe("pending") + await Instance.provide({ directory: a.path, fn: () => Telemetry.init() }) + await Telemetry.flush() + expect(names).toEqual([]) + } finally { + unresolved.mockRestore() + } + }) + + test("auth content that does not parse falls back to the auth file, as Auth does", async () => { + process.env.OPENCODE_AUTH_CONTENT = "{" + expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + writeFileSync(Auth.filepath(), JSON.stringify({ + "https://config.example.invalid": { type: "wellknown", key: "TEST_CONFIG_TOKEN", token: "test-token" }, + })) + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") + }) + test("the opt-out marker files earlier versions wrote are removed", async () => { const markers = ["telemetry-opted-out", "telemetry-opted-out.sending"].map((name) => path.join(home, ".altimate", name)) for (const marker of markers) writeFileSync(marker, "") From 2ae0dd30c14ec1c3adfcf4605863baebde256a53 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 04:36:08 -0800 Subject: [PATCH 31/63] fix: close the remaining telemetry opt-out review gaps - bootstrap() waits for the startup read before deciding whether to re-read. - Register the test reset hook only under a test runner. - An in-memory or empty account DB holds no organization; a non-WAL one stays unknown. - Clarify that overlapping sessions share one lifecycle. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/telemetry/config-state.ts | 8 ++++++-- packages/opencode/src/altimate/telemetry/index.ts | 10 +++++++--- packages/opencode/src/cli/bootstrap.ts | 1 + 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 50abd9535e..f1767e8030 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -114,7 +114,8 @@ async function remoteMayDisable(local: boolean | undefined): Promise { if (local === undefined && wellKnown) return true const dbPath = Database.path() - if (dbPath === ":memory:") return true + // An in-memory database starts empty each process: no organization was selected before this read. + if (dbPath === ":memory:") return false // Only read a WAL database. In rollback-journal mode even a short SELECT // takes a shared lock that can block a writer's commit. @@ -126,7 +127,10 @@ async function remoteMayDisable(local: boolean | undefined): Promise { try { const versions = Buffer.alloc(2) const { bytesRead } = await header.read(versions, 0, 2, 18) - if (bytesRead !== 2 || versions[0] !== 2 || versions[1] !== 2) return true + // A file too short for a header is new and empty: it holds no account yet. + if (bytesRead !== 2) return false + // A non-WAL database is not read (see above), so an organization it may hold is unknown: fail closed. + if (versions[0] !== 2 || versions[1] !== 2) return true } finally { await header.close() } diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 1d4eec86b1..5211e627ab 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2383,8 +2383,11 @@ export namespace Telemetry { export function bufferedCountForTest() { return buffer.length } - // The test preload resets the gate between tests through this, without importing this module. - ;(globalThis as Record)[Symbol.for("altimate.telemetry.resetGateForTest")] = resetGateForTest + // The test preload resets the gate between tests through this, without importing this module. Only + // under a test runner: in a shipped process nothing else can reopen a decided opt-out. + if (process.env.NODE_ENV === "test" || process.env.BUN_TEST) { + ;(globalThis as Record)[Symbol.for("altimate.telemetry.resetGateForTest")] = resetGateForTest + } /** Test seam: end the unreadable-config retry backoff so the next init() re-resolves. */ export function retryConfigNowForTest() { if (configRetry) configRetry.at = 0 @@ -3237,7 +3240,8 @@ export namespace Telemetry { appInsights = undefined // altimate_change start — while the opt-out is undecided nothing was flushed: keep the events for a // later init in this process to send or drop. At process exit they go with the process. Not when a - // project's own read failed: another project's decision must not send that project's events. + // project's own read failed: once its session ends, another project's decision must not send its + // events. (Sessions that overlap share one lifecycle, as before: see the docs' multi-project note.) if (gate !== "pending" || unresolvedInProject) { unresolvedInProject = false buffer = [] diff --git a/packages/opencode/src/cli/bootstrap.ts b/packages/opencode/src/cli/bootstrap.ts index 0307f7a9f9..970369eacb 100644 --- a/packages/opencode/src/cli/bootstrap.ts +++ b/packages/opencode/src/cli/bootstrap.ts @@ -21,6 +21,7 @@ export async function bootstrap(directory: string, cb: () => Promise) { // The CLI's startup telemetry init ran before this project loaded; if it could not settle the // opt-out (a remote or organization config), read it here from the full config, so a command // that starts no session does not drop an opted-in user's events. + await Telemetry.settledOptOutState() // the startup read is not awaited; let it finish first if (Telemetry.awaitingConfig()) await Telemetry.init().catch(() => {}) return cb() }) From 3855c10f7ddf4440fc46be1c97b68ec4046bae83 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 04:46:27 -0800 Subject: [PATCH 32/63] fix: settle a pending telemetry opt-out in effectCmd commands too - One Telemetry.settleInProject() step, called by both CLI project loaders. - Expose the test gate reset only when the test preload asks for it. - Docs: an admin organization config can override the global opt-out. Co-Authored-By: Claude Opus 5.5 --- docs/docs/reference/security-faq.md | 2 +- docs/docs/reference/telemetry.md | 2 +- packages/opencode/src/altimate/telemetry/index.ts | 11 +++++++++-- packages/opencode/src/cli/bootstrap.ts | 6 +----- packages/opencode/src/cli/effect-cmd.ts | 7 ++++++- packages/opencode/test/preload.ts | 3 +++ .../opencode/test/upstream/altimate-features.test.ts | 8 ++++++++ 7 files changed, 29 insertions(+), 10 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index c3f668bbd0..7e57b8cd71 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -183,7 +183,7 @@ No code, queries, file paths, or personal information is included. This event he The install scripts (`altimate.sh/install`, `install.ps1`), the npm postinstall, and the VS Code extension's installer send nothing themselves and contact no telemetry endpoint. They only record the version and installer name to a local file that the CLI reads on its next run, so the opt-out above decides whether anything is ever transmitted. -The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables and the global config are honoured process-wide from the start. +The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start, and so is the global config unless an organization config set by your admin overrides it. ## What happens when I authenticate via a well-known URL? diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index 74b66545f2..d0dfa33f4d 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -184,7 +184,7 @@ export ALTIMATE_TELEMETRY_DISABLED=true `ALTIMATE_CLI_DISABLE_TELEMETRY` and its older spelling `OPENCODE_DISABLE_TELEMETRY` are also supported. Each variable accepts `1` or `true` (case-insensitive). -When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. Until the CLI can read the setting (for example at startup, before the project config or a configured remote source that could set the flag has loaded), it sends nothing; see [Privacy](#privacy). Once a process reads the setting as disabled, that process sends nothing more, even for another project it serves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables and the global config are honoured process-wide from the start. +When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. Until the CLI can read the setting (for example at startup, before the project config or a configured remote source that could set the flag has loaded), it sends nothing; see [Privacy](#privacy). Once a process reads the setting as disabled, that process sends nothing more, even for another project it serves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start, and so is the global config unless an organization config set by your admin overrides it. ### Test runs are excluded diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 5211e627ab..fdbd7b29f0 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2336,6 +2336,13 @@ export namespace Telemetry { export function awaitingConfig() { return gate === "pending" && configRetry !== undefined } + /** For a CLI command that has just loaded its project: the startup init ran before the project + * existed, and if it could not settle the opt-out (a remote or organization config), read it now + * from the full config, so a command that starts no session neither drops nor leaks those events. */ + export async function settleInProject(): Promise { + await settledOptOutState() // the startup init is not awaited; let it finish first + if (awaitingConfig()) await init().catch(() => {}) + } /** Called each time this thread decides the opt-out, for another thread to adopt. */ export function onOptOutDecided(listener: (state: "enabled" | "disabled") => void): () => void { decisionListeners.add(listener) @@ -2384,8 +2391,8 @@ export namespace Telemetry { return buffer.length } // The test preload resets the gate between tests through this, without importing this module. Only - // under a test runner: in a shipped process nothing else can reopen a decided opt-out. - if (process.env.NODE_ENV === "test" || process.env.BUN_TEST) { + // when that preload asked for it: in a shipped process nothing else can reopen a decided opt-out. + if (process.env.ALTIMATE_TELEMETRY_TEST_HOOKS === "1") { ;(globalThis as Record)[Symbol.for("altimate.telemetry.resetGateForTest")] = resetGateForTest } /** Test seam: end the unreadable-config retry backoff so the next init() re-resolves. */ diff --git a/packages/opencode/src/cli/bootstrap.ts b/packages/opencode/src/cli/bootstrap.ts index 970369eacb..d3bac89c30 100644 --- a/packages/opencode/src/cli/bootstrap.ts +++ b/packages/opencode/src/cli/bootstrap.ts @@ -18,11 +18,7 @@ export async function bootstrap(directory: string, cb: () => Promise) { const ctx = await InstanceRuntime.load({ directory }) try { return await Instance.restore(ctx, async () => { - // The CLI's startup telemetry init ran before this project loaded; if it could not settle the - // opt-out (a remote or organization config), read it here from the full config, so a command - // that starts no session does not drop an opted-in user's events. - await Telemetry.settledOptOutState() // the startup read is not awaited; let it finish first - if (Telemetry.awaitingConfig()) await Telemetry.init().catch(() => {}) + await Telemetry.settleInProject() return cb() }) } finally { diff --git a/packages/opencode/src/cli/effect-cmd.ts b/packages/opencode/src/cli/effect-cmd.ts index 226c1cf183..ebecf8c41b 100644 --- a/packages/opencode/src/cli/effect-cmd.ts +++ b/packages/opencode/src/cli/effect-cmd.ts @@ -91,7 +91,12 @@ export const effectCmd = (opts: EffectCmdOpts) => try { // altimate_change start — preserve legacy Instance ALS for Promise-based services // still reached from Effect-native CLI handlers (for example Provider.list -> Instance.state). - await Instance.restore(ctx, () => AppRuntime.runPromise(opts.handler(args).pipe(Effect.provideService(InstanceRef, ctx)))) + // Also settle a telemetry opt-out the CLI's startup read left open (see Telemetry.settleInProject). + const { Telemetry } = await import("@/altimate/telemetry") + await Instance.restore(ctx, async () => { + await Telemetry.settleInProject() + return AppRuntime.runPromise(opts.handler(args).pipe(Effect.provideService(InstanceRef, ctx))) + }) // altimate_change end } finally { await AppRuntime.runPromise(store.dispose(ctx)) diff --git a/packages/opencode/test/preload.ts b/packages/opencode/test/preload.ts index 5ea81cf482..010237a6fc 100644 --- a/packages/opencode/test/preload.ts +++ b/packages/opencode/test/preload.ts @@ -9,6 +9,9 @@ import { afterAll } from "bun:test" import { afterEach, beforeEach } from "bun:test" // altimate_change end +// altimate_change — telemetry exposes its between-test gate reset only when this is set (see below) +process.env.ALTIMATE_TELEMETRY_TEST_HOOKS = "1" + // Set XDG env vars FIRST, before any src/ imports const dir = path.join(os.tmpdir(), "opencode-test-data-" + process.pid) await fs.mkdir(dir, { recursive: true }) diff --git a/packages/opencode/test/upstream/altimate-features.test.ts b/packages/opencode/test/upstream/altimate-features.test.ts index d3dff60f59..690ede847d 100644 --- a/packages/opencode/test/upstream/altimate-features.test.ts +++ b/packages/opencode/test/upstream/altimate-features.test.ts @@ -407,6 +407,14 @@ describe("altimate features: telemetry fail-safe init", () => { expect(config).toContain("ALTIMATE_TELEMETRY_DISABLED") }) + test("both CLI project loaders settle an opt-out the startup read left open", async () => { + // Behaviour is tested in opt-out.test.ts through bootstrap(); this pins the effectCmd loader too. + const bootstrap = await readSrc("cli", "bootstrap.ts") + const effectCmd = await readSrc("cli", "effect-cmd.ts") + expect(bootstrap).toMatch(/Instance\.restore\(ctx, async \(\) => \{\s*await Telemetry\.settleInProject\(\)\s*return cb\(\)/) + expect(effectCmd).toMatch(/Instance\.restore\(ctx, async \(\) => \{\s*await Telemetry\.settleInProject\(\)\s*return AppRuntime\.runPromise\(opts\.handler/) + }) + test("the TUI main thread adopts the worker's resolved opt-out", async () => { const tui = await readSrc("cli", "cmd", "tui.ts") const worker = await readSrc("cli", "tui", "worker.ts") From 2992168493d49d3128184a981760e4ed577c72dd Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 04:52:49 -0800 Subject: [PATCH 33/63] fix: keep a throwing opt-out listener from stopping telemetry Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/telemetry/index.ts | 8 +++++++- .../test/altimate/telemetry/opt-out.test.ts | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index fdbd7b29f0..aac1a0724a 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2326,7 +2326,13 @@ export namespace Telemetry { function decide(next: "enabled" | "disabled") { if (gate === next) return gate = next - for (const listener of decisionListeners) listener(next) + for (const listener of decisionListeners) { + try { + listener(next) + } catch { + // A listener (the TUI worker's RPC push) must not undo this thread's own decision. + } + } } /** The opt-out as this thread has resolved it. */ export function optOutState() { diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 8a7c213306..700558ae47 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -492,6 +492,23 @@ describe("telemetry opt-out", () => { } }) + test("a listener that throws does not stop this thread's telemetry", async () => { + const names = recordIngestion() + signOut() + const stop = Telemetry.onOptOutDecided(() => { + throw new Error("port closed") + }) + try { + configSpy.mockResolvedValue({}) + await Telemetry.init() + trackStartup() + await Telemetry.flush() + expect(names).toEqual(["startup_ready"]) + } finally { + stop() + } + }) + test("an opt-out adopted while this thread's own read runs still wins", async () => { const names = recordIngestion() signOut() From 7e842536906f0ed36146ad5d1f8b6889ab821fc4 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 04:55:35 -0800 Subject: [PATCH 34/63] fix: treat a global config that failed to load as an unresolved opt-out - A legacy TOML global config that fails to import, or a global load that fell back to defaults, marks the config unresolved. - A short, non-empty account database is unknown, not empty. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/telemetry/config-state.ts | 4 ++-- packages/opencode/src/config/config.ts | 20 +++++++++++++++---- packages/opencode/test/config/config.test.ts | 10 ++++++++++ 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index f1767e8030..31f017a74b 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -127,8 +127,8 @@ async function remoteMayDisable(local: boolean | undefined): Promise { try { const versions = Buffer.alloc(2) const { bytesRead } = await header.read(versions, 0, 2, 18) - // A file too short for a header is new and empty: it holds no account yet. - if (bytesRead !== 2) return false + // An empty file is new: it holds no account yet. A short non-empty one is corrupt: unknown. + if (bytesRead !== 2) return (await header.stat()).size > 0 // A non-WAL database is not read (see above), so an organization it may hold is unknown: fail closed. if (versions[0] !== 2 || versions[1] !== 2) return true } finally { diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index ff210c4e9f..5dd74bea64 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -51,9 +51,10 @@ import { withTransientReadRetry } from "@/util/effect-http-client" import { makeRuntime } from "@/effect/run-service" // altimate_change end -// altimate_change start — loaded configs whose organization remote config, which may set -// `telemetry.disabled`, could not be read: the opt-out is unknown. +// altimate_change start — loaded configs in which a source that may set `telemetry.disabled` (the +// organization remote config, a global config the loader replaced with defaults) could not be read. const configsWithUnresolvedTelemetry = new WeakSet() +const incompleteGlobals = new WeakSet() export function telemetryConfigUnresolved(config: Info): boolean { return configsWithUnresolvedTelemetry.has(config) } @@ -453,7 +454,10 @@ export const layer = Layer.effect( // altimate_change end const legacy = path.join(Global.Path.config, "config") + // altimate_change — a legacy file that fails to load may hold a telemetry opt-out + let legacyUnread = false if (existsSync(legacy)) { + legacyUnread = true yield* Effect.promise(() => import(pathToFileURL(legacy).href, { with: { type: "toml" } }) .then(async (mod) => { @@ -463,6 +467,7 @@ export const layer = Layer.effect( result["$schema"] = "https://altimate.ai/config.json" // altimate_change end result = mergeConfig(result, rest) + legacyUnread = false // altimate_change — merged; a failed migration below is harmless await fsNode.writeFile(path.join(Global.Path.config, "config.json"), JSON.stringify(result, null, 2)) await fsNode.unlink(legacy) }) @@ -470,6 +475,7 @@ export const layer = Layer.effect( ) } + if (legacyUnread) incompleteGlobals.add(result) // altimate_change return result }) @@ -478,7 +484,13 @@ export const layer = Layer.effect( Effect.tapError((error) => Effect.logError("failed to load global config, using defaults", { error: String(error) }), ), - Effect.orElseSucceed((): Info => ({})), + // altimate_change start — the defaults stand in for a global config that may opt out + Effect.orElseSucceed((): Info => { + const fallback: Info = {} + incompleteGlobals.add(fallback) + return fallback + }), + // altimate_change end ), Duration.infinity, ) @@ -913,7 +925,7 @@ export const layer = Layer.effect( // altimate_change end // altimate_change — a source that could set `telemetry.disabled` was not read - if (orgConfigUnresolved) configsWithUnresolvedTelemetry.add(result) + if (orgConfigUnresolved || incompleteGlobals.has(global)) configsWithUnresolvedTelemetry.add(result) return { config: result, diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index de5ab414e7..5ef453d96d 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -809,6 +809,16 @@ for (const failure of ["account", "organization"] as const) { ) } +it.effect("a legacy global config that fails to load leaves the telemetry opt-out unresolved", () => + withGlobalConfig({}, ({ dir }) => + Effect.gen(function* () { + yield* FSUtil.use.writeWithDirs(path.join(dir, "config"), "broken = [") + const config = yield* Config.use.get().pipe(provideInstanceEffect(dir)) + expect(Config.telemetryConfigUnresolved(config)).toBe(true) + }).pipe(Effect.provide(testInstanceStoreLayer), Effect.provide(CrossSpawnSpawner.defaultLayer)), + ), +) + it.instance("validates config schema and throws on invalid fields", () => Effect.gen(function* () { const test = yield* TestInstance From 9f4a61b512f6b2dcf9bed2f95644e81b64d2a680 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 04:57:37 -0800 Subject: [PATCH 35/63] fix: address bot review findings on the telemetry opt-out - A config loaded while the auth store was unreadable stays unresolved after repair. - Recheck the gate right before reading the machine id for the auth URL. - debug bundle: say whether the opt-out is pending or disabled. - Harden the two-project and org-recovery tests. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/debug/collect.ts | 2 +- .../opencode/src/altimate/plugin/altimate.ts | 3 +- .../src/altimate/telemetry/config-state.ts | 13 +++++- .../test/altimate/telemetry/opt-out.test.ts | 41 ++++++++++++++----- packages/opencode/test/config/config.test.ts | 1 + 5 files changed, 45 insertions(+), 15 deletions(-) diff --git a/packages/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index 529be13089..8946898d00 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -98,7 +98,7 @@ async function telemetryFacts(network: boolean): Promise { if (!network) return { enabled: false, checked: false, reason: "not started with --no-network" } try { await Telemetry.init() - return Telemetry.isEnabled() ? { enabled: true } : { enabled: false, reason: "disabled in config, or config not readable" } + return Telemetry.isEnabled() ? { enabled: true } : { enabled: false, reason: Telemetry.optOutState() === "pending" ? "config not readable yet" : "disabled in config" } } catch { return { enabled: false, checked: false, reason: "could not be determined" } } diff --git a/packages/opencode/src/altimate/plugin/altimate.ts b/packages/opencode/src/altimate/plugin/altimate.ts index 9d0d070074..31e0b9132d 100644 --- a/packages/opencode/src/altimate/plugin/altimate.ts +++ b/packages/opencode/src/altimate/plugin/altimate.ts @@ -106,7 +106,8 @@ export async function buildCliContext(machineIdPath?: string, directory?: string } } let machineId = "" - if (!disabled) { + // An opt-out adopted while the config was read still wins. + if (!disabled && Telemetry.optOutState() !== "disabled") { // getOrCreateMachineId returns "" on all error conditions (ENOENT excluded — // it mints a new UUID instead) and logs appropriately; no try/catch needed. machineId = getOrCreateMachineId(machineIdPath) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 31f017a74b..3b4b3da383 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -90,12 +90,21 @@ export function instanceDirectory(): string | undefined { } /** The opt-out from the full config; throws where `Config` cannot load (outside an Instance). */ +// Loaded configs built while the auth store could not be read: they lack its well-known remote +// configs even after the store is repaired, until the app reloads its config. +const loadedWithoutAuth = new WeakSet() + export async function loadedState(): Promise { const config = await Config.get() - if (Config.telemetryConfigUnresolved(config)) return "unreadable" + if (Config.telemetryConfigUnresolved(config) || loadedWithoutAuth.has(config)) return "unreadable" // Auth.all() returns an empty store when its read or parse fails, hiding well-known remote config. // Called only for that throw (an unparseable auth file); its result does not matter here. - await hasWellKnownAuth() + try { + await hasWellKnownAuth() + } catch (error) { + loadedWithoutAuth.add(config) + throw error + } return config.telemetry?.disabled ? "disabled" : "enabled" } diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 700558ae47..e849f9e1b7 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -742,6 +742,21 @@ describe("telemetry opt-out", () => { expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") }) + test("a config loaded while the auth store was unreadable stays unresolved after the store is repaired", async () => { + const loaded = {} as Awaited> + configSpy.mockResolvedValue(loaded) + writeFileSync(Auth.filepath(), "{") + await expect(TelemetryConfig.loadedState()).rejects.toThrow() + // Repaired with a well-known login: the cached config never read that login's remote config. + writeFileSync(Auth.filepath(), JSON.stringify({ + "https://config.example.invalid": { type: "wellknown", key: "TEST_CONFIG_TOKEN", token: "test-token" }, + })) + expect(await TelemetryConfig.loadedState()).toBe("unreadable") + // A config the app loads afresh is read as usual. + configSpy.mockResolvedValue({}) + expect(await TelemetryConfig.loadedState()).toBe("enabled") + }) + test("the opt-out marker files earlier versions wrote are removed", async () => { const markers = ["telemetry-opted-out", "telemetry-opted-out.sending"].map((name) => path.join(home, ".altimate", name)) for (const marker of markers) writeFileSync(marker, "") @@ -797,17 +812,21 @@ describe("telemetry opt-out", () => { Telemetry.track(errorEvent("A2")) }, }) - await aStarted - await Instance.provide({ - directory: b.path, - fn: async () => { - await Telemetry.init() - enabledDuringTurns.push(Telemetry.isEnabled()) - Telemetry.track(errorEvent("B1")) - }, - }) - releaseA() - await turnA + // A failing turn A rejects the wait instead of leaving it hanging. + await Promise.race([aStarted, turnA.then(() => Promise.reject(new Error("turn A ended before starting")))]) + try { + await Instance.provide({ + directory: b.path, + fn: async () => { + await Telemetry.init() + enabledDuringTurns.push(Telemetry.isEnabled()) + Telemetry.track(errorEvent("B1")) + }, + }) + } finally { + releaseA() + await turnA + } await Telemetry.flush() expect(enabledDuringTurns).toEqual([true, true]) diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 5ef453d96d..fe5e71d41d 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -745,6 +745,7 @@ for (const failure of ["account", "organization"] as const) { { APPLICATIONINSIGHTS_CONNECTION_STRING: "InstrumentationKey=test;IngestionEndpoint=https://ingest.example.invalid/", ALTIMATE_TELEMETRY_DISABLED: undefined, + OPENCODE_AUTH_CONTENT: undefined, ALTIMATE_CLI_DISABLE_TELEMETRY: undefined, OPENCODE_DISABLE_TELEMETRY: undefined, }, From 972171878c398e67e32961f90437bef8a11550cf Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:01:31 -0800 Subject: [PATCH 36/63] fix: keep old opt-out markers and pin the mid-flush abort test - Stop deleting the old opt-out marker files: on a downgrade, the older CLI would send its farewell event again. - The abort test uses a long flush budget and checks the abort happened inside adoptOptOut. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/telemetry/index.ts | 17 ----------------- .../test/altimate/telemetry/opt-out.test.ts | 15 ++++----------- 2 files changed, 4 insertions(+), 28 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index aac1a0724a..60c07c0992 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -15,7 +15,6 @@ import fs from "fs" import path from "path" import os from "os" import { fileLog } from "@/altimate/util/file-log" -import { Global } from "../../global" // altimate_change — test-isolated home for the legacy marker cleanup const log = Log.create({ service: "telemetry" }) @@ -2386,7 +2385,6 @@ export namespace Telemetry { configRetry = undefined unresolvedInProject = false adopted = undefined - legacyMarkersRemoved = false if (initDone && enabled) return gate = "pending" buffer = [] @@ -2643,23 +2641,8 @@ export namespace Telemetry { } // altimate_change end - // altimate_change start — the opt-out marker files earlier versions wrote are no longer read - let legacyMarkersRemoved = false - function removeLegacyOptOutMarkers() { - if (legacyMarkersRemoved) return - legacyMarkersRemoved = true - for (const name of ["telemetry-opted-out", "telemetry-opted-out.sending"]) { - try { - fs.rmSync(path.join(Global.Path.home, ".altimate", name), { force: true, recursive: true }) - } catch { - // Best effort: a leftover marker is harmless. - } - } - } - // altimate_change end async function doInit() { - removeLegacyOptOutMarkers() // altimate_change // altimate_change — an unreadable config leaves this init unfinished, so the next init() retries. let unresolved = false try { diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index e849f9e1b7..aca3b35aa7 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -681,11 +681,13 @@ describe("telemetry opt-out", () => { configSpy.mockResolvedValue({}) await Telemetry.init() trackStartup() - const flushing = Telemetry.flush() + // A long request budget, so only the opt-out can abort the batch (not the flush's own timeout). + const flushing = Telemetry.flush(600_000) await inFlight await Telemetry.adoptOptOut("disabled") - await flushing + // Aborted by adoptOptOut itself, before it returned. expect(aborted).toBe(true) + await flushing }) test("a command that loads a project settles an opt-out the startup read left open", async () => { @@ -757,15 +759,6 @@ describe("telemetry opt-out", () => { expect(await TelemetryConfig.loadedState()).toBe("enabled") }) - test("the opt-out marker files earlier versions wrote are removed", async () => { - const markers = ["telemetry-opted-out", "telemetry-opted-out.sending"].map((name) => path.join(home, ".altimate", name)) - for (const marker of markers) writeFileSync(marker, "") - signOut() - configSpy.mockResolvedValue({}) - await Telemetry.init() - expect(markers.filter((marker) => existsSync(marker))).toEqual([]) - }) - test("the retry throttle still applies after an earlier session enabled telemetry", async () => { recordIngestion() signOut() From 42bed3ad474104c577f176e2d8b7f959615753c1 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:06:41 -0800 Subject: [PATCH 37/63] fix: keep an enabled telemetry decision across reads that cannot see it - Outside a project, an unreadable file read keeps an enabled decision a full config made; a file opt-out still wins. - Re-read auth.json once before treating it as unreadable (Auth.set is not atomic). - Ignore a worker enabled answer that arrives during shutdown. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/telemetry/config-state.ts | 7 +++++- .../opencode/src/altimate/telemetry/index.ts | 9 ++++++-- .../test/altimate/telemetry/opt-out.test.ts | 23 +++++++++++++++++-- 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 3b4b3da383..4bb10b6bd9 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -93,6 +93,7 @@ export function instanceDirectory(): string | undefined { // Loaded configs built while the auth store could not be read: they lack its well-known remote // configs even after the store is repaired, until the app reloads its config. const loadedWithoutAuth = new WeakSet() +const AUTH_REREAD_MS = 100 export async function loadedState(): Promise { const config = await Config.get() @@ -100,7 +101,11 @@ export async function loadedState(): Promise { // Auth.all() returns an empty store when its read or parse fails, hiding well-known remote config. // Called only for that throw (an unparseable auth file); its result does not matter here. try { - await hasWellKnownAuth() + await hasWellKnownAuth().catch(async () => { + // Auth.set truncates then writes, so a read can land mid-write: look again before deciding. + await new Promise((resolve) => setTimeout(resolve, AUTH_REREAD_MS)) + return hasWellKnownAuth() + }) } catch (error) { loadedWithoutAuth.add(config) throw error diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 60c07c0992..1e556e255c 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2375,7 +2375,8 @@ export namespace Telemetry { activeFlushAbort?.abort() // a batch already taken must not post after the opt-out return Promise.resolve() } - if (gate !== "pending") return Promise.resolve() + // Not during a shutdown: a re-init chained behind the exit flush would start a lifecycle nobody ends. + if (gate !== "pending" || shutdownPromise) return Promise.resolve() adopted = "enabled" return (initPromise ?? Promise.resolve()).catch(() => {}).then(() => init()) } @@ -2654,7 +2655,11 @@ export namespace Telemetry { droppedEvents = 0 return } - const state = adopted ?? (await TelemetryConfig.resolve(configDirectory)) + let state = adopted ?? (await TelemetryConfig.resolve(configDirectory)) + // Outside an Instance only the files can be read. Where they cannot settle it (a remote or + // organization config), an enabled decision a full config already made in this process stands; + // an opt-out the files do show still wins. + if (state === "unreadable" && gate === "enabled" && !TelemetryConfig.instanceDirectory()) state = "enabled" // Another thread's opt-out may have been adopted while the read ran: it still wins. if (state === "disabled" || optOutState() === "disabled") { decide("disabled") diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index aca3b35aa7..5c4dd9322c 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -509,6 +509,24 @@ describe("telemetry opt-out", () => { } }) + test("an enabled decision from the full config stands for later inits outside a project", async () => { + const names = recordIngestion() + signOut() + wellKnownAuth() // the files alone cannot settle this user's opt-out + await using dir = await tmpdir({ git: true }) + configSpy.mockResolvedValue({}) + await Instance.provide({ directory: dir.path, fn: () => Telemetry.init() }) + expect(Telemetry.optOutState()).toBe("enabled") + await Telemetry.shutdown() + + // Between sessions, outside any project. + trackStartup() + await Telemetry.init() + expect(Telemetry.isEnabled()).toBe(true) + await Telemetry.flush() + expect(names).toEqual(["startup_ready"]) + }) + test("an opt-out adopted while this thread's own read runs still wins", async () => { const names = recordIngestion() signOut() @@ -759,7 +777,7 @@ describe("telemetry opt-out", () => { expect(await TelemetryConfig.loadedState()).toBe("enabled") }) - test("the retry throttle still applies after an earlier session enabled telemetry", async () => { + test("after a session enabled telemetry, an unreadable read outside a project keeps that decision", async () => { recordIngestion() signOut() configSpy.mockResolvedValue({}) @@ -769,7 +787,8 @@ describe("telemetry opt-out", () => { configSpy.mockRejectedValue(new Error("InstanceRef not provided")) process.env.OPENCODE_CONFIG_CONTENT = "{" const reads = configSpy.mock.calls.length - for (let i = 0; i < 5; i++) await Telemetry.init() + await Telemetry.init() + expect(Telemetry.isEnabled()).toBe(true) expect(configSpy.mock.calls.length - reads).toBe(1) }) From 52a0466769a796990a487fa7b2fd66f18688ba11 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:27:08 -0800 Subject: [PATCH 38/63] fix: throttle the shutdown re-init and narrow the auth mark - The re-init queued behind a shutdown goes through the instance-less retry throttle. - One failed auth read no longer marks a config already read alongside a readable store. - Drop the unreachable defaults-fallback mark; debug bundle names a missing sink. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/debug/collect.ts | 8 +++++++- .../opencode/src/altimate/telemetry/config-state.ts | 5 ++++- packages/opencode/src/altimate/telemetry/index.ts | 11 +++++++---- packages/opencode/src/config/config.ts | 10 ++-------- .../opencode/test/altimate/telemetry/opt-out.test.ts | 6 +++++- 5 files changed, 25 insertions(+), 15 deletions(-) diff --git a/packages/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index 8946898d00..4de8c1d127 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -92,13 +92,19 @@ function envFlags(): string[] { /** With `network`, telemetry has been started by the CLI; its start is awaited here so the answer is not read * before it settles. Without, it is not started (it would send), so only the environment switches are checked. */ +function optOutReason(state: "pending" | "enabled" | "disabled") { + if (state === "pending") return "config not readable yet" + if (state === "disabled") return "disabled in config" + return "no telemetry sink (test runner or invalid connection string)" +} + async function telemetryFacts(network: boolean): Promise { const optOut = TelemetryConfig.disablingEnvironmentVariable() if (optOut) return { enabled: false, reason: `${optOut} is set` } if (!network) return { enabled: false, checked: false, reason: "not started with --no-network" } try { await Telemetry.init() - return Telemetry.isEnabled() ? { enabled: true } : { enabled: false, reason: Telemetry.optOutState() === "pending" ? "config not readable yet" : "disabled in config" } + return Telemetry.isEnabled() ? { enabled: true } : { enabled: false, reason: optOutReason(Telemetry.optOutState()) } } catch { return { enabled: false, checked: false, reason: "could not be determined" } } diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 4bb10b6bd9..3f56ab70e1 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -93,6 +93,8 @@ export function instanceDirectory(): string | undefined { // Loaded configs built while the auth store could not be read: they lack its well-known remote // configs even after the store is repaired, until the app reloads its config. const loadedWithoutAuth = new WeakSet() +// Loaded configs already read alongside a readable auth store: a later failed read is transient. +const readWithAuth = new WeakSet() const AUTH_REREAD_MS = 100 export async function loadedState(): Promise { @@ -107,9 +109,10 @@ export async function loadedState(): Promise { return hasWellKnownAuth() }) } catch (error) { - loadedWithoutAuth.add(config) + if (!readWithAuth.has(config)) loadedWithoutAuth.add(config) throw error } + readWithAuth.add(config) return config.telemetry?.disabled ? "disabled" : "enabled" } diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 1e556e255c..b10488c0e4 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2600,7 +2600,7 @@ export namespace Telemetry { if (!reinitPromise) { const chained: Promise = shutdownPromise .catch(() => {}) - .then(doInit) + .then(() => (retryThrottled() ? undefined : doInit())) // altimate_change — the throttle applies here too .then(() => releaseUnresolved(chained)) // altimate_change — see releaseUnresolved .finally(() => { reinitPromise = undefined @@ -2624,9 +2624,7 @@ export namespace Telemetry { // CONFIG_RETRY_MS. Inside an Instance a read is the Instance's cached config (its own reloads keep // it current), so every init reads it: one project's unreadable config never holds up another's. // An opt-out adopted from another thread needs no read. - if (!initPromise && !adopted && configRetry && Date.now() < configRetry.at && !TelemetryConfig.instanceDirectory()) { - return Promise.resolve() - } + if (!initPromise && retryThrottled()) return Promise.resolve() if (!initPromise) { const started: Promise = doInit().then(() => releaseUnresolved(started)) initPromise = started @@ -2635,6 +2633,11 @@ export namespace Telemetry { // altimate_change end } + // altimate_change — an unreadable config is re-read outside an Instance at most every CONFIG_RETRY_MS + function retryThrottled() { + return !adopted && configRetry !== undefined && Date.now() < configRetry.at && !TelemetryConfig.instanceDirectory() + } + // altimate_change start — an init left unresolved stays pre-init so the next init() retries; only // the init that still owns initPromise unpublishes it (not a re-init published during a shutdown) function releaseUnresolved(owner: Promise) { diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 5dd74bea64..fb824006ec 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -52,7 +52,7 @@ import { makeRuntime } from "@/effect/run-service" // altimate_change end // altimate_change start — loaded configs in which a source that may set `telemetry.disabled` (the -// organization remote config, a global config the loader replaced with defaults) could not be read. +// organization remote config, a legacy global config that failed to import) could not be read. const configsWithUnresolvedTelemetry = new WeakSet() const incompleteGlobals = new WeakSet() export function telemetryConfigUnresolved(config: Info): boolean { @@ -484,13 +484,7 @@ export const layer = Layer.effect( Effect.tapError((error) => Effect.logError("failed to load global config, using defaults", { error: String(error) }), ), - // altimate_change start — the defaults stand in for a global config that may opt out - Effect.orElseSucceed((): Info => { - const fallback: Info = {} - incompleteGlobals.add(fallback) - return fallback - }), - // altimate_change end + Effect.orElseSucceed((): Info => ({})), ), Duration.infinity, ) diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 5c4dd9322c..2275b0ad5d 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -495,7 +495,9 @@ describe("telemetry opt-out", () => { test("a listener that throws does not stop this thread's telemetry", async () => { const names = recordIngestion() signOut() + let listenerCalled = false const stop = Telemetry.onOptOutDecided(() => { + listenerCalled = true throw new Error("port closed") }) try { @@ -503,6 +505,7 @@ describe("telemetry opt-out", () => { await Telemetry.init() trackStartup() await Telemetry.flush() + expect(listenerCalled).toBe(true) expect(names).toEqual(["startup_ready"]) } finally { stop() @@ -593,7 +596,8 @@ describe("telemetry opt-out", () => { // A caller arriving now joins the re-init instead of starting a second one. expect(Telemetry.init()).toBe(reinit) await reinit - expect(Telemetry.optOutState()).toBe("enabled") + // The re-init is throttled like any instance-less retry, so the opt-out stays undecided. + expect(Telemetry.optOutState()).toBe("pending") }) test("one project's unreadable config never holds up an opted-in project's next session", async () => { From 921baac2fc6fea9670777a00310cefac5ebae359 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:29:08 -0800 Subject: [PATCH 39/63] test: make the outside-project read unreadable in the enabled-reuse test Co-Authored-By: Claude Opus 5.5 --- packages/opencode/test/altimate/telemetry/opt-out.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 2275b0ad5d..bdc4780634 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -522,7 +522,10 @@ describe("telemetry opt-out", () => { expect(Telemetry.optOutState()).toBe("enabled") await Telemetry.shutdown() - // Between sessions, outside any project. + // Between sessions, outside any project: the full config cannot load here, and the files alone + // read as unreadable (a well-known login), so only the earlier enabled decision keeps it on. + configSpy.mockRejectedValue(new Error("InstanceRef not provided")) + expect(await TelemetryConfig.resolve(home)).toBe("unreadable") trackStartup() await Telemetry.init() expect(Telemetry.isEnabled()).toBe(true) From 78be48c6f3dd869dae9cca8c99defe9249f98d76 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:32:16 -0800 Subject: [PATCH 40/63] fix: treat an in-memory account database as an unknown organization source Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/telemetry/config-state.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 3f56ab70e1..e2d271ebe0 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -131,8 +131,9 @@ async function remoteMayDisable(local: boolean | undefined): Promise { if (local === undefined && wellKnown) return true const dbPath = Database.path() - // An in-memory database starts empty each process: no organization was selected before this read. - if (dbPath === ":memory:") return false + // An in-memory database belongs to the connection that opened it: this probe cannot see whether an + // organization was selected there, so the answer is unknown. + if (dbPath === ":memory:") return true // Only read a WAL database. In rollback-journal mode even a short SELECT // takes a shared lock that can block a writer's commit. From bda0166e56c8c2a1a54211e643c96ad215c9a39e Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:36:59 -0800 Subject: [PATCH 41/63] fix: close the last telemetry opt-out review notes - An empty auth file holds no well-known entry, as Auth reads it. - A throttled init restarts the stall monitor a shutdown stopped. - settleInProject returns at once when the opt-out is decided and idle. - Tidy debug/collect imports and doc placement. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/debug/collect.ts | 6 +++--- packages/opencode/src/altimate/telemetry/config-state.ts | 3 ++- packages/opencode/src/altimate/telemetry/index.ts | 8 ++++++-- packages/opencode/test/altimate/telemetry/opt-out.test.ts | 5 +++++ 4 files changed, 16 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index 4de8c1d127..e266d15322 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -6,7 +6,6 @@ * names or hosts before they leave this file. */ import fs from "fs" -import { TelemetryConfig } from "@/altimate/telemetry/config-state" import os from "os" import path from "path" import dns from "dns/promises" @@ -16,6 +15,7 @@ import { Global } from "@opencode-ai/core/global" import { InstallationVersion } from "@opencode-ai/core/installation/version" import { resolveInstall } from "@/installation" import { Telemetry } from "@/altimate/telemetry" +import { TelemetryConfig } from "@/altimate/telemetry/config-state" import { AltimateApi } from "@/altimate/api/client" import * as Registry from "@/altimate/native/connections/registry" import { resolveConfig } from "@/altimate/native/connections/credential-store" @@ -90,14 +90,14 @@ function envFlags(): string[] { }) } -/** With `network`, telemetry has been started by the CLI; its start is awaited here so the answer is not read - * before it settles. Without, it is not started (it would send), so only the environment switches are checked. */ function optOutReason(state: "pending" | "enabled" | "disabled") { if (state === "pending") return "config not readable yet" if (state === "disabled") return "disabled in config" return "no telemetry sink (test runner or invalid connection string)" } +/** With `network`, telemetry has been started by the CLI; its start is awaited here so the answer is not read + * before it settles. Without, it is not started (it would send), so only the environment switches are checked. */ async function telemetryFacts(network: boolean): Promise { const optOut = TelemetryConfig.disablingEnvironmentVariable() if (optOut) return { enabled: false, reason: `${optOut} is set` } diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index e2d271ebe0..c17c347977 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -77,7 +77,8 @@ async function hasWellKnownAuth(): Promise { throw error } // Unparseable: a well-known entry may be behind it. `Config` would load without its remote config. - parsed = JSON.parse(contents) + // An empty file (touched, or a crash between Auth.set's truncate and write) holds no entry, as Auth reads it. + parsed = contents.trim() === "" ? {} : JSON.parse(contents) } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Unreadable auth store") return Object.values(parsed).some( diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index b10488c0e4..40089d97d7 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2345,6 +2345,7 @@ export namespace Telemetry { * existed, and if it could not settle the opt-out (a remote or organization config), read it now * from the full config, so a command that starts no session neither drops nor leaks those events. */ export async function settleInProject(): Promise { + if (gate !== "pending" && !initPromise) return // decided and idle: nothing to wait for await settledOptOutState() // the startup init is not awaited; let it finish first if (awaitingConfig()) await init().catch(() => {}) } @@ -2600,7 +2601,7 @@ export namespace Telemetry { if (!reinitPromise) { const chained: Promise = shutdownPromise .catch(() => {}) - .then(() => (retryThrottled() ? undefined : doInit())) // altimate_change — the throttle applies here too + .then(() => (retryThrottled() ? startLoopMonitor() : doInit())) // altimate_change — the throttle applies here too .then(() => releaseUnresolved(chained)) // altimate_change — see releaseUnresolved .finally(() => { reinitPromise = undefined @@ -2624,7 +2625,10 @@ export namespace Telemetry { // CONFIG_RETRY_MS. Inside an Instance a read is the Instance's cached config (its own reloads keep // it current), so every init reads it: one project's unreadable config never holds up another's. // An opt-out adopted from another thread needs no read. - if (!initPromise && retryThrottled()) return Promise.resolve() + if (!initPromise && retryThrottled()) { + startLoopMonitor() // a shutdown stopped it; the stall watcher runs whether or not telemetry does + return Promise.resolve() + } if (!initPromise) { const started: Promise = doInit().then(() => releaseUnresolved(started)) initPromise = started diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index bdc4780634..316b2bc8fd 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -760,6 +760,11 @@ describe("telemetry opt-out", () => { } }) + test("an empty auth file holds no well-known entry, as Auth reads it", async () => { + writeFileSync(Auth.filepath(), "") + expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + }) + test("auth content that does not parse falls back to the auth file, as Auth does", async () => { process.env.OPENCODE_AUTH_CONTENT = "{" expect(await TelemetryConfig.disabledState(home)).toBe("enabled") From b55ee9be8f8da8836ddbfc21f48dc9fcde7909c1 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:45:02 -0800 Subject: [PATCH 42/63] fix: let a file opt-out win even when an organization is selected - The files setting telemetry.disabled now read as disabled, not unreadable, so an earlier enabled decision cannot override it (fail closed). - debug bundle: clearer reason when telemetry is not running. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/debug/collect.ts | 2 +- .../src/altimate/telemetry/config-state.ts | 4 ++- .../test/altimate/telemetry/opt-out.test.ts | 29 +++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/debug/collect.ts b/packages/opencode/src/altimate/debug/collect.ts index e266d15322..fc8ab693a0 100644 --- a/packages/opencode/src/altimate/debug/collect.ts +++ b/packages/opencode/src/altimate/debug/collect.ts @@ -93,7 +93,7 @@ function envFlags(): string[] { function optOutReason(state: "pending" | "enabled" | "disabled") { if (state === "pending") return "config not readable yet" if (state === "disabled") return "disabled in config" - return "no telemetry sink (test runner or invalid connection string)" + return "not running in this process (no telemetry sink, or this session's config not resolved yet)" } /** With `network`, telemetry has been started by the CLI; its start is awaited here so the answer is not read diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index c17c347977..dfe97671b8 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -264,8 +264,10 @@ export async function disabledState(directory: string = process.cwd()): Promise< if (managed) await readText(managed.text, managed.source, path.dirname(managed.source)) if (unknown) return "unreadable" + // The files themselves opt out: that stands, even if a remote config might turn it back on (fail closed). + if (value === true) return "disabled" if (!managedSetting && (await remoteMayDisable(value))) return "unreadable" - return value === true ? "disabled" : "enabled" + return "enabled" } catch { return "unreadable" } diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 316b2bc8fd..b1a55e2fd6 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -533,6 +533,35 @@ describe("telemetry opt-out", () => { expect(names).toEqual(["startup_ready"]) }) + test("a file opt-out added mid-process wins over an earlier enabled decision, even with an organization selected", async () => { + const names = recordIngestion() + signOut() + const dbPath = path.join(home, "account.db") + const db = new SQLite(dbPath) + db.exec(` + PRAGMA journal_mode = WAL; + CREATE TABLE account (id TEXT PRIMARY KEY); + CREATE TABLE account_state (id INTEGER PRIMARY KEY, active_account_id TEXT, active_org_id TEXT); + INSERT INTO account VALUES ('account'); + INSERT INTO account_state VALUES (1, 'account', 'org'); + `) + db.close() + databaseSpy.mockReturnValue(dbPath) + await using dir = await tmpdir({ git: true }) + configSpy.mockResolvedValue({}) + await Instance.provide({ directory: dir.path, fn: () => Telemetry.init() }) + expect(Telemetry.optOutState()).toBe("enabled") + await Telemetry.shutdown() + + configSpy.mockRejectedValue(new Error("InstanceRef not provided")) + process.env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ telemetry: { disabled: true } }) + trackStartup() + await Telemetry.init() + await Telemetry.flush() + expect(Telemetry.optOutState()).toBe("disabled") + expect(names).toEqual([]) + }) + test("an opt-out adopted while this thread's own read runs still wins", async () => { const names = recordIngestion() signOut() From 1ada8a7fa1c82cea02ff0a3685e49c26ac026db8 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:52:30 -0800 Subject: [PATCH 43/63] fix: ask SQLite for URI parsing when reading a closed account database - Linux builds of SQLite parse file: URIs only when asked (SQLITE_OPEN_URI); without it the immutable read failed and held opted-in users. - The org-selected file opt-out test first proves the organization path is active. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/telemetry/config-state.ts | 5 +++-- packages/opencode/test/altimate/telemetry/opt-out.test.ts | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index dfe97671b8..64cb492ffb 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -1,4 +1,4 @@ -import { Database as SQLite } from "bun:sqlite" +import { Database as SQLite, constants as SQLiteConstants } from "bun:sqlite" import path from "path" import fs from "fs/promises" import { existsSync } from "fs" @@ -159,7 +159,8 @@ async function remoteMayDisable(local: boolean | undefined): Promise { // no writer is attached, so read it as immutable (which reports its journal mode as "delete"). const immutable = !existsSync(`${dbPath}-wal`) const db = immutable - ? new SQLite(`${pathToFileURL(dbPath).href}?immutable=1`, { readonly: true }) // escapes `#`, `?`, `%` + ? // escapes `#`, `?`, `%`; URI parsing must be asked for explicitly where SQLite is built without it (Linux) + new SQLite(`${pathToFileURL(dbPath).href}?immutable=1`, SQLiteConstants.SQLITE_OPEN_READONLY | SQLiteConstants.SQLITE_OPEN_URI) : new SQLite(dbPath, { readonly: true }) try { db.exec("PRAGMA busy_timeout = 0") diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index b1a55e2fd6..d0bac00f71 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -554,7 +554,11 @@ describe("telemetry opt-out", () => { await Telemetry.shutdown() configSpy.mockRejectedValue(new Error("InstanceRef not provided")) + // The selected organization makes the files alone inconclusive... + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") + // ...until the files themselves opt out. process.env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ telemetry: { disabled: true } }) + expect(await TelemetryConfig.disabledState(home)).toBe("disabled") trackStartup() await Telemetry.init() await Telemetry.flush() From 9729433fb412f934f1668954a8b9ad92517a198c Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 05:56:19 -0800 Subject: [PATCH 44/63] test: cover the remaining telemetry opt-out guards - Tests for the in-memory and non-WAL account database guards and the late opt-out check in buildCliContext. - Count only auth entries Auth accepts as well-known logins. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/telemetry/config-state.ts | 10 +++++--- .../test/altimate/altimate-plugin.test.ts | 20 +++++++++++++++ .../test/altimate/telemetry/opt-out.test.ts | 25 +++++++++++++++++++ 3 files changed, 52 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 64cb492ffb..82bfeaa0e4 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -4,6 +4,7 @@ import fs from "fs/promises" import { existsSync } from "fs" import { pathToFileURL } from "url" import * as Effect from "effect/Effect" +import { Option, Schema } from "effect" import { InstanceRef } from "@/effect/instance-ref" import { attach } from "@/effect/run-service" import { Flag, env as flagEnv } from "@opencode-ai/core/flag/flag" @@ -81,10 +82,13 @@ async function hasWellKnownAuth(): Promise { parsed = contents.trim() === "" ? {} : JSON.parse(contents) } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Unreadable auth store") - return Object.values(parsed).some( - (entry) => entry && typeof entry === "object" && (entry as { type?: unknown }).type === "wellknown", - ) + // Only entries Auth itself accepts: Config never fetches a malformed one. + return Object.values(parsed).some((entry) => { + const decoded = decodeAuthEntry(entry) + return Option.isSome(decoded) && decoded.value.type === "wellknown" + }) } +const decodeAuthEntry = Schema.decodeUnknownOption(Auth.Info) export function instanceDirectory(): string | undefined { return Effect.runSync(attach(InstanceRef))?.directory diff --git a/packages/opencode/test/altimate/altimate-plugin.test.ts b/packages/opencode/test/altimate/altimate-plugin.test.ts index 85a1188e2a..880ebb8900 100644 --- a/packages/opencode/test/altimate/altimate-plugin.test.ts +++ b/packages/opencode/test/altimate/altimate-plugin.test.ts @@ -118,6 +118,26 @@ describe("buildCliContext", () => { expect(await contextHasMachineId()).toBe(false) }) + test("omits machine_id when this process adopts an opt-out while the config is read", async () => { + delete process.env.ALTIMATE_TELEMETRY_DISABLED + let release!: (value: unknown) => void + let started!: () => void + const reading = new Promise((resolve) => (started = resolve)) + cfg.mockImplementation((() => { + started() + return new Promise((resolve) => (release = resolve)) + }) as never) + await using dir = await tmpdir() + const idPath = path.join(dir.path, "machine-id") + fs.writeFileSync(idPath, VALID_UUID, "utf8") + const building = buildCliContext(idPath) + await reading + await Telemetry.adoptOptOut("disabled") + release({}) + const ctx = JSON.parse(Buffer.from(await building, "base64url").toString("utf8")) as Record + expect(Object.prototype.hasOwnProperty.call(ctx, "machine_id")).toBe(false) + }) + test("inside a project, omits machine_id when a remote config source could not be read", async () => { delete process.env.ALTIMATE_TELEMETRY_DISABLED await using project = await tmpdir({ git: true }) diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index d0bac00f71..985ef4b870 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -793,6 +793,31 @@ describe("telemetry opt-out", () => { } }) + test("a well-known entry Auth would reject does not hold telemetry", async () => { + writeFileSync(Auth.filepath(), JSON.stringify({ "https://config.example.invalid": { type: "wellknown" } })) + expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + }) + + test("an in-memory account database is an unknown organization source", async () => { + databaseSpy.mockReturnValue(":memory:") + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") + }) + + test("an account database not in WAL mode is not read, so its organization is unknown", async () => { + const dbPath = path.join(home, "account.db") + const db = new SQLite(dbPath) + db.exec(` + PRAGMA journal_mode = DELETE; + CREATE TABLE account (id TEXT PRIMARY KEY); + CREATE TABLE account_state (id INTEGER PRIMARY KEY, active_account_id TEXT, active_org_id TEXT); + INSERT INTO account VALUES ('account'); + INSERT INTO account_state VALUES (1, 'account', NULL); + `) + db.close() + databaseSpy.mockReturnValue(dbPath) + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") + }) + test("an empty auth file holds no well-known entry, as Auth reads it", async () => { writeFileSync(Auth.filepath(), "") expect(await TelemetryConfig.disabledState(home)).toBe("enabled") From d38ebd4bb5351527ece8d253a3857952fb8044ad Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:02:19 -0800 Subject: [PATCH 45/63] fix: let a readable telemetry opt-out stand when another config source failed Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/telemetry/config-state.ts | 2 ++ .../opencode/test/altimate/telemetry/opt-out.test.ts | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 82bfeaa0e4..2ad8fbe97a 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -104,6 +104,8 @@ const AUTH_REREAD_MS = 100 export async function loadedState(): Promise { const config = await Config.get() + // An opt-out the readable sources already set stands, even if another source could not be read. + if (config.telemetry?.disabled === true) return "disabled" if (Config.telemetryConfigUnresolved(config) || loadedWithoutAuth.has(config)) return "unreadable" // Auth.all() returns an empty store when its read or parse fails, hiding well-known remote config. // Called only for that throw (an unparseable auth file); its result does not matter here. diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 985ef4b870..8148c98f22 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -179,6 +179,16 @@ describe("telemetry opt-out", () => { await expectSilentLifecycle() }) + test("an opt-out in the readable config stands even when an organization config load failed", async () => { + configSpy.mockResolvedValue({ telemetry: { disabled: true } } as Awaited>) + const unresolved = spyOn(Config, "telemetryConfigUnresolved").mockReturnValue(true) + try { + expect(await TelemetryConfig.loadedState()).toBe("disabled") + } finally { + unresolved.mockRestore() + } + }) + test("a partial config cannot enable telemetry after an organization config load failed", async () => { configSpy.mockResolvedValue({} as Awaited>) const unresolved = spyOn(Config, "telemetryConfigUnresolved").mockReturnValue(true) From cfff9f85ed00ea8246c83c6375ae64de115acef7 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:03:56 -0800 Subject: [PATCH 46/63] fix: count raw well-known auth entries again so the probe fails closed Auth passes OPENCODE_AUTH_CONTENT through without schema decoding, so Config can fetch remote config for a raw entry; the probe must hold for it too. Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/telemetry/config-state.ts | 12 +++++------- .../opencode/test/altimate/telemetry/opt-out.test.ts | 6 +++--- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 2ad8fbe97a..fb262efe59 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -4,7 +4,6 @@ import fs from "fs/promises" import { existsSync } from "fs" import { pathToFileURL } from "url" import * as Effect from "effect/Effect" -import { Option, Schema } from "effect" import { InstanceRef } from "@/effect/instance-ref" import { attach } from "@/effect/run-service" import { Flag, env as flagEnv } from "@opencode-ai/core/flag/flag" @@ -82,13 +81,12 @@ async function hasWellKnownAuth(): Promise { parsed = contents.trim() === "" ? {} : JSON.parse(contents) } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Unreadable auth store") - // Only entries Auth itself accepts: Config never fetches a malformed one. - return Object.values(parsed).some((entry) => { - const decoded = decodeAuthEntry(entry) - return Option.isSome(decoded) && decoded.value.type === "wellknown" - }) + // Any well-known-typed entry counts: Auth passes OPENCODE_AUTH_CONTENT through without decoding it, so + // Config can fetch remote config even for an entry the file path would reject (fail closed). + return Object.values(parsed).some( + (entry) => entry && typeof entry === "object" && (entry as { type?: unknown }).type === "wellknown", + ) } -const decodeAuthEntry = Schema.decodeUnknownOption(Auth.Info) export function instanceDirectory(): string | undefined { return Effect.runSync(attach(InstanceRef))?.directory diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 8148c98f22..699d056012 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -803,9 +803,9 @@ describe("telemetry opt-out", () => { } }) - test("a well-known entry Auth would reject does not hold telemetry", async () => { - writeFileSync(Auth.filepath(), JSON.stringify({ "https://config.example.invalid": { type: "wellknown" } })) - expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + test("a raw well-known entry in OPENCODE_AUTH_CONTENT holds telemetry, as Config can still fetch for it", async () => { + process.env.OPENCODE_AUTH_CONTENT = JSON.stringify({ "https://config.example.invalid": { type: "wellknown" } }) + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") }) test("an in-memory account database is an unknown organization source", async () => { From 1186d36daecbe3edffb4ecebb11d07709fd0ae14 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:16:56 -0800 Subject: [PATCH 47/63] fix: mark a config loaded while the auth store was unreadable - Config checks the auth store as Auth reads it and marks the load unresolved when it could not be read, so its skipped well-known remote configs cannot read as enabled later. - Drop the probe-side marking this replaces; isolate the plugin test from inherited env opt-outs. Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/telemetry/config-state.ts | 29 ++++++------------- packages/opencode/src/config/config.ts | 24 +++++++++++++-- .../test/altimate/altimate-plugin.test.ts | 13 ++++++++- .../test/altimate/telemetry/opt-out.test.ts | 14 +++------ packages/opencode/test/config/config.test.ts | 17 +++++++++++ 5 files changed, 64 insertions(+), 33 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index fb262efe59..fe23ff3cbb 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -93,32 +93,21 @@ export function instanceDirectory(): string | undefined { } /** The opt-out from the full config; throws where `Config` cannot load (outside an Instance). */ -// Loaded configs built while the auth store could not be read: they lack its well-known remote -// configs even after the store is repaired, until the app reloads its config. -const loadedWithoutAuth = new WeakSet() -// Loaded configs already read alongside a readable auth store: a later failed read is transient. -const readWithAuth = new WeakSet() const AUTH_REREAD_MS = 100 export async function loadedState(): Promise { const config = await Config.get() // An opt-out the readable sources already set stands, even if another source could not be read. if (config.telemetry?.disabled === true) return "disabled" - if (Config.telemetryConfigUnresolved(config) || loadedWithoutAuth.has(config)) return "unreadable" - // Auth.all() returns an empty store when its read or parse fails, hiding well-known remote config. - // Called only for that throw (an unparseable auth file); its result does not matter here. - try { - await hasWellKnownAuth().catch(async () => { - // Auth.set truncates then writes, so a read can land mid-write: look again before deciding. - await new Promise((resolve) => setTimeout(resolve, AUTH_REREAD_MS)) - return hasWellKnownAuth() - }) - } catch (error) { - if (!readWithAuth.has(config)) loadedWithoutAuth.add(config) - throw error - } - readWithAuth.add(config) - return config.telemetry?.disabled ? "disabled" : "enabled" + // Config marks a load whose auth store could not be read (its well-known remote configs were skipped). + if (Config.telemetryConfigUnresolved(config)) return "unreadable" + // A store unreadable now leaves this read unknown; it throws. Auth.set truncates then writes, so a + // read can land mid-write: look again before deciding. The result itself does not matter here. + await hasWellKnownAuth().catch(async () => { + await new Promise((resolve) => setTimeout(resolve, AUTH_REREAD_MS)) + return hasWellKnownAuth() + }) + return "enabled" } /** The opt-out as the caller can best read it: the full config inside an Instance (a failed load can diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index fb824006ec..b1c2c814b2 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -52,9 +52,28 @@ import { makeRuntime } from "@/effect/run-service" // altimate_change end // altimate_change start — loaded configs in which a source that may set `telemetry.disabled` (the -// organization remote config, a legacy global config that failed to import) could not be read. +// organization remote config, a legacy global config that failed to import, the well-known remote +// configs behind an unreadable auth store) could not be read. const configsWithUnresolvedTelemetry = new WeakSet() const incompleteGlobals = new WeakSet() +// Auth.all() returns an empty store when the store cannot be read, so the load skips its well-known +// remote configs. Read it as Auth does: OPENCODE_AUTH_CONTENT when it parses, otherwise the file. +async function authStoreUnreadable(): Promise { + const inline = process.env.OPENCODE_AUTH_CONTENT + if (inline) { + try { + JSON.parse(inline) + return false + } catch {} + } + try { + const text = await fsNode.readFile(Auth.filepath(), "utf8") + if (text.trim() !== "") JSON.parse(text) + return false + } catch (error) { + return (error as NodeJS.ErrnoException)?.code !== "ENOENT" + } +} export function telemetryConfigUnresolved(config: Info): boolean { return configsWithUnresolvedTelemetry.has(config) } @@ -514,6 +533,7 @@ export const layer = Layer.effect( const loadInstanceState = Effect.fn("Config.loadInstanceState")( function* (ctx: InstanceContext) { const auth = yield* authSvc.all().pipe(Effect.orDie) + const authUnreadable = yield* Effect.promise(authStoreUnreadable) // altimate_change — see authStoreUnreadable let result: Info = {} const authEnv: Record = {} @@ -919,7 +939,7 @@ export const layer = Layer.effect( // altimate_change end // altimate_change — a source that could set `telemetry.disabled` was not read - if (orgConfigUnresolved || incompleteGlobals.has(global)) configsWithUnresolvedTelemetry.add(result) + if (orgConfigUnresolved || authUnreadable || incompleteGlobals.has(global)) configsWithUnresolvedTelemetry.add(result) return { config: result, diff --git a/packages/opencode/test/altimate/altimate-plugin.test.ts b/packages/opencode/test/altimate/altimate-plugin.test.ts index 880ebb8900..92f54d5fd5 100644 --- a/packages/opencode/test/altimate/altimate-plugin.test.ts +++ b/packages/opencode/test/altimate/altimate-plugin.test.ts @@ -119,7 +119,12 @@ describe("buildCliContext", () => { }) test("omits machine_id when this process adopts an opt-out while the config is read", async () => { - delete process.env.ALTIMATE_TELEMETRY_DISABLED + // Every env opt-out short-circuits before the config read this test holds open. + const saved = ["ALTIMATE_TELEMETRY_DISABLED", "ALTIMATE_CLI_DISABLE_TELEMETRY", "OPENCODE_DISABLE_TELEMETRY"].map( + (key) => [key, process.env[key]] as const, + ) + for (const [key] of saved) delete process.env[key] + try { let release!: (value: unknown) => void let started!: () => void const reading = new Promise((resolve) => (started = resolve)) @@ -136,6 +141,12 @@ describe("buildCliContext", () => { release({}) const ctx = JSON.parse(Buffer.from(await building, "base64url").toString("utf8")) as Record expect(Object.prototype.hasOwnProperty.call(ctx, "machine_id")).toBe(false) + } finally { + for (const [key, value] of saved) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } + } }) test("inside a project, omits machine_id when a remote config source could not be read", async () => { diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 699d056012..55082da972 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -842,18 +842,12 @@ describe("telemetry opt-out", () => { expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") }) - test("a config loaded while the auth store was unreadable stays unresolved after the store is repaired", async () => { - const loaded = {} as Awaited> - configSpy.mockResolvedValue(loaded) + test("an auth store unreadable at read time leaves that read unknown, not the config", async () => { + configSpy.mockResolvedValue({}) writeFileSync(Auth.filepath(), "{") await expect(TelemetryConfig.loadedState()).rejects.toThrow() - // Repaired with a well-known login: the cached config never read that login's remote config. - writeFileSync(Auth.filepath(), JSON.stringify({ - "https://config.example.invalid": { type: "wellknown", key: "TEST_CONFIG_TOKEN", token: "test-token" }, - })) - expect(await TelemetryConfig.loadedState()).toBe("unreadable") - // A config the app loads afresh is read as usual. - configSpy.mockResolvedValue({}) + // The store recovers: the config itself was loaded fine (Config marks a load that missed it). + writeFileSync(Auth.filepath(), "{}") expect(await TelemetryConfig.loadedState()).toBe("enabled") }) diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index fe5e71d41d..7a9f51d1ee 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -820,6 +820,23 @@ it.effect("a legacy global config that fails to load leaves the telemetry opt-ou ), ) +it.instance("a config loaded while the auth store is unreadable leaves the telemetry opt-out unresolved", () => + withProcessEnv( + "OPENCODE_AUTH_CONTENT", + undefined, + Effect.gen(function* () { + const authFile = Auth.filepath() + const previous = yield* Effect.promise(() => fs.readFile(authFile, "utf8").catch(() => undefined)) + yield* Effect.promise(() => fs.mkdir(path.dirname(authFile), { recursive: true }).then(() => fs.writeFile(authFile, "{"))) + try { + expect(Config.telemetryConfigUnresolved(yield* Config.use.get())).toBe(true) + } finally { + yield* Effect.promise(() => (previous === undefined ? fs.rm(authFile, { force: true }) : fs.writeFile(authFile, previous))) + } + }), + ), +) + it.instance("validates config schema and throws on invalid fields", () => Effect.gen(function* () { const test = yield* TestInstance From afb0a5c4d44ce39d434259b300574aca94943325 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:25:10 -0800 Subject: [PATCH 48/63] fix: record an unreadable auth store where Auth.all reads it - Auth.all marks the store it returns in place of an existing, non-empty auth file it could not read; Config marks that load unresolved. No second read can disagree with the one the load used. - Remove the duplicate auth-store reader from Config. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/auth/index.ts | 30 ++++++++++++++++++-- packages/opencode/src/config/config.ts | 20 +------------ packages/opencode/test/config/config.test.ts | 2 +- 3 files changed, 30 insertions(+), 22 deletions(-) diff --git a/packages/opencode/src/auth/index.ts b/packages/opencode/src/auth/index.ts index c06d17254d..2f6802e6e5 100644 --- a/packages/opencode/src/auth/index.ts +++ b/packages/opencode/src/auth/index.ts @@ -1,5 +1,6 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import path from "path" +import { existsSync, readFileSync } from "fs" // altimate_change — tell a missing auth store from an unreadable one import { Effect, Layer, Record, Result, Schema, Context } from "effect" import { NonNegativeInt } from "@opencode-ai/core/schema" import { Global } from "@opencode-ai/core/global" @@ -67,6 +68,21 @@ export interface Interface { export class Service extends Context.Service()("@opencode/Auth.cli") {} // altimate_change end +// altimate_change start — stores returned in place of an auth file that exists but could not be read: +// Config skips their well-known remote configs, so its telemetry opt-out is unknown. +const unreadStores = new WeakSet() +export function readFailed(store: object): boolean { + return unreadStores.has(store) +} +function storeFileHasContent(): boolean { + try { + return existsSync(file) && readFileSync(file, "utf8").trim() !== "" + } catch { + return true + } +} +// altimate_change end + export const layer = Layer.effect( Service, Effect.gen(function* () { @@ -80,8 +96,18 @@ export const layer = Layer.effect( } catch (err) {} } - const data = (yield* fsys.readJson(file).pipe(Effect.orElseSucceed(() => ({})))) as Record - return Record.filterMap(data, (value) => Result.fromOption(decode(value), () => undefined)) + // altimate_change start — record a failed read of an auth file that exists and is not empty + let failed = false + const data = (yield* fsys.readJson(file).pipe( + Effect.orElseSucceed(() => { + failed = storeFileHasContent() + return {} + }), + )) as Record + const store = Record.filterMap(data, (value) => Result.fromOption(decode(value), () => undefined)) + if (failed) unreadStores.add(store) + return store + // altimate_change end }) const get = Effect.fn("Auth.get")(function* (providerID: string) { diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index b1c2c814b2..93960fd9fd 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -56,24 +56,6 @@ import { makeRuntime } from "@/effect/run-service" // configs behind an unreadable auth store) could not be read. const configsWithUnresolvedTelemetry = new WeakSet() const incompleteGlobals = new WeakSet() -// Auth.all() returns an empty store when the store cannot be read, so the load skips its well-known -// remote configs. Read it as Auth does: OPENCODE_AUTH_CONTENT when it parses, otherwise the file. -async function authStoreUnreadable(): Promise { - const inline = process.env.OPENCODE_AUTH_CONTENT - if (inline) { - try { - JSON.parse(inline) - return false - } catch {} - } - try { - const text = await fsNode.readFile(Auth.filepath(), "utf8") - if (text.trim() !== "") JSON.parse(text) - return false - } catch (error) { - return (error as NodeJS.ErrnoException)?.code !== "ENOENT" - } -} export function telemetryConfigUnresolved(config: Info): boolean { return configsWithUnresolvedTelemetry.has(config) } @@ -533,7 +515,7 @@ export const layer = Layer.effect( const loadInstanceState = Effect.fn("Config.loadInstanceState")( function* (ctx: InstanceContext) { const auth = yield* authSvc.all().pipe(Effect.orDie) - const authUnreadable = yield* Effect.promise(authStoreUnreadable) // altimate_change — see authStoreUnreadable + const authUnreadable = Auth.readFailed(auth) // altimate_change — an unreadable store skipped its remote configs let result: Info = {} const authEnv: Record = {} diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 7a9f51d1ee..a80e0c7d24 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -820,7 +820,7 @@ it.effect("a legacy global config that fails to load leaves the telemetry opt-ou ), ) -it.instance("a config loaded while the auth store is unreadable leaves the telemetry opt-out unresolved", () => +configIt({ auth: Auth.defaultLayer }).instance("a config loaded while the auth store is unreadable leaves the telemetry opt-out unresolved", () => withProcessEnv( "OPENCODE_AUTH_CONTENT", undefined, From 516aa1c295e183ce30136c4a7808b45cf44da5e3 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:30:56 -0800 Subject: [PATCH 49/63] refactor: stat the auth file instead of re-reading it after a failed read Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/auth/index.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/auth/index.ts b/packages/opencode/src/auth/index.ts index 2f6802e6e5..70062b2f88 100644 --- a/packages/opencode/src/auth/index.ts +++ b/packages/opencode/src/auth/index.ts @@ -1,6 +1,6 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import path from "path" -import { existsSync, readFileSync } from "fs" // altimate_change — tell a missing auth store from an unreadable one +import { statSync } from "fs" // altimate_change — tell a missing or empty auth store from an unreadable one import { Effect, Layer, Record, Result, Schema, Context } from "effect" import { NonNegativeInt } from "@opencode-ai/core/schema" import { Global } from "@opencode-ai/core/global" @@ -76,9 +76,9 @@ export function readFailed(store: object): boolean { } function storeFileHasContent(): boolean { try { - return existsSync(file) && readFileSync(file, "utf8").trim() !== "" - } catch { - return true + return statSync(file).size > 0 // a stat, not a second read of the file the read just failed on + } catch (error) { + return (error as NodeJS.ErrnoException)?.code !== "ENOENT" } } // altimate_change end From 1e73f2ac83cc95d8552cfb32af8fb57c324f3ec7 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:34:26 -0800 Subject: [PATCH 50/63] fix: let the config load decide auth readability inside a project - Drop the in-project auth.json re-read: Auth.all() marks an unreadable store at load, so a later torn read no longer holds a config that loaded fine. - Docs: a file opt-out holds for the process even when an admin organization config enables telemetry. Co-Authored-By: Claude Opus 5.5 --- docs/docs/reference/security-faq.md | 2 +- docs/docs/reference/telemetry.md | 2 +- .../opencode/src/altimate/telemetry/config-state.ts | 10 ++-------- .../opencode/test/altimate/telemetry/opt-out.test.ts | 11 +---------- 4 files changed, 5 insertions(+), 20 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index 7e57b8cd71..125ac042d5 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -183,7 +183,7 @@ No code, queries, file paths, or personal information is included. This event he The install scripts (`altimate.sh/install`, `install.ps1`), the npm postinstall, and the VS Code extension's installer send nothing themselves and contact no telemetry endpoint. They only record the version and installer name to a local file that the CLI reads on its next run, so the opt-out above decides whether anything is ever transmitted. -The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start, and so is the global config unless an organization config set by your admin overrides it. +The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables and a `telemetry.disabled` in your own config files are honoured process-wide from the start; once a process reads either, it sends nothing more, even if an organization config set by your admin enables telemetry. ## What happens when I authenticate via a well-known URL? diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index d0dfa33f4d..9d8ce25f03 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -184,7 +184,7 @@ export ALTIMATE_TELEMETRY_DISABLED=true `ALTIMATE_CLI_DISABLE_TELEMETRY` and its older spelling `OPENCODE_DISABLE_TELEMETRY` are also supported. Each variable accepts `1` or `true` (case-insensitive). -When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. Until the CLI can read the setting (for example at startup, before the project config or a configured remote source that could set the flag has loaded), it sends nothing; see [Privacy](#privacy). Once a process reads the setting as disabled, that process sends nothing more, even for another project it serves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start, and so is the global config unless an organization config set by your admin overrides it. +When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. Until the CLI can read the setting (for example at startup, before the project config or a configured remote source that could set the flag has loaded), it sends nothing; see [Privacy](#privacy). Once a process reads the setting as disabled, that process sends nothing more, even for another project it serves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables and a `telemetry.disabled` in your own config files are honoured process-wide from the start; once a process reads either, it sends nothing more, even if an organization config set by your admin enables telemetry. ### Test runs are excluded diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index fe23ff3cbb..62d064aa16 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -93,20 +93,14 @@ export function instanceDirectory(): string | undefined { } /** The opt-out from the full config; throws where `Config` cannot load (outside an Instance). */ -const AUTH_REREAD_MS = 100 export async function loadedState(): Promise { const config = await Config.get() // An opt-out the readable sources already set stands, even if another source could not be read. if (config.telemetry?.disabled === true) return "disabled" - // Config marks a load whose auth store could not be read (its well-known remote configs were skipped). + // Config marks a load whose auth store could not be read (Auth.all() records it), so the store is + // not read again here: the load that built this config is what counts. if (Config.telemetryConfigUnresolved(config)) return "unreadable" - // A store unreadable now leaves this read unknown; it throws. Auth.set truncates then writes, so a - // read can land mid-write: look again before deciding. The result itself does not matter here. - await hasWellKnownAuth().catch(async () => { - await new Promise((resolve) => setTimeout(resolve, AUTH_REREAD_MS)) - return hasWellKnownAuth() - }) return "enabled" } diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 55082da972..d9213c239d 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -842,12 +842,9 @@ describe("telemetry opt-out", () => { expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") }) - test("an auth store unreadable at read time leaves that read unknown, not the config", async () => { + test("inside a project the load decides: a later unreadable auth read does not hold a config that loaded fine", async () => { configSpy.mockResolvedValue({}) writeFileSync(Auth.filepath(), "{") - await expect(TelemetryConfig.loadedState()).rejects.toThrow() - // The store recovers: the config itself was loaded fine (Config marks a load that missed it). - writeFileSync(Auth.filepath(), "{}") expect(await TelemetryConfig.loadedState()).toBe("enabled") }) @@ -921,12 +918,6 @@ describe("telemetry opt-out", () => { expect(names.sort()).toEqual(["A1", "A2", "B1"]) }) - test("malformed auth prevents an otherwise loaded config from enabling telemetry", async () => { - writeFileSync(Auth.filepath(), "null") - configSpy.mockResolvedValue({}) - await expectSilentLifecycle() - }) - test("an unreadable config suppresses all requests", async () => { process.env.OPENCODE_CONFIG_CONTENT = "{" await expectSilentLifecycle() From 7028f9c2ad468f8cb182acf648980c9761bd2030 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:41:02 -0800 Subject: [PATCH 51/63] docs: describe how an organization config interacts with a file opt-out Co-Authored-By: Claude Opus 5.5 --- docs/docs/reference/security-faq.md | 2 +- docs/docs/reference/telemetry.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index 125ac042d5..8bb3102591 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -183,7 +183,7 @@ No code, queries, file paths, or personal information is included. This event he The install scripts (`altimate.sh/install`, `install.ps1`), the npm postinstall, and the VS Code extension's installer send nothing themselves and contact no telemetry endpoint. They only record the version and installer name to a local file that the CLI reads on its next run, so the opt-out above decides whether anything is ever transmitted. -The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables and a `telemetry.disabled` in your own config files are honoured process-wide from the start; once a process reads either, it sends nothing more, even if an organization config set by your admin enables telemetry. +The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start. An organization config set by your admin is merged over your own files: inside a project it decides, so it can turn telemetry back on, while a command that reads only your files (before a project loads) honours your `telemetry.disabled`. ## What happens when I authenticate via a well-known URL? diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index 9d8ce25f03..3ff357e5cd 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -184,7 +184,7 @@ export ALTIMATE_TELEMETRY_DISABLED=true `ALTIMATE_CLI_DISABLE_TELEMETRY` and its older spelling `OPENCODE_DISABLE_TELEMETRY` are also supported. Each variable accepts `1` or `true` (case-insensitive). -When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. Until the CLI can read the setting (for example at startup, before the project config or a configured remote source that could set the flag has loaded), it sends nothing; see [Privacy](#privacy). Once a process reads the setting as disabled, that process sends nothing more, even for another project it serves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables and a `telemetry.disabled` in your own config files are honoured process-wide from the start; once a process reads either, it sends nothing more, even if an organization config set by your admin enables telemetry. +When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. Until the CLI can read the setting (for example at startup, before the project config or a configured remote source that could set the flag has loaded), it sends nothing; see [Privacy](#privacy). Once a process reads the setting as disabled, that process sends nothing more, even for another project it serves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start. An organization config set by your admin is merged over your own files: inside a project it decides, so it can turn telemetry back on, while a command that reads only your files (before a project loads) honours your `telemetry.disabled`. ### Test runs are excluded From b0856f8493065287b299f6567ad457cee0a8456c Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:42:42 -0800 Subject: [PATCH 52/63] fix: honour another project's file opt-out in a workspace handoff buildCliContext inside an Instance now also requires the handoff project's own files to allow telemetry when it is not the Instance's project. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/plugin/altimate.ts | 9 +++++++-- .../opencode/test/altimate/altimate-plugin.test.ts | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/plugin/altimate.ts b/packages/opencode/src/altimate/plugin/altimate.ts index 31e0b9132d..472931072c 100644 --- a/packages/opencode/src/altimate/plugin/altimate.ts +++ b/packages/opencode/src/altimate/plugin/altimate.ts @@ -1,6 +1,7 @@ import type { Hooks, PluginInput } from "@opencode-ai/plugin" import { createServer } from "http" import { randomBytes } from "crypto" +import path from "path" // altimate_change — compare the handoff project with the Instance import open from "open" import { AltimateApi } from "../api/client" // altimate_change — onboarding telemetry for the gateway sign-in funnel @@ -88,9 +89,13 @@ export async function buildCliContext(machineIdPath?: string, directory?: string // Server routes run inside Instance.provide(), so the full config resolves during an // ordinary browser authorize(). const loaded = await TelemetryConfig.loadedState().catch(() => undefined) + const instance = TelemetryConfig.instanceDirectory() + // A handoff for another project than the one this Instance serves: that project's own files + // may opt out, so they must allow it too. + const otherProject = Boolean(instance && directory && path.resolve(directory) !== instance) if (loaded) { - disabled = loaded !== "enabled" - } else if (TelemetryConfig.instanceDirectory()) { + disabled = loaded !== "enabled" || (otherProject && (await TelemetryConfig.disabledState(directory)) !== "enabled") + } else if (instance) { disabled = true } else { // The paths that skip instance bootstrap: `altimate auth login ` and the diff --git a/packages/opencode/test/altimate/altimate-plugin.test.ts b/packages/opencode/test/altimate/altimate-plugin.test.ts index 92f54d5fd5..c44788e8f1 100644 --- a/packages/opencode/test/altimate/altimate-plugin.test.ts +++ b/packages/opencode/test/altimate/altimate-plugin.test.ts @@ -161,6 +161,20 @@ describe("buildCliContext", () => { expect(await contextHasMachineId(project.path)).toBe(true) }) + test("inside a project, omits machine_id for another project whose own files opt out", async () => { + delete process.env.ALTIMATE_TELEMETRY_DISABLED + await using current = await tmpdir({ git: true }) + await using other = await tmpdir({ git: true }) + fs.mkdirSync(path.join(other.path, ".altimate-code")) + fs.writeFileSync(path.join(other.path, ".altimate-code", "altimate-code.json"), '{ "telemetry": { "disabled": true } }') + await using dir = await tmpdir() + const idPath = path.join(dir.path, "machine-id") + fs.writeFileSync(idPath, VALID_UUID, "utf8") + const encoded = await Instance.provide({ directory: current.path, fn: () => buildCliContext(idPath, other.path) }) + const ctx = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")) as Record + expect(Object.prototype.hasOwnProperty.call(ctx, "machine_id")).toBe(false) + }) + test("inside a project, omits machine_id when the full config fails to load", async () => { delete process.env.ALTIMATE_TELEMETRY_DISABLED await using project = await tmpdir({ git: true }) From 6a579e1ce3b4ebc390f2734582fffc29805435bc Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:51:06 -0800 Subject: [PATCH 53/63] fix: compare the handoff project canonically with the Instance - Resolve symlinks as Instance.provide does before deciding a handoff is for another project. - The test checks the Instance's own project keeps the id, so only the new branch can omit it. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/plugin/altimate.ts | 12 +++++++++++- .../opencode/test/altimate/altimate-plugin.test.ts | 7 ++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/plugin/altimate.ts b/packages/opencode/src/altimate/plugin/altimate.ts index 472931072c..fccadbda8e 100644 --- a/packages/opencode/src/altimate/plugin/altimate.ts +++ b/packages/opencode/src/altimate/plugin/altimate.ts @@ -2,6 +2,7 @@ import type { Hooks, PluginInput } from "@opencode-ai/plugin" import { createServer } from "http" import { randomBytes } from "crypto" import path from "path" // altimate_change — compare the handoff project with the Instance +import { Filesystem } from "@/util/filesystem" // altimate_change — canonicalize as Instance.provide does import open from "open" import { AltimateApi } from "../api/client" // altimate_change — onboarding telemetry for the gateway sign-in funnel @@ -76,6 +77,15 @@ const log = Log.create({ service: "altimate-plugin" }) // and `cli_version` are strings, treat `cli_version: "local"` as a valid dev // build, and treat the payload as untrusted (anyone can craft a URL). An absent // `machine_id` means "do not attribute" — it must never be aliased on. +// altimate_change — the Instance's directory is canonical (symlinks resolved); compare like with like +function canonicalDirectory(directory: string): string { + try { + return Filesystem.resolve(directory) + } catch { + return path.resolve(directory) + } +} + /** `directory`: the project the command acts on, whose config may opt out; the process's working * directory when the command has none (`auth login`). */ export async function buildCliContext(machineIdPath?: string, directory?: string): Promise { @@ -92,7 +102,7 @@ export async function buildCliContext(machineIdPath?: string, directory?: string const instance = TelemetryConfig.instanceDirectory() // A handoff for another project than the one this Instance serves: that project's own files // may opt out, so they must allow it too. - const otherProject = Boolean(instance && directory && path.resolve(directory) !== instance) + const otherProject = Boolean(instance && directory && canonicalDirectory(directory) !== instance) if (loaded) { disabled = loaded !== "enabled" || (otherProject && (await TelemetryConfig.disabledState(directory)) !== "enabled") } else if (instance) { diff --git a/packages/opencode/test/altimate/altimate-plugin.test.ts b/packages/opencode/test/altimate/altimate-plugin.test.ts index c44788e8f1..92849d0ff8 100644 --- a/packages/opencode/test/altimate/altimate-plugin.test.ts +++ b/packages/opencode/test/altimate/altimate-plugin.test.ts @@ -162,7 +162,9 @@ describe("buildCliContext", () => { }) test("inside a project, omits machine_id for another project whose own files opt out", async () => { - delete process.env.ALTIMATE_TELEMETRY_DISABLED + for (const key of ["ALTIMATE_TELEMETRY_DISABLED", "ALTIMATE_CLI_DISABLE_TELEMETRY", "OPENCODE_DISABLE_TELEMETRY"]) { + if (process.env[key] !== undefined) return // an inherited env opt-out would short-circuit before this branch + } await using current = await tmpdir({ git: true }) await using other = await tmpdir({ git: true }) fs.mkdirSync(path.join(other.path, ".altimate-code")) @@ -170,6 +172,9 @@ describe("buildCliContext", () => { await using dir = await tmpdir() const idPath = path.join(dir.path, "machine-id") fs.writeFileSync(idPath, VALID_UUID, "utf8") + // The same call for the Instance's own project keeps the id, so the omission comes from the new branch. + const own = await Instance.provide({ directory: current.path, fn: () => buildCliContext(idPath, current.path) }) + expect(Object.prototype.hasOwnProperty.call(JSON.parse(Buffer.from(own, "base64url").toString("utf8")), "machine_id")).toBe(true) const encoded = await Instance.provide({ directory: current.path, fn: () => buildCliContext(idPath, other.path) }) const ctx = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")) as Record expect(Object.prototype.hasOwnProperty.call(ctx, "machine_id")).toBe(false) From 8f80f8bbc997e9bb9d0ac8b75959f52f472f1a39 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 06:55:47 -0800 Subject: [PATCH 54/63] test: make the handoff test fail if the canonical comparison is reverted Co-Authored-By: Claude Opus 5.5 --- .../opencode/test/altimate/altimate-plugin.test.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/opencode/test/altimate/altimate-plugin.test.ts b/packages/opencode/test/altimate/altimate-plugin.test.ts index 92849d0ff8..c68d1480a4 100644 --- a/packages/opencode/test/altimate/altimate-plugin.test.ts +++ b/packages/opencode/test/altimate/altimate-plugin.test.ts @@ -6,6 +6,7 @@ import { buildAuthorizeUrl, buildCliContext } from "../../src/altimate/plugin/al import { getOrCreateMachineId } from "../../src/altimate/util/machine-id" import { Config } from "../../src/config/config" import { Telemetry } from "../../src/altimate/telemetry" +import { TelemetryConfig } from "../../src/altimate/telemetry/config-state" import os from "os" import { tmpdir } from "../fixture/fixture" import { Instance } from "../../src/project/instance" @@ -162,9 +163,8 @@ describe("buildCliContext", () => { }) test("inside a project, omits machine_id for another project whose own files opt out", async () => { - for (const key of ["ALTIMATE_TELEMETRY_DISABLED", "ALTIMATE_CLI_DISABLE_TELEMETRY", "OPENCODE_DISABLE_TELEMETRY"]) { - if (process.env[key] !== undefined) return // an inherited env opt-out would short-circuit before this branch - } + // An inherited env opt-out would short-circuit before this branch. + if (TelemetryConfig.disablingEnvironmentVariable()) return await using current = await tmpdir({ git: true }) await using other = await tmpdir({ git: true }) fs.mkdirSync(path.join(other.path, ".altimate-code")) @@ -172,8 +172,11 @@ describe("buildCliContext", () => { await using dir = await tmpdir() const idPath = path.join(dir.path, "machine-id") fs.writeFileSync(idPath, VALID_UUID, "utf8") - // The same call for the Instance's own project keeps the id, so the omission comes from the new branch. - const own = await Instance.provide({ directory: current.path, fn: () => buildCliContext(idPath, current.path) }) + // The Instance's own project, named through a symlink, keeps the id: the comparison is canonical, and + // the omission below comes from the other-project branch. + const link = path.join(dir.path, "current-link") + fs.symlinkSync(current.path, link) + const own = await Instance.provide({ directory: current.path, fn: () => buildCliContext(idPath, link) }) expect(Object.prototype.hasOwnProperty.call(JSON.parse(Buffer.from(own, "base64url").toString("utf8")), "machine_id")).toBe(true) const encoded = await Instance.provide({ directory: current.path, fn: () => buildCliContext(idPath, other.path) }) const ctx = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")) as Record From 404087b2693f75dc4643e8bb1e46498bc51ba8a0 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 07:09:53 -0800 Subject: [PATCH 55/63] fix: address cubic and local-review notes on auth-store and docs - A failed auth read of a non-regular path counts as unreadable; whitespace-only auth.json is unreadable at startup too, matching Auth.all(). - Docs: a file opt-out read at CLI startup holds for that process; only a process reading the merged project config follows an admin org config. - Tests: a missing or empty auth.json leaves the opt-out resolved; the canonical-path test now discriminates. Co-Authored-By: Claude Opus 5.5 --- docs/docs/reference/security-faq.md | 2 +- docs/docs/reference/telemetry.md | 2 +- .../src/altimate/telemetry/config-state.ts | 5 ++-- packages/opencode/src/auth/index.ts | 5 +++- .../test/altimate/altimate-plugin.test.ts | 6 ++++- packages/opencode/test/config/config.test.ts | 23 +++++++++++++++++++ 6 files changed, 37 insertions(+), 6 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index 8bb3102591..a24f026517 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -183,7 +183,7 @@ No code, queries, file paths, or personal information is included. This event he The install scripts (`altimate.sh/install`, `install.ps1`), the npm postinstall, and the VS Code extension's installer send nothing themselves and contact no telemetry endpoint. They only record the version and installer name to a local file that the CLI reads on its next run, so the opt-out above decides whether anything is ever transmitted. -The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start. An organization config set by your admin is merged over your own files: inside a project it decides, so it can turn telemetry back on, while a command that reads only your files (before a project loads) honours your `telemetry.disabled`. +The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start. A `telemetry.disabled` in your own files is normally read at CLI startup, before any project loads, so it holds for that process. A process that reads only a project's merged config (such as the TUI's worker thread) follows that config, where an organization config set by your admin is merged over your files. ## What happens when I authenticate via a well-known URL? diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index 3ff357e5cd..0b1f91b748 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -184,7 +184,7 @@ export ALTIMATE_TELEMETRY_DISABLED=true `ALTIMATE_CLI_DISABLE_TELEMETRY` and its older spelling `OPENCODE_DISABLE_TELEMETRY` are also supported. Each variable accepts `1` or `true` (case-insensitive). -When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. Until the CLI can read the setting (for example at startup, before the project config or a configured remote source that could set the flag has loaded), it sends nothing; see [Privacy](#privacy). Once a process reads the setting as disabled, that process sends nothing more, even for another project it serves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start. An organization config set by your admin is merged over your own files: inside a project it decides, so it can turn telemetry back on, while a command that reads only your files (before a project loads) honours your `telemetry.disabled`. +When any of these variables or `telemetry.disabled: true` disables telemetry, the CLI makes zero usage telemetry requests. That includes startup, sessions, error reporting, shutdown, and the account lookup used to identify telemetry events. This applies even if the CLI has sent telemetry before. Until the CLI can read the setting (for example at startup, before the project config or a configured remote source that could set the flag has loaded), it sends nothing; see [Privacy](#privacy). Once a process reads the setting as disabled, that process sends nothing more, even for another project it serves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start. A `telemetry.disabled` in your own files is normally read at CLI startup, before any project loads, so it holds for that process. A process that reads only a project's merged config (such as the TUI's worker thread) follows that config, where an organization config set by your admin is merged over your files. ### Test runs are excluded diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 62d064aa16..98daa78ea9 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -77,8 +77,9 @@ async function hasWellKnownAuth(): Promise { throw error } // Unparseable: a well-known entry may be behind it. `Config` would load without its remote config. - // An empty file (touched, or a crash between Auth.set's truncate and write) holds no entry, as Auth reads it. - parsed = contents.trim() === "" ? {} : JSON.parse(contents) + // An empty file (touched, or a crash between Auth.set's truncate and write) holds no entry, as Auth.all() + // reads it; anything else that does not parse (whitespace included) is unreadable there too. + parsed = contents === "" ? {} : JSON.parse(contents) } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Unreadable auth store") // Any well-known-typed entry counts: Auth passes OPENCODE_AUTH_CONTENT through without decoding it, so diff --git a/packages/opencode/src/auth/index.ts b/packages/opencode/src/auth/index.ts index 70062b2f88..a540581c8e 100644 --- a/packages/opencode/src/auth/index.ts +++ b/packages/opencode/src/auth/index.ts @@ -76,7 +76,10 @@ export function readFailed(store: object): boolean { } function storeFileHasContent(): boolean { try { - return statSync(file).size > 0 // a stat, not a second read of the file the read just failed on + // A stat, not a second read of the file the read just failed on. Only an empty regular file is + // "no store"; anything else that failed to read counts as unreadable. + const stat = statSync(file) + return !stat.isFile() || stat.size > 0 } catch (error) { return (error as NodeJS.ErrnoException)?.code !== "ENOENT" } diff --git a/packages/opencode/test/altimate/altimate-plugin.test.ts b/packages/opencode/test/altimate/altimate-plugin.test.ts index c68d1480a4..3937fa5c76 100644 --- a/packages/opencode/test/altimate/altimate-plugin.test.ts +++ b/packages/opencode/test/altimate/altimate-plugin.test.ts @@ -176,7 +176,11 @@ describe("buildCliContext", () => { // the omission below comes from the other-project branch. const link = path.join(dir.path, "current-link") fs.symlinkSync(current.path, link) - const own = await Instance.provide({ directory: current.path, fn: () => buildCliContext(idPath, link) }) + // The files-only read is made inconclusive, so treating the alias as another project would omit the id. + const filesOnly = spyOn(TelemetryConfig, "disabledState").mockResolvedValue("unreadable") + const own = await Instance.provide({ directory: current.path, fn: () => buildCliContext(idPath, link) }).finally( + () => filesOnly.mockRestore(), + ) expect(Object.prototype.hasOwnProperty.call(JSON.parse(Buffer.from(own, "base64url").toString("utf8")), "machine_id")).toBe(true) const encoded = await Instance.provide({ directory: current.path, fn: () => buildCliContext(idPath, other.path) }) const ctx = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")) as Record diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index a80e0c7d24..7b8632915b 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -820,6 +820,29 @@ it.effect("a legacy global config that fails to load leaves the telemetry opt-ou ), ) +for (const [label, contents] of [["a missing", undefined], ["an empty", ""]] as const) { + configIt({ auth: Auth.defaultLayer }).instance(`${label} auth store leaves the telemetry opt-out resolved`, () => + withProcessEnv( + "OPENCODE_AUTH_CONTENT", + undefined, + Effect.gen(function* () { + const authFile = Auth.filepath() + const previous = yield* Effect.promise(() => fs.readFile(authFile, "utf8").catch(() => undefined)) + yield* Effect.promise(async () => { + await fs.mkdir(path.dirname(authFile), { recursive: true }) + if (contents === undefined) await fs.rm(authFile, { force: true }) + else await fs.writeFile(authFile, contents) + }) + try { + expect(Config.telemetryConfigUnresolved(yield* Config.use.get())).toBe(false) + } finally { + yield* Effect.promise(() => (previous === undefined ? fs.rm(authFile, { force: true }) : fs.writeFile(authFile, previous))) + } + }), + ), + ) +} + configIt({ auth: Auth.defaultLayer }).instance("a config loaded while the auth store is unreadable leaves the telemetry opt-out unresolved", () => withProcessEnv( "OPENCODE_AUTH_CONTENT", From 194c8c50b6ad80be6451c5e927d20e85bdd105f6 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 07:25:04 -0800 Subject: [PATCH 56/63] test: pin whitespace-only auth stores and share the auth-store fixture - startup probe and config load both treat a whitespace-only auth.json as unreadable - one `withAuthStore` helper drives the missing/empty/whitespace/unparseable cases - attach the `loadedState` doc comment; drop a stray blank line Co-Authored-By: Claude Opus 5.5 --- .../src/altimate/telemetry/config-state.ts | 1 - .../opencode/src/altimate/telemetry/index.ts | 1 - .../test/altimate/telemetry/opt-out.test.ts | 4 +- packages/opencode/test/config/config.test.ts | 73 +++++++++---------- 4 files changed, 39 insertions(+), 40 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 98daa78ea9..eff1570657 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -94,7 +94,6 @@ export function instanceDirectory(): string | undefined { } /** The opt-out from the full config; throws where `Config` cannot load (outside an Instance). */ - export async function loadedState(): Promise { const config = await Config.get() // An opt-out the readable sources already set stands, even if another source could not be read. diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 40089d97d7..df49d34091 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2649,7 +2649,6 @@ export namespace Telemetry { } // altimate_change end - async function doInit() { // altimate_change — an unreadable config leaves this init unfinished, so the next init() retries. let unresolved = false diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index d9213c239d..e47ff612dd 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -828,9 +828,11 @@ describe("telemetry opt-out", () => { expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") }) - test("an empty auth file holds no well-known entry, as Auth reads it", async () => { + test("an empty auth file holds no well-known entry, but a whitespace-only one is unreadable, as Auth reads them", async () => { writeFileSync(Auth.filepath(), "") expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + writeFileSync(Auth.filepath(), " \n") + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") }) test("auth content that does not parse falls back to the auth file, as Auth does", async () => { diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 7b8632915b..ae66541956 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -820,46 +820,45 @@ it.effect("a legacy global config that fails to load leaves the telemetry opt-ou ), ) -for (const [label, contents] of [["a missing", undefined], ["an empty", ""]] as const) { - configIt({ auth: Auth.defaultLayer }).instance(`${label} auth store leaves the telemetry opt-out resolved`, () => - withProcessEnv( - "OPENCODE_AUTH_CONTENT", - undefined, - Effect.gen(function* () { - const authFile = Auth.filepath() - const previous = yield* Effect.promise(() => fs.readFile(authFile, "utf8").catch(() => undefined)) - yield* Effect.promise(async () => { - await fs.mkdir(path.dirname(authFile), { recursive: true }) - if (contents === undefined) await fs.rm(authFile, { force: true }) - else await fs.writeFile(authFile, contents) - }) - try { - expect(Config.telemetryConfigUnresolved(yield* Config.use.get())).toBe(false) - } finally { - yield* Effect.promise(() => (previous === undefined ? fs.rm(authFile, { force: true }) : fs.writeFile(authFile, previous))) - } - }), - ), +// Writes the auth store (undefined removes it) for one effect, then restores the previous file. +const withAuthStore = (contents: string | undefined, effect: Effect.Effect) => + Effect.gen(function* () { + const authFile = Auth.filepath() + const previous = yield* Effect.promise(() => fs.readFile(authFile, "utf8").catch(() => undefined)) + yield* Effect.promise(async () => { + await fs.mkdir(path.dirname(authFile), { recursive: true }) + if (contents === undefined) await fs.rm(authFile, { force: true }) + else await fs.writeFile(authFile, contents) + }) + return yield* effect.pipe( + Effect.ensuring( + Effect.promise(() => (previous === undefined ? fs.rm(authFile, { force: true }) : fs.writeFile(authFile, previous))), + ), + ) + }) + +for (const [label, contents, unresolved] of [ + ["a missing", undefined, false], + ["an empty", "", false], + ["a whitespace-only", " \n", true], + ["an unparseable", "{", true], +] as const) { + configIt({ auth: Auth.defaultLayer }).instance( + `a config loaded with ${label} auth store leaves the telemetry opt-out ${unresolved ? "unresolved" : "resolved"}`, + () => + withProcessEnv( + "OPENCODE_AUTH_CONTENT", + undefined, + withAuthStore( + contents, + Effect.gen(function* () { + expect(Config.telemetryConfigUnresolved(yield* Config.use.get())).toBe(unresolved) + }), + ), + ), ) } -configIt({ auth: Auth.defaultLayer }).instance("a config loaded while the auth store is unreadable leaves the telemetry opt-out unresolved", () => - withProcessEnv( - "OPENCODE_AUTH_CONTENT", - undefined, - Effect.gen(function* () { - const authFile = Auth.filepath() - const previous = yield* Effect.promise(() => fs.readFile(authFile, "utf8").catch(() => undefined)) - yield* Effect.promise(() => fs.mkdir(path.dirname(authFile), { recursive: true }).then(() => fs.writeFile(authFile, "{"))) - try { - expect(Config.telemetryConfigUnresolved(yield* Config.use.get())).toBe(true) - } finally { - yield* Effect.promise(() => (previous === undefined ? fs.rm(authFile, { force: true }) : fs.writeFile(authFile, previous))) - } - }), - ), -) - it.instance("validates config schema and throws on invalid fields", () => Effect.gen(function* () { const test = yield* TestInstance From 20ef32ca348eb3d875cbc9f5856fc47febc6d3dd Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 07:53:44 -0800 Subject: [PATCH 57/63] fix: close the exit race in an adopted enabled answer and other review notes - `adoptOptOut("enabled")` skips its init if a shutdown started while it waited - an aborted batch is not put back after an opt-out - the other-project handoff check reads only that project's files - identity tests clear `ALTIMATE_CLI_DISABLE_TELEMETRY` too Co-Authored-By: Claude Opus 5.5 --- .../opencode/src/altimate/plugin/altimate.ts | 5 ++-- .../src/altimate/telemetry/config-state.ts | 5 ++-- .../opencode/src/altimate/telemetry/index.ts | 12 +++++++-- .../test/altimate/altimate-plugin.test.ts | 16 +++++++++++ .../test/altimate/telemetry/identity.test.ts | 2 +- .../test/altimate/telemetry/opt-out.test.ts | 27 +++++++++++++++++++ 6 files changed, 60 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/altimate/plugin/altimate.ts b/packages/opencode/src/altimate/plugin/altimate.ts index fccadbda8e..e00ee8451c 100644 --- a/packages/opencode/src/altimate/plugin/altimate.ts +++ b/packages/opencode/src/altimate/plugin/altimate.ts @@ -101,10 +101,11 @@ export async function buildCliContext(machineIdPath?: string, directory?: string const loaded = await TelemetryConfig.loadedState().catch(() => undefined) const instance = TelemetryConfig.instanceDirectory() // A handoff for another project than the one this Instance serves: that project's own files - // may opt out, so they must allow it too. + // may opt out, so they must allow it too. The remote and organization sources are the same for + // both projects and the loaded config already covers them. const otherProject = Boolean(instance && directory && canonicalDirectory(directory) !== instance) if (loaded) { - disabled = loaded !== "enabled" || (otherProject && (await TelemetryConfig.disabledState(directory)) !== "enabled") + disabled = loaded !== "enabled" || (otherProject && (await TelemetryConfig.disabledState(directory, { filesOnly: true })) !== "enabled") } else if (instance) { disabled = true } else { diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index eff1570657..00f4a8477a 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -173,7 +173,8 @@ async function remoteMayDisable(local: boolean | undefined): Promise { } } -export async function disabledState(directory: string = process.cwd()): Promise { +/** `filesOnly` skips the remote and organization sources, for a caller whose loaded config already covers them. */ +export async function disabledState(directory: string = process.cwd(), opts?: { filesOnly?: boolean }): Promise { try { let value: boolean | undefined // Any source that fails to read, parse or validate fails Config's whole load, so the answer @@ -254,7 +255,7 @@ export async function disabledState(directory: string = process.cwd()): Promise< if (unknown) return "unreadable" // The files themselves opt out: that stands, even if a remote config might turn it back on (fail closed). if (value === true) return "disabled" - if (!managedSetting && (await remoteMayDisable(value))) return "unreadable" + if (!opts?.filesOnly && !managedSetting && (await remoteMayDisable(value))) return "unreadable" return "enabled" } catch { return "unreadable" diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index df49d34091..4e2984fcc9 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2379,7 +2379,11 @@ export namespace Telemetry { // Not during a shutdown: a re-init chained behind the exit flush would start a lifecycle nobody ends. if (gate !== "pending" || shutdownPromise) return Promise.resolve() adopted = "enabled" - return (initPromise ?? Promise.resolve()).catch(() => {}).then(() => init()) + const shutdownsAtCall = shutdownsStarted + // Checked again once the running init settles: a shutdown may have started (or finished) meanwhile. + return (initPromise ?? Promise.resolve()) + .catch(() => {}) + .then(() => (shutdownPromise || shutdownsStarted !== shutdownsAtCall ? undefined : init())) } /** Test seam: forget the process-wide opt-out decision and the events held for it. A lifecycle a * test left running and enabled keeps its decision, so it goes on sending as it did before the gate. */ @@ -2436,6 +2440,8 @@ export namespace Telemetry { // altimate_change — in-flight shutdown, declared with the rest of the module state so init() // above can consult it. See shutdown() for why concurrent shutdowns must be serialized. let shutdownPromise: Promise | undefined + // Counts shutdowns started, so a deferred init can tell one began while it waited. + let shutdownsStarted = 0 // altimate_change — init chained onto an in-flight shutdown; see init(). let reinitPromise: Promise | undefined // altimate_change — the currently running flush, so shutdown waits rather than racing it. @@ -3120,7 +3126,8 @@ export namespace Telemetry { // altimate_change — no write-back during shutdown. The buffer is cleared a few lines later // regardless, so re-inserting here does not save these events; it only leaves them to be // shipped by whatever lifecycle comes next, under a different launch id. - if (shuttingDown) return + // Nor after an opt-out: it aborted this batch, and nothing may be held for sending. + if (shuttingDown || gate === "disabled") return // Re-add events that haven't been retried yet to avoid data loss const retriable = events.filter((e) => !sent.has(e) && !(e as any)._retried) // altimate_change — a batch never attempted (an earlier one failed) keeps its retry. @@ -3181,6 +3188,7 @@ export namespace Telemetry { if (timer) clearTimeout(timer) return } + shutdownsStarted++ shutdownPromise = doShutdown(opts?.timeoutMs).finally(() => { shutdownPromise = undefined }) diff --git a/packages/opencode/test/altimate/altimate-plugin.test.ts b/packages/opencode/test/altimate/altimate-plugin.test.ts index 3937fa5c76..b0bdc7e77a 100644 --- a/packages/opencode/test/altimate/altimate-plugin.test.ts +++ b/packages/opencode/test/altimate/altimate-plugin.test.ts @@ -10,6 +10,7 @@ import { TelemetryConfig } from "../../src/altimate/telemetry/config-state" import os from "os" import { tmpdir } from "../fixture/fixture" import { Instance } from "../../src/project/instance" +import { Database } from "@opencode-ai/core/database/database" const VALID_UUID = "550e8400-e29b-41d4-a716-446655440000" @@ -187,6 +188,21 @@ describe("buildCliContext", () => { expect(Object.prototype.hasOwnProperty.call(ctx, "machine_id")).toBe(false) }) + test("inside a project, keeps machine_id for another project without an opt-out when remote sources exist", async () => { + if (TelemetryConfig.disablingEnvironmentVariable()) return + await using current = await tmpdir({ git: true }) + await using other = await tmpdir({ git: true }) + await using dir = await tmpdir() + const idPath = path.join(dir.path, "machine-id") + fs.writeFileSync(idPath, VALID_UUID, "utf8") + // An account database the startup probe cannot read: only the loaded config can rule on remote sources. + const database = spyOn(Database, "path").mockReturnValue(":memory:") + const encoded = await Instance.provide({ directory: current.path, fn: () => buildCliContext(idPath, other.path) }).finally( + () => database.mockRestore(), + ) + expect(JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"))["machine_id"]).toBe(VALID_UUID) + }) + test("inside a project, omits machine_id when the full config fails to load", async () => { delete process.env.ALTIMATE_TELEMETRY_DISABLED await using project = await tmpdir({ git: true }) diff --git a/packages/opencode/test/altimate/telemetry/identity.test.ts b/packages/opencode/test/altimate/telemetry/identity.test.ts index 4f1b206714..fd293b9e79 100644 --- a/packages/opencode/test/altimate/telemetry/identity.test.ts +++ b/packages/opencode/test/altimate/telemetry/identity.test.ts @@ -30,7 +30,7 @@ async function until(pred: () => boolean, ms = 2_000) { return pred() } -const DISABLE_FLAGS = ["ALTIMATE_TELEMETRY_DISABLED", "OPENCODE_DISABLE_TELEMETRY"] as const +const DISABLE_FLAGS = ["ALTIMATE_TELEMETRY_DISABLED", "ALTIMATE_CLI_DISABLE_TELEMETRY", "OPENCODE_DISABLE_TELEMETRY"] as const describe("telemetry identity", () => { const savedFlags: Record = {} diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index e47ff612dd..eb3057ecad 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -756,6 +756,33 @@ describe("telemetry opt-out", () => { // Aborted by adoptOptOut itself, before it returned. expect(aborted).toBe(true) await flushing + // The aborted batch is not put back: nothing stays held after the opt-out. + expect(Telemetry.bufferedCountForTest()).toBe(0) + }) + + test("an enabled answer from the worker starts nothing once a shutdown began while this thread's init ran", async () => { + signOut() + wellKnownAuth() + let fail!: (error: Error) => void + let started!: () => void + const reading = new Promise((resolve) => (started = resolve)) + configSpy.mockImplementation(() => { + started() + return new Promise((_, reject) => (fail = reject)) + }) + trackStartup() + const initializing = Telemetry.init() + await reading + const adopting = Telemetry.adoptOptOut("enabled") + const exiting = Telemetry.shutdown() + // The startup read cannot see the remote config, so this thread's own init leaves it pending. + fail(new Error("InstanceRef not provided")) + await initializing + await exiting + await adopting + await Telemetry.flush() + expect(Telemetry.isEnabled()).toBe(false) + expect(fetchSpy).not.toHaveBeenCalled() }) test("a command that loads a project settles an opt-out the startup read left open", async () => { From 61aeea526a55891c091c711d355a278f71734bf8 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 08:00:58 -0800 Subject: [PATCH 58/63] fix: stamp held events on a copy and guard the invalid-global-config load - `track()` no longer writes session/project ids onto the caller's object - test that a global config failing validation fails the load rather than dropping its opt-out Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/altimate/telemetry/index.ts | 8 ++++++-- packages/opencode/test/config/config.test.ts | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index 4e2984fcc9..d9d19e8d55 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -3024,8 +3024,12 @@ export namespace Telemetry { // project it was tracked under instead of taking the next one's at flush. if (!initDone) { const held = event as { session_id?: unknown; project_id?: unknown } - if (held.session_id === undefined && sessionId) held.session_id = sessionId - if (held.project_id === undefined && projectId) held.project_id = projectId + const stamp = { + ...(held.session_id === undefined && sessionId ? { session_id: sessionId } : {}), + ...(held.project_id === undefined && projectId ? { project_id: projectId } : {}), + } + // Stamped on a copy, so a caller's object is left as it passed it. + if (Object.keys(stamp).length > 0) event = { ...event, ...stamp } as Event } // altimate_change end // altimate_change — no ambient workspace stamping: a row names its workspace itself (the prompt diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index ae66541956..4309158091 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -810,6 +810,21 @@ for (const failure of ["account", "organization"] as const) { ) } +it.effect("a global config that fails validation fails the load instead of dropping its opt-out", () => + withGlobalConfig({}, ({ dir }) => + Effect.gen(function* () { + yield* FSUtil.use.writeWithDirs( + path.join(dir, "altimate-code.json"), + JSON.stringify({ telemetry: { disabled: true }, notARealKey: 1 }), + ) + // The load fails outright (it does not fall back to defaults that drop the opt-out), which telemetry + // reads as unresolved inside a project. + const exit = yield* Config.use.get().pipe(provideInstanceEffect(dir), Effect.exit) + expect(Exit.isFailure(exit)).toBe(true) + }).pipe(Effect.provide(testInstanceStoreLayer), Effect.provide(CrossSpawnSpawner.defaultLayer)), + ), +) + it.effect("a legacy global config that fails to load leaves the telemetry opt-out unresolved", () => withGlobalConfig({}, ({ dir }) => Effect.gen(function* () { From 784dca84037aca467d8f6f1be52956ce7bcbfb85 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 08:08:50 -0800 Subject: [PATCH 59/63] fix: read non-object inline auth as Auth does, and document per-project discards - `OPENCODE_AUTH_CONTENT` parsing to a non-object holds no well-known entry at startup - test that a held event is stamped on a copy - docs: held events are also dropped when a session ends for a project whose config could not be read Co-Authored-By: Claude Opus 5.5 --- docs/docs/reference/security-faq.md | 2 +- docs/docs/reference/telemetry.md | 2 +- packages/opencode/src/altimate/telemetry/config-state.ts | 2 ++ .../opencode/test/altimate/telemetry/opt-out.test.ts | 9 +++++++++ 4 files changed, 13 insertions(+), 2 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index a24f026517..abd4e9c08b 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -183,7 +183,7 @@ No code, queries, file paths, or personal information is included. This event he The install scripts (`altimate.sh/install`, `install.ps1`), the npm postinstall, and the VS Code extension's installer send nothing themselves and contact no telemetry endpoint. They only record the version and installer name to a local file that the CLI reads on its next run, so the opt-out above decides whether anything is ever transmitted. -The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled or the process exits before the setting resolves. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start. A `telemetry.disabled` in your own files is normally read at CLI startup, before any project loads, so it holds for that process. A process that reads only a project's merged config (such as the TUI's worker thread) follows that config, where an organization config set by your admin is merged over your files. +The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled, if the process exits before the setting resolves, or when a session ends for a project whose own config could not be read. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start. A `telemetry.disabled` in your own files is normally read at CLI startup, before any project loads, so it holds for that process. A process that reads only a project's merged config (such as the TUI's worker thread) follows that config, where an organization config set by your admin is merged over your files. ## What happens when I authenticate via a well-known URL? diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index 0b1f91b748..96c8bb631e 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -227,7 +227,7 @@ What identifies the sender of an event depends on whether the machine is signed The Claude Code plugin's `plugin_session_start` and `plugin_feature_used` are the exception: signed in or not, they carry neither the machine ID nor your account, and their `ai.user.id` is the plugin's own random install id. -These identifiers are sent only while telemetry is enabled. While the opt-out setting is unresolved, Altimate Code holds events in a bounded in-memory buffer and skips telemetry requests, including the `/users/me` lookup. If a later initialization resolves telemetry as enabled, it sends the queued events. If it resolves as disabled or the process exits while the setting is still unresolved, it discards them. +These identifiers are sent only while telemetry is enabled. While the opt-out setting is unresolved, Altimate Code holds events in a bounded in-memory buffer and skips telemetry requests, including the `/users/me` lookup. If a later initialization resolves telemetry as enabled, it sends the queued events. It discards them if it resolves as disabled, if the process exits while the setting is still unresolved, or when a session ends for a project whose own config could not be read. ### CLI Authentication Flow diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 00f4a8477a..cf1713bae0 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -68,6 +68,8 @@ async function hasWellKnownAuth(): Promise { // As Auth reads it: OPENCODE_AUTH_CONTENT when it parses, otherwise the auth file. const inline = process.env.OPENCODE_AUTH_CONTENT let parsed: unknown = inline ? parseJson(inline) : undefined + // Auth uses parsed inline content as is, so content that is not an object holds no entry. + if (parsed !== undefined && (!parsed || typeof parsed !== "object" || Array.isArray(parsed))) return false if (parsed === undefined) { let contents: string try { diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index eb3057ecad..330f617b28 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -477,6 +477,8 @@ describe("telemetry opt-out", () => { // An event that names no session of its own (an MCP or stall event) takes the process's. const { session_id: _omitted, ...sessionless } = errorEvent("Held") Telemetry.track(sessionless as unknown as Telemetry.Event) + // Stamped on the held copy: the caller's object is left as it passed it. + expect("session_id" in sessionless).toBe(false) await Telemetry.shutdown() Telemetry.setContext({ sessionId: "session-b", projectId: "project-b" }) @@ -862,6 +864,13 @@ describe("telemetry opt-out", () => { expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") }) + test("auth content that parses to something other than an object holds no well-known entry, as Auth reads it", async () => { + for (const content of ["[]", '"x"', "1", "null"]) { + process.env.OPENCODE_AUTH_CONTENT = content + expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + } + }) + test("auth content that does not parse falls back to the auth file, as Auth does", async () => { process.env.OPENCODE_AUTH_CONTENT = "{" expect(await TelemetryConfig.disabledState(home)).toBe("enabled") From 0c392b7f8b2d7a5ad32b81e8d14d4814f817b702 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 08:18:12 -0800 Subject: [PATCH 60/63] fix: address bot and local-review P3s on the opt-out gate - a non-object auth file holds no entry at startup, as Auth reads it - `track()` stamps the trace id on the copy too, leaving the caller's event untouched - the deferred adopt init relies on the shutdown counter alone - plugin tests clear all three opt-out variables; one test renamed to what it sets up - docs: a broken legacy TOML config keeps the setting unresolved; unnest a marker Co-Authored-By: Claude Opus 5.5 --- docs/docs/reference/security-faq.md | 2 +- docs/docs/reference/telemetry.md | 2 +- .../src/altimate/telemetry/config-state.ts | 6 +++--- .../opencode/src/altimate/telemetry/index.ts | 21 ++++++++----------- .../test/altimate/altimate-plugin.test.ts | 17 ++++++++------- .../test/altimate/telemetry/opt-out.test.ts | 7 ++++++- 6 files changed, 30 insertions(+), 25 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index abd4e9c08b..c8dc70dada 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -183,7 +183,7 @@ No code, queries, file paths, or personal information is included. This event he The install scripts (`altimate.sh/install`, `install.ps1`), the npm postinstall, and the VS Code extension's installer send nothing themselves and contact no telemetry endpoint. They only record the version and installer name to a local file that the CLI reads on its next run, so the opt-out above decides whether anything is ever transmitted. -The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled, if the process exits before the setting resolves, or when a session ends for a project whose own config could not be read. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start. A `telemetry.disabled` in your own files is normally read at CLI startup, before any project loads, so it holds for that process. A process that reads only a project's merged config (such as the TUI's worker thread) follows that config, where an organization config set by your admin is merged over your files. +The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled, if the process exits before the setting resolves, or when a session ends for a project whose own config could not be read. A legacy global `config` (TOML) file that fails to import keeps the setting unresolved until it is fixed or removed. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start. A `telemetry.disabled` in your own files is normally read at CLI startup, before any project loads, so it holds for that process. A process that reads only a project's merged config (such as the TUI's worker thread) follows that config, where an organization config set by your admin is merged over your files. ## What happens when I authenticate via a well-known URL? diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index 96c8bb631e..8a900d15bf 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -227,7 +227,7 @@ What identifies the sender of an event depends on whether the machine is signed The Claude Code plugin's `plugin_session_start` and `plugin_feature_used` are the exception: signed in or not, they carry neither the machine ID nor your account, and their `ai.user.id` is the plugin's own random install id. -These identifiers are sent only while telemetry is enabled. While the opt-out setting is unresolved, Altimate Code holds events in a bounded in-memory buffer and skips telemetry requests, including the `/users/me` lookup. If a later initialization resolves telemetry as enabled, it sends the queued events. It discards them if it resolves as disabled, if the process exits while the setting is still unresolved, or when a session ends for a project whose own config could not be read. +These identifiers are sent only while telemetry is enabled. While the opt-out setting is unresolved, Altimate Code holds events in a bounded in-memory buffer and skips telemetry requests, including the `/users/me` lookup. If a later initialization resolves telemetry as enabled, it sends the queued events. It discards them if it resolves as disabled, if the process exits while the setting is still unresolved, or when a session ends for a project whose own config could not be read. A legacy global `config` (TOML) file that fails to import keeps the setting unresolved until it is fixed or removed. ### CLI Authentication Flow diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index cf1713bae0..f8bfbb169d 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -68,8 +68,6 @@ async function hasWellKnownAuth(): Promise { // As Auth reads it: OPENCODE_AUTH_CONTENT when it parses, otherwise the auth file. const inline = process.env.OPENCODE_AUTH_CONTENT let parsed: unknown = inline ? parseJson(inline) : undefined - // Auth uses parsed inline content as is, so content that is not an object holds no entry. - if (parsed !== undefined && (!parsed || typeof parsed !== "object" || Array.isArray(parsed))) return false if (parsed === undefined) { let contents: string try { @@ -83,7 +81,9 @@ async function hasWellKnownAuth(): Promise { // reads it; anything else that does not parse (whitespace included) is unreadable there too. parsed = contents === "" ? {} : JSON.parse(contents) } - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Unreadable auth store") + // Valid JSON that is not an object holds no entry: Auth uses inline content as is and reads such a file + // as an empty store, without marking the read failed. + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false // Any well-known-typed entry counts: Auth passes OPENCODE_AUTH_CONTENT through without decoding it, so // Config can fetch remote config even for an entry the file path would reject (fail closed). return Object.values(parsed).some( diff --git a/packages/opencode/src/altimate/telemetry/index.ts b/packages/opencode/src/altimate/telemetry/index.ts index d9d19e8d55..2f1954815b 100644 --- a/packages/opencode/src/altimate/telemetry/index.ts +++ b/packages/opencode/src/altimate/telemetry/index.ts @@ -2383,7 +2383,7 @@ export namespace Telemetry { // Checked again once the running init settles: a shutdown may have started (or finished) meanwhile. return (initPromise ?? Promise.resolve()) .catch(() => {}) - .then(() => (shutdownPromise || shutdownsStarted !== shutdownsAtCall ? undefined : init())) + .then(() => (shutdownsStarted !== shutdownsAtCall ? undefined : init())) } /** Test seam: forget the process-wide opt-out decision and the events held for it. A lifecycle a * test left running and enabled keeps its decision, so it goes on sending as it did before the gate. */ @@ -3019,18 +3019,16 @@ export namespace Telemetry { // Becomes the envelope's `ai.operation.id`, joining it to the extension's and backend's records. const eventSession = (event as { session_id?: unknown }).session_id const operationId = typeof eventSession === "string" ? TraceContext.activeTraceId(eventSession) : undefined - if (operationId) (event as any)._operation_id = operationId // An event held while the opt-out is unknown can outlive this session: it keeps the session and // project it was tracked under instead of taking the next one's at flush. - if (!initDone) { - const held = event as { session_id?: unknown; project_id?: unknown } - const stamp = { - ...(held.session_id === undefined && sessionId ? { session_id: sessionId } : {}), - ...(held.project_id === undefined && projectId ? { project_id: projectId } : {}), - } - // Stamped on a copy, so a caller's object is left as it passed it. - if (Object.keys(stamp).length > 0) event = { ...event, ...stamp } as Event + const held = event as { session_id?: unknown; project_id?: unknown } + const stamp = { + ...(operationId ? { _operation_id: operationId } : {}), + ...(!initDone && held.session_id === undefined && sessionId ? { session_id: sessionId } : {}), + ...(!initDone && held.project_id === undefined && projectId ? { project_id: projectId } : {}), } + // Stamped on a copy, so a caller's object is left as it passed it. + if (Object.keys(stamp).length > 0) event = { ...event, ...stamp } as Event // altimate_change end // altimate_change — no ambient workspace stamping: a row names its workspace itself (the prompt // loop's rows, tool rows and memory rows carry the turn's; workspace rows carry their own) or it @@ -3257,7 +3255,7 @@ export namespace Telemetry { shuttingDown = false enabled = false appInsights = undefined - // altimate_change start — while the opt-out is undecided nothing was flushed: keep the events for a + // altimate_change — while the opt-out is undecided nothing was flushed: keep the events for a // later init in this process to send or drop. At process exit they go with the process. Not when a // project's own read failed: once its session ends, another project's decision must not send its // events. (Sessions that overlap share one lifecycle, as before: see the docs' multi-project note.) @@ -3266,7 +3264,6 @@ export namespace Telemetry { buffer = [] droppedEvents = 0 } - // altimate_change end sessionId = "" projectId = "" machineId = "" diff --git a/packages/opencode/test/altimate/altimate-plugin.test.ts b/packages/opencode/test/altimate/altimate-plugin.test.ts index b0bdc7e77a..ce4d738113 100644 --- a/packages/opencode/test/altimate/altimate-plugin.test.ts +++ b/packages/opencode/test/altimate/altimate-plugin.test.ts @@ -24,19 +24,22 @@ function stubConfig(impl: () => Promise) { describe("buildCliContext", () => { let cfg: ReturnType - let savedDisabled: string | undefined + const optOutFlags = ["ALTIMATE_TELEMETRY_DISABLED", "ALTIMATE_CLI_DISABLE_TELEMETRY", "OPENCODE_DISABLE_TELEMETRY"] + let savedFlags: Record = {} beforeEach(() => { // Clear any real opt-out from the dev's shell so these "telemetry enabled" - // tests are not silently broken by an exported ALTIMATE_TELEMETRY_DISABLED. - savedDisabled = process.env.ALTIMATE_TELEMETRY_DISABLED - delete process.env.ALTIMATE_TELEMETRY_DISABLED + // tests are not silently broken (or skipped) by an exported opt-out variable. + savedFlags = Object.fromEntries(optOutFlags.map((flag) => [flag, process.env[flag]])) + for (const flag of optOutFlags) delete process.env[flag] cfg = stubConfig(async () => ({})) }) afterEach(() => { cfg.mockRestore() - if (savedDisabled === undefined) delete process.env.ALTIMATE_TELEMETRY_DISABLED - else process.env.ALTIMATE_TELEMETRY_DISABLED = savedDisabled + for (const flag of optOutFlags) { + if (savedFlags[flag] === undefined) delete process.env[flag] + else process.env[flag] = savedFlags[flag] + } }) test("returns a valid base64url-encoded JSON blob with machine_id", async () => { @@ -188,7 +191,7 @@ describe("buildCliContext", () => { expect(Object.prototype.hasOwnProperty.call(ctx, "machine_id")).toBe(false) }) - test("inside a project, keeps machine_id for another project without an opt-out when remote sources exist", async () => { + test("inside a project, keeps machine_id for another project without an opt-out when the account database cannot be read", async () => { if (TelemetryConfig.disablingEnvironmentVariable()) return await using current = await tmpdir({ git: true }) await using other = await tmpdir({ git: true }) diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 330f617b28..1a12a5aa3a 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -864,11 +864,16 @@ describe("telemetry opt-out", () => { expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") }) - test("auth content that parses to something other than an object holds no well-known entry, as Auth reads it", async () => { + test("auth content or an auth file that parses to something other than an object holds no well-known entry, as Auth reads it", async () => { for (const content of ["[]", '"x"', "1", "null"]) { process.env.OPENCODE_AUTH_CONTENT = content expect(await TelemetryConfig.disabledState(home)).toBe("enabled") } + delete process.env.OPENCODE_AUTH_CONTENT + for (const content of ["[]", '"x"', "5", "true"]) { + writeFileSync(Auth.filepath(), content) + expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + } }) test("auth content that does not parse falls back to the auth file, as Auth does", async () => { From 4c261ce7e69b61bb285937d511303e71d9b59825 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 08:32:12 -0800 Subject: [PATCH 61/63] fix: treat any non-object auth store as unreadable at startup - a `null` store fails Config's load, so reading non-objects as empty was fail-open; only a plain object is ruled on now - FAQ auth-flow bullet names all three opt-out variables and the unresolved case Co-Authored-By: Claude Opus 5.5 --- docs/docs/reference/security-faq.md | 2 +- packages/opencode/src/altimate/telemetry/config-state.ts | 6 +++--- packages/opencode/test/altimate/telemetry/opt-out.test.ts | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index c8dc70dada..e131ccb097 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -168,7 +168,7 @@ export ALTIMATE_TELEMETRY_DISABLED=true - **Users who are not signed in:** A random UUID (`crypto.randomUUID()`) is generated on first run and stored at `~/.altimate/machine-id`. This is NOT tied to your hardware, OS, or identity — it's purely random. - **Both identifiers** are only sent when telemetry is enabled. Disable with `ALTIMATE_TELEMETRY_DISABLED=true` or the `telemetry.disabled` config option. - **No fingerprinting:** We do not use browser fingerprinting, hardware IDs, MAC addresses, or IP-based tracking. -- **CLI auth flow:** When you sign in via `altimate auth login`, the anonymous machine ID is included in the authorization URL and associated with your account in product analytics for funnel analysis. This is suppressed when you disable telemetry — via `ALTIMATE_TELEMETRY_DISABLED=true` or the `telemetry.disabled` config option — and the machine ID is omitted from the URL entirely. +- **CLI auth flow:** When you sign in via `altimate auth login`, the anonymous machine ID is included in the authorization URL and associated with your account in product analytics for funnel analysis. The machine ID is omitted from the URL entirely when you disable telemetry (any of the three environment variables below, or the `telemetry.disabled` config option), and also while that setting cannot be resolved. ### What happens on first launch? diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index f8bfbb169d..8afe04b97c 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -81,9 +81,9 @@ async function hasWellKnownAuth(): Promise { // reads it; anything else that does not parse (whitespace included) is unreadable there too. parsed = contents === "" ? {} : JSON.parse(contents) } - // Valid JSON that is not an object holds no entry: Auth uses inline content as is and reads such a file - // as an empty store, without marking the read failed. - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false + // Only a plain object is a store this probe can rule on. Anything else is unreadable (fail closed): some + // such values (null) fail Config's load outright, and it is not worth matching Auth case by case. + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Unreadable auth store") // Any well-known-typed entry counts: Auth passes OPENCODE_AUTH_CONTENT through without decoding it, so // Config can fetch remote config even for an entry the file path would reject (fail closed). return Object.values(parsed).some( diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 1a12a5aa3a..0027b83d6e 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -864,15 +864,15 @@ describe("telemetry opt-out", () => { expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") }) - test("auth content or an auth file that parses to something other than an object holds no well-known entry, as Auth reads it", async () => { + test("auth content or an auth file that parses to anything but a plain object is unreadable (fail closed)", async () => { for (const content of ["[]", '"x"', "1", "null"]) { process.env.OPENCODE_AUTH_CONTENT = content - expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") } delete process.env.OPENCODE_AUTH_CONTENT - for (const content of ["[]", '"x"', "5", "true"]) { + for (const content of ["[]", '"x"', "5", "true", "null"]) { writeFileSync(Auth.filepath(), content) - expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") } }) From fc0bcf1023d578d520cce5f419be1fa69a1b3350 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 08:44:20 -0800 Subject: [PATCH 62/63] test: pin local-over-well-known precedence; name all opt-out variables in the FAQ Co-Authored-By: Claude Opus 5.5 --- docs/docs/reference/security-faq.md | 4 ++-- packages/opencode/test/altimate/altimate-plugin.test.ts | 2 +- packages/opencode/test/altimate/telemetry/opt-out.test.ts | 7 +++++++ 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index e131ccb097..400fbed152 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -166,9 +166,9 @@ export ALTIMATE_TELEMETRY_DISABLED=true - **Signed-in users:** Events carry your Altimate user ID and tenant, so they are not anonymous. No email address, hashed or not, is sent. See [User identification](telemetry.md) for how the ID is looked up and cached. - **Users who are not signed in:** A random UUID (`crypto.randomUUID()`) is generated on first run and stored at `~/.altimate/machine-id`. This is NOT tied to your hardware, OS, or identity — it's purely random. -- **Both identifiers** are only sent when telemetry is enabled. Disable with `ALTIMATE_TELEMETRY_DISABLED=true` or the `telemetry.disabled` config option. +- **Both identifiers** are only sent when telemetry is enabled. Disable with `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY` or `OPENCODE_DISABLE_TELEMETRY` set to `1` or `true`, or the `telemetry.disabled` config option. - **No fingerprinting:** We do not use browser fingerprinting, hardware IDs, MAC addresses, or IP-based tracking. -- **CLI auth flow:** When you sign in via `altimate auth login`, the anonymous machine ID is included in the authorization URL and associated with your account in product analytics for funnel analysis. The machine ID is omitted from the URL entirely when you disable telemetry (any of the three environment variables below, or the `telemetry.disabled` config option), and also while that setting cannot be resolved. +- **CLI auth flow:** When you sign in via `altimate auth login`, the anonymous machine ID is included in the authorization URL and associated with your account in product analytics for funnel analysis. The machine ID is omitted from the URL entirely when you disable telemetry (any of those three environment variables, or the `telemetry.disabled` config option), and also while that setting cannot be resolved. ### What happens on first launch? diff --git a/packages/opencode/test/altimate/altimate-plugin.test.ts b/packages/opencode/test/altimate/altimate-plugin.test.ts index ce4d738113..fc97a248f5 100644 --- a/packages/opencode/test/altimate/altimate-plugin.test.ts +++ b/packages/opencode/test/altimate/altimate-plugin.test.ts @@ -191,7 +191,7 @@ describe("buildCliContext", () => { expect(Object.prototype.hasOwnProperty.call(ctx, "machine_id")).toBe(false) }) - test("inside a project, keeps machine_id for another project without an opt-out when the account database cannot be read", async () => { + test("inside a project, keeps machine_id for another project without an opt-out, without consulting the account database", async () => { if (TelemetryConfig.disablingEnvironmentVariable()) return await using current = await tmpdir({ git: true }) await using other = await tmpdir({ git: true }) diff --git a/packages/opencode/test/altimate/telemetry/opt-out.test.ts b/packages/opencode/test/altimate/telemetry/opt-out.test.ts index 0027b83d6e..9529373a3f 100644 --- a/packages/opencode/test/altimate/telemetry/opt-out.test.ts +++ b/packages/opencode/test/altimate/telemetry/opt-out.test.ts @@ -876,6 +876,13 @@ describe("telemetry opt-out", () => { } }) + test("an explicit local telemetry setting outranks a well-known remote config, which Config merges first", async () => { + process.env.OPENCODE_AUTH_CONTENT = JSON.stringify({ "https://config.example.invalid": { type: "wellknown" } }) + expect(await TelemetryConfig.disabledState(home)).toBe("unreadable") + process.env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ telemetry: { disabled: false } }) + expect(await TelemetryConfig.disabledState(home)).toBe("enabled") + }) + test("auth content that does not parse falls back to the auth file, as Auth does", async () => { process.env.OPENCODE_AUTH_CONTENT = "{" expect(await TelemetryConfig.disabledState(home)).toBe("enabled") From 37dbb3a1649503f48eb60dc71bdcadfffeca7044 Mon Sep 17 00:00:00 2001 From: anandgupta42 Date: Sat, 21 Nov 2026 09:13:57 -0800 Subject: [PATCH 63/63] docs: a legacy TOML hold lifts on config reload; note the loose well-known match Co-Authored-By: Claude Opus 5.5 --- docs/docs/reference/security-faq.md | 2 +- docs/docs/reference/telemetry.md | 2 +- packages/opencode/src/altimate/telemetry/config-state.ts | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/docs/reference/security-faq.md b/docs/docs/reference/security-faq.md index 400fbed152..5132e924cf 100644 --- a/docs/docs/reference/security-faq.md +++ b/docs/docs/reference/security-faq.md @@ -183,7 +183,7 @@ No code, queries, file paths, or personal information is included. This event he The install scripts (`altimate.sh/install`, `install.ps1`), the npm postinstall, and the VS Code extension's installer send nothing themselves and contact no telemetry endpoint. They only record the version and installer name to a local file that the CLI reads on its next run, so the opt-out above decides whether anything is ever transmitted. -The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled, if the process exits before the setting resolves, or when a session ends for a project whose own config could not be read. A legacy global `config` (TOML) file that fails to import keeps the setting unresolved until it is fixed or removed. One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start. A `telemetry.disabled` in your own files is normally read at CLI startup, before any project loads, so it holds for that process. A process that reads only a project's merged config (such as the TUI's worker thread) follows that config, where an organization config set by your admin is merged over your files. +The CLI sends zero usage telemetry requests when `ALTIMATE_TELEMETRY_DISABLED`, `ALTIMATE_CLI_DISABLE_TELEMETRY`, or `OPENCODE_DISABLE_TELEMETRY` is set to `1` or `true` (case-insensitive), or when `telemetry.disabled` is `true` in config. This also covers first launch and shutdown. If the opt-out setting is unresolved, the CLI holds events in memory and makes no telemetry requests. It discards them if telemetry is disabled, if the process exits before the setting resolves, or when a session ends for a project whose own config could not be read. A legacy global `config` (TOML) file that fails to import keeps the setting unresolved until it is fixed or removed and the config is reloaded (a long-running process reloads it on restart). One exception: a process that serves several projects (`serve`, an IDE) reads a project's own `telemetry.disabled` when that project's session starts, so a few of its events from before then can be sent if another, opted-in project already turned telemetry on. The environment variables are honoured process-wide from the start. A `telemetry.disabled` in your own files is normally read at CLI startup, before any project loads, so it holds for that process. A process that reads only a project's merged config (such as the TUI's worker thread) follows that config, where an organization config set by your admin is merged over your files. ## What happens when I authenticate via a well-known URL? diff --git a/docs/docs/reference/telemetry.md b/docs/docs/reference/telemetry.md index 8a900d15bf..36f07bc1b3 100644 --- a/docs/docs/reference/telemetry.md +++ b/docs/docs/reference/telemetry.md @@ -227,7 +227,7 @@ What identifies the sender of an event depends on whether the machine is signed The Claude Code plugin's `plugin_session_start` and `plugin_feature_used` are the exception: signed in or not, they carry neither the machine ID nor your account, and their `ai.user.id` is the plugin's own random install id. -These identifiers are sent only while telemetry is enabled. While the opt-out setting is unresolved, Altimate Code holds events in a bounded in-memory buffer and skips telemetry requests, including the `/users/me` lookup. If a later initialization resolves telemetry as enabled, it sends the queued events. It discards them if it resolves as disabled, if the process exits while the setting is still unresolved, or when a session ends for a project whose own config could not be read. A legacy global `config` (TOML) file that fails to import keeps the setting unresolved until it is fixed or removed. +These identifiers are sent only while telemetry is enabled. While the opt-out setting is unresolved, Altimate Code holds events in a bounded in-memory buffer and skips telemetry requests, including the `/users/me` lookup. If a later initialization resolves telemetry as enabled, it sends the queued events. It discards them if it resolves as disabled, if the process exits while the setting is still unresolved, or when a session ends for a project whose own config could not be read. A legacy global `config` (TOML) file that fails to import keeps the setting unresolved until it is fixed or removed and the config is reloaded (a long-running process reloads it on restart). ### CLI Authentication Flow diff --git a/packages/opencode/src/altimate/telemetry/config-state.ts b/packages/opencode/src/altimate/telemetry/config-state.ts index 8afe04b97c..fb9e680bcf 100644 --- a/packages/opencode/src/altimate/telemetry/config-state.ts +++ b/packages/opencode/src/altimate/telemetry/config-state.ts @@ -85,7 +85,8 @@ async function hasWellKnownAuth(): Promise { // such values (null) fail Config's load outright, and it is not worth matching Auth case by case. if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Unreadable auth store") // Any well-known-typed entry counts: Auth passes OPENCODE_AUTH_CONTENT through without decoding it, so - // Config can fetch remote config even for an entry the file path would reject (fail closed). + // Config can fetch remote config even for an entry the file path would reject. For the file this is + // looser than Auth's decode (a malformed entry also counts), which only errs toward holding (fail closed). return Object.values(parsed).some( (entry) => entry && typeof entry === "object" && (entry as { type?: unknown }).type === "wellknown", )