Skip to content

Commit a1fefe9

Browse files
feat: carry the signed-in user and tenant on telemetry, and send a final event on opt-out (#1501)
* feat: telemetry carries the backend user id and tenant when signed in Resolve the signed-in user once per credential (GET /users/me, cached at ~/.altimate/telemetry-identity.json) and stamp user_id and tenant on every event; the hashed account email is gone. Backend calls send x-altimate-client. Closes #1498 Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE * test: telemetry no longer calls Account.active() The two source guards expected the awaited call that the identity change removed; they now assert the call is gone and identity comes from the stored credential. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE * fix: a stale identity resolution never overwrites a newer sign-in or a shutdown Each resolution carries the generation it started in and applies only while it is the newest; shutdown() bumps the generation, so an in-flight /users/me answer for the previous credential is discarded. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE * fix: telemetry identity follows credential changes from any path Resolve the credential like the provider (file, else the auth-store key); notice sign-in, sign-out and key changes on disk at the next flush; attribute a batch to the identity it was tracked under; drop the cache on a 401 or 403; never cache an answer for a credential that changed mid-flight. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE * fix: retry a failed identity lookup later, normalise auth-store URLs A resolution that fails while a credential exists resets the stamp with a 60 s backoff so a later flush tries again; an auth-store key keeps no trailing slash; the mid-flight test waits for the request to reach its gate. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE * fix: a credential change during the retry backoff is noticed at once The backoff throttles retries of the unchanged failed credential only; the stamp comparison keeps running, so a different credential appearing in the window resolves at the next flush. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE * feat: send one final telemetry_opted_out event when telemetry is disabled A machine that has sent telemetry before sends the opt-out once (machine id, version, how it was set, cached user id and tenant) and nothing after; a marker next to the machine id keeps it to once and is cleared when telemetry is re-enabled. Closes #1499 Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE * fix: opt-out marker reads the machine id bounded and leaves telemetry state alone readExistingMachineId() shares the regular-file, size-cap and UUID checks of the minting read; the envelope builder takes the machine id and identity as arguments so recordOptOut() never mutates module state an enabled init may use. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE * fix: a stale opt-out send never posts or writes the marker after a shutdown The send carries the lifecycle it started in; shutdown() bumps it, so a task still pending when telemetry is re-enabled neither posts nor recreates the marker. Marker removal is best effort, and the suite drops the force flag. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_011AhtJPr3nmT1Po92ZQk4VE * test: telemetry identity and opt-out fixtures carry `surface` Main made `surface` required on `startup_ready`; the fixtures that track it now set it. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X * fix: an opt-out send accepted across a shutdown keeps its marker The marker write keys on a generation that only an enabled init bumps, so a shutdown while still opted out no longer leaves the accepted event unmarked and sent again. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X * fix: address cubic review of the identity and opt-out modules - `refreshIdentity()` makes no lookup while telemetry is disabled - marker created exclusively - flat exports in the new modules - machine-id docs on their own functions - telemetry tests isolated from disable flags, auth store and real home Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X * fix: honour a config telemetry opt-out when init runs without an Instance `TelemetryConfig.disabledState()` reads `telemetry.disabled` from the config files. When `Config.get()` throws, init uses it; when the files cannot be read, init keeps the opt-out marker and resolves no identity. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X * fix: one opt-out event without the account; no polling of a rejected key - claim the opt-out send with an in-flight file, so two inits send once - the event carries the machine id and source only - retry identity only after a transient failure - refresh identity on TUI /logout - create ~/.altimate owner-only Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X * docs: telemetry page matches the identity and opt-out behaviour Signed-in events carry the user id and tenant; the identity cache and lookup; the one final `telemetry_opted_out` event, its marker and claim files; no email hash. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X * fix: read the opt-out from the command's project; guard the marker across processes - init reads the config of the run/attach `--dir` or TUI project - legacy TOML global config read; a non-boolean value is unreadable - the marker is written only while this send still holds its claim - docs: eligibility is an existing machine id Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X * fix: the config opt-out probe emits no telemetry of its own The probe parses with `track: false`, so reading a config that uses env interpolation queues no `config_env_interpolation` row. Its tests set aside every global config source and both inline-config variables. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X * test: the probe's no-telemetry check waits on the import, not a timer Also restores the env variable it sets instead of deleting it. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X * fix: the opt-out probe rejects any source the config loader would reject Each source is parsed with missing `{file:}` references as errors and validated by the loader's own schema step (`validateLoaded`); any failure makes the read unreadable. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X * fix: the opt-out probe parses a whitespace-only source, as the loader does Only an empty source is skipped; whitespace goes to the parser and fails, so the read is unreadable. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
1 parent ec289cf commit a1fefe9

20 files changed

Lines changed: 1787 additions & 50 deletions

File tree

‎docs/docs/reference/telemetry.md‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
---
22
title: "Telemetry — Altimate Code"
3-
description: "Altimate Code collects anonymous usage telemetry by default. See what's collected and how to opt out."
3+
description: "Altimate Code collects usage telemetry by default. See what's collected, what identifies you when you sign in, and how to opt out."
44
---
55
# Telemetry
66

7-
Altimate Code collects anonymous usage data to help us improve the product. This page describes what we collect, why, and how to opt out.
7+
Altimate Code collects usage data to help us improve the product. Events from a machine that is not signed in to Altimate are anonymous; once you sign in, events also carry your Altimate user ID and tenant (see [User Identification](#new-user-identification)). This page describes what we collect, why, and how to opt out.
88

99
## What We Collect
1010

@@ -62,8 +62,9 @@ We collect the following categories of events:
6262
| `altimate_base_register_result` | The registration outcome from a picker-driven selection (the welcome picker, the full catalogue, or the provider dialog): `success`, `rate_limited`, `unavailable`, `network`, or `error`. Optional `origin` is `welcome`, `model`, or `migration` (returning free-default users offered Altimate Base). Auto-registration at startup is reported separately, by `altimate_base_registration` above. No credential or gateway response body is included. |
6363
| `gateway_device_code_issued` | The Altimate Gateway authorize URL was built and the browser open attempted. **Name note:** the flow is a browser loopback OAuth — there is no device code. The name follows the original event spec. |
6464
| `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`. |
65-
| `instance_connected` | Credentials received and saved. `time_to_connect_ms` runs from the start of the authorize call, so it includes the browser launch. No instance or tenant name is sent. |
65+
| `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)). |
6666
| `onboarding_completed` | A model is ready and chat is live. |
67+
| `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. |
6768
| `scan_gate_shown` / `scan_gate_choice` | The "scan your environment?" gate appeared, and what the user did — `scan`, `skip`, or `dismissed` (esc / click-away). |
6869
| `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. |
6970
| `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. |
@@ -74,7 +75,7 @@ We collect the following categories of events:
7475
| `review_run` | A dbt/SQL review completed or failed — `invocation` (`cli` for `altimate-code review`, `tool` for the `dbt_pr_review` tool), status, duration, and on success the verdict, the pre-gating verdict, mode, risk tier, and finding counts by severity and by category. No file paths, model or column names, finding titles or bodies, SQL, diff content, or repository/branch/PR names. |
7576
| `review_post_outcome` | Whether a review was published to GitHub — `not_requested`, `not_attempted`, `target_unresolved`, `full`, `partial`, or `summary_failed`, plus duration. Emitted on the **CLI path only** — the `dbt_pr_review` tool completes reviews but never publishes, so a `review_run` with `invocation: tool` has no post event and that is not a failure. Within the CLI path there is exactly one per **completed** review: a review that failed emits `review_run: failed` and no post event, so absence there means the review failed rather than that an event was lost. `not_attempted` is publication requested but never reached (a bad `--output` path, a stdout write error). No repository, PR, or comment content. |
7677

77-
Each event includes a timestamp, anonymous 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 an anonymous machine ID (a random UUID stored in `~/.altimate/machine-id`, generated once and never tied to any personal information).
78+
Each event 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).
7879

7980
### Notes on the review events
8081

@@ -133,7 +134,13 @@ You can also set the environment variable:
133134
export ALTIMATE_TELEMETRY_DISABLED=true
134135
```
135136

136-
When telemetry is disabled, no events are sent and no network requests are made to the telemetry endpoint.
137+
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.
138+
139+
- The event is sent only if `~/.altimate/machine-id` already exists. A machine that never ran with telemetry on sends nothing.
140+
- 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.
141+
- While the event is being sent, a short-lived `~/.altimate/telemetry-opted-out.sending` file stops a second process from sending it too.
142+
- Turning telemetry back on removes the marker, so a later opt-out is recorded again.
143+
- No account lookup is made while telemetry is disabled.
137144

138145
### Test runs are excluded
139146

@@ -161,20 +168,20 @@ We take your privacy seriously. Altimate Code telemetry **never** collects:
161168
- Code content, file contents, or file paths
162169
- Credentials, API keys, or tokens
163170
- Database connection strings or hostnames
164-
- Personally identifiable information (your email is SHA-256 hashed before sending and is used only for anonymous user correlation)
171+
- Your email address, in any form (when you are signed in, events carry your Altimate user ID and tenant instead — see below)
165172
- Tool arguments or outputs
166173
- AI prompt content or responses
167174

168175
Error messages are truncated to 500 characters and scrubbed of file paths before sending.
169176

170177
### New User Identification
171178

172-
Altimate Code uses two types of anonymous identifiers for analytics, depending on whether you are logged in:
179+
What identifies the sender of an event depends on whether the machine is signed in to Altimate:
173180

174-
- **Anonymous users (not logged in):** A random UUID is generated using `crypto.randomUUID()` on first run and stored at `~/.altimate/machine-id`. This ID is not tied to your hardware, operating system, or identity — it is purely random and serves only to distinguish one machine from another in aggregate analytics.
175-
- **Logged-in users (OAuth):** Your email address is SHA-256 hashed before sending. The raw email is never transmitted.
181+
- **Not signed in:** A random UUID is generated using `crypto.randomUUID()` on first run and stored at `~/.altimate/machine-id`. This ID is not tied to your hardware, operating system, or identity — it is purely random and serves only to distinguish one machine from another in aggregate analytics. It is also the Application Insights user ID (`ai.user.id`).
182+
- **Signed in to Altimate:** Events also carry `user_id`, your Altimate user ID (a UUID), and `tenant`, the name of your Altimate instance; `ai.user.id` is your user ID instead of the machine ID. These identify your account, so signed-in events are not anonymous. To find them, Altimate Code makes one `GET /users/me` request to the Altimate API with the credential you signed in with, and caches the answer at `~/.altimate/telemetry-identity.json` (readable only by you). The cache holds the user ID, the tenant and a fingerprint of the credential — no API key or token. A new credential is looked up again; a sign-out, or a credential the API rejects, removes the cache. No email address, hashed or not, is sent.
176183

177-
Both identifiers are only sent when telemetry is enabled. Disable telemetry entirely with `ALTIMATE_TELEMETRY_DISABLED=true` or the config option above.
184+
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.
178185

179186
### CLI Authentication Flow
180187

‎packages/opencode/src/altimate/api/client.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import path from "path"
33
import { rm } from "node:fs/promises"
44
import { Global } from "../../global"
55
import { Filesystem } from "../../util/filesystem"
6+
import { InstallationVersion } from "@opencode-ai/core/installation/version"
67

78
const DEFAULT_MCP_URL = "https://mcpserver.getaltimate.com/sse"
89
// altimate_change start — default Altimate API URL when user omits it from the TUI credential entry
@@ -66,6 +67,12 @@ export namespace AltimateApi {
6667
return path.join(Global.Path.home, ".altimate", "altimate.json")
6768
}
6869

70+
/** Names this client on every backend call so the server can attribute create and link
71+
* calls to altimate-code rather than to the web app or the extension. */
72+
export function clientHeaders(): Record<string, string> {
73+
return { "x-altimate-client": `altimate-code/${InstallationVersion}` }
74+
}
75+
6976
export async function isConfigured(): Promise<boolean> {
7077
return Filesystem.exists(credentialsPath())
7178
}
@@ -185,6 +192,7 @@ export namespace AltimateApi {
185192
"x-tenant": creds.altimateInstanceName,
186193
Authorization: `Bearer ${creds.altimateApiKey}`,
187194
"Content-Type": "application/json",
195+
...clientHeaders(),
188196
},
189197
// altimate_change start — upstream_fix: attach abort signal
190198
signal: controller.signal,
@@ -224,6 +232,7 @@ export namespace AltimateApi {
224232
headers: {
225233
"x-tenant": instance,
226234
"Content-Type": "application/json",
235+
...clientHeaders(),
227236
},
228237
body: JSON.stringify({ token }),
229238
signal: controller.signal,
@@ -252,6 +261,7 @@ export namespace AltimateApi {
252261
"Content-Type": "application/json",
253262
Authorization: `Bearer ${creds.altimateApiKey}`,
254263
"x-tenant": creds.altimateInstanceName,
264+
...clientHeaders(),
255265
},
256266
...(body ? { body: JSON.stringify(body) } : {}),
257267
})

‎packages/opencode/src/altimate/plugin/altimate.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import open from "open"
55
import { AltimateApi } from "../api/client"
66
// altimate_change — onboarding telemetry for the gateway sign-in funnel
77
import * as OnboardingTelemetry from "../telemetry/onboarding"
8+
import { Telemetry } from "../telemetry"
89
// altimate_change — shared machine-id helper (race-safe, UUID-validated, size-capped)
910
import { getOrCreateMachineId } from "../util/machine-id"
1011
import { Config } from "@/config/config"
@@ -491,6 +492,10 @@ export async function AltimateAuthPlugin(_input: PluginInput): Promise<Hooks> {
491492
altimateInstanceName: creds.instance,
492493
altimateApiKey: authToken,
493494
})
495+
// altimate_change start — telemetry is already running in this process; stamp the
496+
// user id and tenant of the account just signed in on the events that follow.
497+
void Telemetry.refreshIdentity().catch(() => {})
498+
// altimate_change end
494499
// altimate_change start — onboarding funnel: auth succeeded and the instance
495500
// is live. The instance name is the customer's tenant identifier and is never
496501
// sent. time_to_connect_ms runs from the start of authorize() — before the
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
import path from "path"
2+
import fs from "fs/promises"
3+
import { existsSync } from "fs"
4+
import * as Effect from "effect/Effect"
5+
import { Flag, env as flagEnv } from "@opencode-ai/core/flag/flag"
6+
import { FSUtil } from "@opencode-ai/core/fs-util"
7+
import { Global } from "../../global"
8+
import { ConfigPaths } from "@/config/paths"
9+
import { ConfigManaged } from "@/config/managed"
10+
import { validateLoaded } from "@/config/config"
11+
12+
/**
13+
* Whether the user config turns telemetry off, read without an Instance.
14+
*
15+
* `Config.get()` needs an Instance, and the CLI's main thread initialises telemetry in middleware
16+
* before one exists, so there it throws. Treating that as "enabled" let an opted-out user's main
17+
* thread clear the opt-out marker and resolve their identity. This reads the same files `Config`
18+
* merges, in the same order (a later source overrides an earlier one), straight from disk:
19+
* the global config files (the legacy TOML `config` file included), `OPENCODE_CONFIG`, the project
20+
* files and `.altimate-code`/`.opencode` directories found from `directory`, the inline
21+
* `OPENCODE_CONFIG_CONTENT`, the managed config directory and macOS managed preferences. Remote and
22+
* account configs are not read (they need the network). The read emits no telemetry of its own: it
23+
* runs before telemetry knows whether it may.
24+
*
25+
* - `disabled`: the last source that sets `telemetry.disabled` sets it to `true`.
26+
* - `enabled`: no source turns it off.
27+
* - `unreadable`: some source could not be read, parsed or validated as `Config` does (a missing
28+
* `{file:}` reference, a value its schema rejects). `Config` would fail to load at all, so the
29+
* answer is unknown. Callers fail closed for anything an opt-out forbids.
30+
*/
31+
export type State = "disabled" | "enabled" | "unreadable"
32+
33+
const DIR_FILES = ["altimate-code.json", "altimate-code.jsonc", "opencode.json", "opencode.jsonc"]
34+
const GLOBAL_FILES = ["config.json", "opencode.json", "opencode.jsonc", "altimate-code.json", "altimate-code.jsonc"]
35+
36+
/** The git root above `directory`, which `Config` uses as the stop for its upward search. */
37+
function worktreeOf(directory: string): string | undefined {
38+
let dir = path.resolve(directory)
39+
while (true) {
40+
if (existsSync(path.join(dir, ".git"))) return dir
41+
const parent = path.dirname(dir)
42+
if (parent === dir) return undefined
43+
dir = parent
44+
}
45+
}
46+
47+
export async function disabledState(directory: string = process.cwd()): Promise<State> {
48+
try {
49+
let value: boolean | undefined
50+
// Any source that fails to read, parse or validate fails Config's whole load, so the answer
51+
// is unknown however the other sources set it.
52+
let unknown = false
53+
const take = (data: unknown) => {
54+
const disabled = (data as { telemetry?: { disabled?: unknown } } | undefined)?.telemetry?.disabled
55+
if (disabled === undefined) return
56+
if (typeof disabled !== "boolean") unknown = true
57+
else value = disabled
58+
}
59+
// Parse as the loader does (a missing `{file:}` reference is an error) and validate with the
60+
// loader's own schema step, so a source Config would reject cannot set the answer.
61+
const parse = async (text: string, input: string | { source: string; dir: string }) => {
62+
if (!text) return // the loader skips only an empty file; whitespace still goes to its parser
63+
const source = typeof input === "string" ? input : input.source
64+
try {
65+
take(validateLoaded(await ConfigPaths.parseText(text, input, "error", { track: false }), source))
66+
} catch {
67+
unknown = true
68+
}
69+
}
70+
const readFile = async (file: string) => {
71+
let text: string
72+
try {
73+
text = await fs.readFile(file, "utf-8")
74+
} catch (err) {
75+
if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") unknown = true
76+
return
77+
}
78+
await parse(text, file)
79+
}
80+
const readText = (text: string, source: string, dir: string) => parse(text, { source, dir })
81+
82+
for (const file of GLOBAL_FILES) await readFile(path.join(Global.Path.config, file))
83+
// The legacy TOML global config, which Config merges after the JSON files (and migrates).
84+
const legacy = path.join(Global.Path.config, "config")
85+
try {
86+
take(Bun.TOML.parse(await fs.readFile(legacy, "utf-8")))
87+
} catch (err) {
88+
if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") unknown = true
89+
}
90+
if (Flag.OPENCODE_CONFIG) await readFile(Flag.OPENCODE_CONFIG)
91+
92+
const worktree = worktreeOf(directory)
93+
const located = await Effect.runPromise(
94+
Effect.all([
95+
Flag.OPENCODE_DISABLE_PROJECT_CONFIG
96+
? Effect.succeed([] as string[])
97+
: ConfigPaths.files("opencode", directory, worktree),
98+
ConfigPaths.directories(directory, worktree),
99+
]).pipe(Effect.provide(FSUtil.defaultLayer)),
100+
)
101+
const [projectFiles, directories] = located
102+
for (const file of projectFiles) await readFile(file)
103+
for (const dir of directories) {
104+
if (dir.endsWith(".altimate-code") || dir.endsWith(".opencode") || dir === Flag.OPENCODE_CONFIG_DIR) {
105+
for (const file of DIR_FILES) await readFile(path.join(dir, file))
106+
}
107+
}
108+
109+
const inline = flagEnv("OPENCODE_CONFIG_CONTENT")
110+
if (inline) await readText(inline, "OPENCODE_CONFIG_CONTENT", directory)
111+
112+
const managedDir = ConfigManaged.managedConfigDir()
113+
if (existsSync(managedDir)) for (const file of DIR_FILES) await readFile(path.join(managedDir, file))
114+
const managed = await ConfigManaged.readManagedPreferences().catch(() => {
115+
unknown = true
116+
return undefined
117+
})
118+
if (managed) await readText(managed.text, managed.source, path.dirname(managed.source))
119+
120+
if (unknown) return "unreadable"
121+
return value ? "disabled" : "enabled"
122+
} catch {
123+
return "unreadable"
124+
}
125+
}
126+
127+
export * as TelemetryConfig from "./config-state"

0 commit comments

Comments
 (0)