Просмотр исходного кода

fix: require separate consent for automatic telemetry uploads

Default runtime metrics and diagnostics to off, honor global opt-outs,
and recheck diagnostic consent before sending. Include privacy
regressions and the generated source and test inventories.
saladday 2 месяцев назад
Родитель
Сommit
36bd09392a

+ 7 - 1
packages/config/src/config.ts

@@ -917,6 +917,10 @@ export interface ReviewConfig {
 export interface TelemetryConfig {
 export interface TelemetryConfig {
   /** Send anonymous TUI usage events. Disabled until the user opts in. */
   /** Send anonymous TUI usage events. Disabled until the user opts in. */
   enabled: boolean;
   enabled: boolean;
+  /** Send runtime performance metrics. Separate opt-in, disabled by default. */
+  metrics?: boolean;
+  /** Send minimized, account-linked automatic error reports. Separate opt-in, disabled by default. */
+  diagnostics?: boolean;
 }
 }
 
 
 export interface Config {
 export interface Config {
@@ -1765,7 +1769,7 @@ const DEFAULTS: Omit<
   // No status line items by default: the TUI picks its build-specific default
   // No status line items by default: the TUI picks its build-specific default
   // when `tui.statusLine` is absent.
   // when `tui.statusLine` is absent.
   tui: {},
   tui: {},
-  telemetry: { enabled: false },
+  telemetry: { enabled: false, metrics: false, diagnostics: false },
   opencode: {
   opencode: {
     xdg: {
     xdg: {
       dataIsolation: false,
       dataIsolation: false,
@@ -2098,6 +2102,8 @@ function parseTelemetryConfig(raw: unknown): TelemetryConfig {
   const enabled = Reflect.get(raw, "enabled");
   const enabled = Reflect.get(raw, "enabled");
   return {
   return {
     enabled: typeof enabled === "boolean" ? enabled : DEFAULTS.telemetry.enabled,
     enabled: typeof enabled === "boolean" ? enabled : DEFAULTS.telemetry.enabled,
+    metrics: Reflect.get(raw, "metrics") === true,
+    diagnostics: Reflect.get(raw, "diagnostics") === true,
   };
   };
 }
 }
 
 

+ 1 - 0
packages/config/src/index.ts

@@ -1,3 +1,4 @@
+export { isTelemetryChannelEnabled, type TelemetryChannel } from './telemetry-policy.js';
 export { isLocalSourceProvenanceEnabled } from './source-provenance.js';
 export { isLocalSourceProvenanceEnabled } from './source-provenance.js';
 export { writeTuiStatusLineSetting } from './tui-status-line-write.js';
 export { writeTuiStatusLineSetting } from './tui-status-line-write.js';
 export { parseRunawayGuardOverride, resolveRunawayGuardConfig } from './runaway-guard-config.js';
 export { parseRunawayGuardOverride, resolveRunawayGuardConfig } from './runaway-guard-config.js';

+ 23 - 0
packages/config/src/telemetry-policy.ts

@@ -0,0 +1,23 @@
+import { getConfig, type TelemetryConfig } from './config.js';
+
+export type TelemetryChannel = keyof TelemetryConfig;
+
+const TELEMETRY_OPT_OUT_ENV = ['MCODE_DISABLE_TELEMETRY', 'DO_NOT_TRACK'] as const;
+
+/**
+ * True only when the channel is explicitly opted in and no global opt-out is set.
+ * An unreadable config never authorizes an upload.
+ */
+export function isTelemetryChannelEnabled(
+  channel: TelemetryChannel,
+  readConfigured: () => boolean | undefined = () => getConfig().telemetry[channel],
+): boolean {
+  for (const key of TELEMETRY_OPT_OUT_ENV) {
+    if (/^(?:1|true|yes|on)$/iu.test(process.env[key]?.trim() ?? '')) return false;
+  }
+  try {
+    return readConfigured() === true;
+  } catch {
+    return false;
+  }
+}

+ 3 - 1
packages/local-runtime/src/error-reporting/reporter.ts

@@ -15,7 +15,7 @@
  * every stage; never expose them to callers or affect LLM requests, retries, or turn results.
  * every stage; never expose them to callers or affect LLM requests, retries, or turn results.
  */
  */
 
 
-import { getRuntimeBuildEnv, getRuntimeRegion } from '@mavis/config';
+import { getRuntimeBuildEnv, getRuntimeRegion, isTelemetryChannelEnabled } from '@mavis/config';
 import { LLM_ERROR_REASONS } from '@mavis/shared/llm-error-classifier';
 import { LLM_ERROR_REASONS } from '@mavis/shared/llm-error-classifier';
 
 
 import { logger } from '../common/logger.js';
 import { logger } from '../common/logger.js';
@@ -62,6 +62,7 @@ export function createDesktopErrorReporter(
 
 
   /** Read login state, encrypt each event_log, and POST the batch without letting failures affect the main flow. */
   /** Read login state, encrypt each event_log, and POST the batch without letting failures affect the main flow. */
   async function encryptAndSend(events: DesktopErrorLog[]): Promise<void> {
   async function encryptAndSend(events: DesktopErrorLog[]): Promise<void> {
+    if (!isTelemetryChannelEnabled('diagnostics', options.readTelemetryEnabled)) return;
     const authContext = options.authContextGetter?.();
     const authContext = options.authContextGetter?.();
     const token = authContext?.accessToken?.trim();
     const token = authContext?.accessToken?.trim();
     const userId = authContext?.realUserID?.trim();
     const userId = authContext?.realUserID?.trim();
@@ -103,6 +104,7 @@ export function createDesktopErrorReporter(
   return {
   return {
     report(event: DesktopErrorLog): void {
     report(event: DesktopErrorLog): void {
       try {
       try {
+        if (!isTelemetryChannelEnabled('diagnostics', options.readTelemetryEnabled)) return;
         // Drop oversized raw logs entirely, never truncate (design §2). Measure plaintext size to bound both
         // Drop oversized raw logs entirely, never truncate (design §2). Measure plaintext size to bound both
         // memory usage and the final request body.
         // memory usage and the final request body.
         const byteLength = Buffer.byteLength(event.event_log, 'utf8');
         const byteLength = Buffer.byteLength(event.event_log, 'utf8');

+ 2 - 0
packages/local-runtime/src/error-reporting/types.ts

@@ -67,6 +67,8 @@ export interface DesktopErrorReporter {
  * DESKTOP_ERROR_REPORTING_DEFAULTS}); tests may override them for deterministic results.
  * DESKTOP_ERROR_REPORTING_DEFAULTS}); tests may override them for deterministic results.
  */
  */
 export interface DesktopErrorReporterOptions {
 export interface DesktopErrorReporterOptions {
+  /** Explicit `telemetry.diagnostics` opt-in; environment opt-outs always take precedence. */
+  readTelemetryEnabled?: () => boolean | undefined;
   /** Read live login state (token and real user ID) for each send. */
   /** Read live login state (token and real user ID) for each send. */
   authContextGetter?: () => LocalRuntimeAuthContext | undefined;
   authContextGetter?: () => LocalRuntimeAuthContext | undefined;
   /** Managed-backend routing headers, consistent with other cloud calls. */
   /** Managed-backend routing headers, consistent with other cloud calls. */

+ 16 - 4
packages/local-runtime/src/runtime/host-metrics.ts

@@ -1,4 +1,9 @@
-import { getRuntimeBuildEnv, getRuntimeRegion, isManagedRuntime } from '@mavis/config';
+import {
+  getRuntimeBuildEnv,
+  getRuntimeRegion,
+  isManagedRuntime,
+  isTelemetryChannelEnabled,
+} from '@mavis/config';
 import { createPiTurnHistogramBucketsByName } from '@mavis/agent-core/pi-turn-runner';
 import { createPiTurnHistogramBucketsByName } from '@mavis/agent-core/pi-turn-runner';
 
 
 import { logger } from '../common/logger.js';
 import { logger } from '../common/logger.js';
@@ -12,6 +17,8 @@ import {
 import type { LocalRuntimeMode } from './mode.js';
 import type { LocalRuntimeMode } from './mode.js';
 
 
 export interface LocalRuntimeHostMetricsOptions {
 export interface LocalRuntimeHostMetricsOptions {
+  /** Explicit `telemetry.metrics` opt-in; environment opt-outs always take precedence. */
+  readonly readTelemetryEnabled?: () => boolean | undefined;
   readonly runtimeOwnerKind: string;
   readonly runtimeOwnerKind: string;
   readonly runtimeMode?: LocalRuntimeMode;
   readonly runtimeMode?: LocalRuntimeMode;
   readonly appVersion?: string;
   readonly appVersion?: string;
@@ -101,7 +108,9 @@ export function buildLocalRuntimeMetricsClient(
   options: LocalRuntimeHostMetricsOptions,
   options: LocalRuntimeHostMetricsOptions,
 ): MetricsClient {
 ): MetricsClient {
   const managed = isManagedRuntime();
   const managed = isManagedRuntime();
-  const reporter = options.metricsReporter ?? buildManagedReporter(managed);
+  // The built-in cloud transport additionally requires an explicit `telemetry.metrics` opt-in.
+  const cloudEnabled = managed && isTelemetryChannelEnabled('metrics', options.readTelemetryEnabled);
+  const reporter = options.metricsReporter ?? buildManagedReporter(cloudEnabled);
 
 
   const onError = (err: unknown): void => {
   const onError = (err: unknown): void => {
     logger.warn(
     logger.warn(
@@ -110,8 +119,11 @@ export function buildLocalRuntimeMetricsClient(
     );
     );
   };
   };
 
 
-  if (!managed && !options.metricsReporter) {
-    logger.info({ reason: 'unmanaged_runtime' }, 'Local runtime metrics reporter disabled');
+  if (!cloudEnabled && !options.metricsReporter) {
+    logger.info(
+      { reason: managed ? 'telemetry_metrics_opt_in_required' : 'unmanaged_runtime' },
+      'Local runtime metrics reporter disabled',
+    );
   }
   }
 
 
   return createLocalRuntimeMetricsClient({
   return createLocalRuntimeMetricsClient({

+ 40 - 1
packages/local-runtime/test/unit/error-reporting-privacy.test.ts

@@ -26,9 +26,10 @@ function receiverDecrypt(event: DesktopErrorLog): string {
   );
   );
 }
 }
 
 
-function reporterFixture() {
+function reporterFixture(readTelemetryEnabled: () => boolean | undefined = () => true) {
   const requests: Array<{ url: string; init: RequestInit }> = [];
   const requests: Array<{ url: string; init: RequestInit }> = [];
   const reporter = createDesktopErrorReporter({
   const reporter = createDesktopErrorReporter({
+    readTelemetryEnabled,
     authContextGetter: () => ({ accessToken: token, realUserID: userId }),
     authContextGetter: () => ({ accessToken: token, realUserID: userId }),
     region: () => 'en',
     region: () => 'en',
     buildEnv: () => 'prod',
     buildEnv: () => 'prod',
@@ -41,6 +42,44 @@ function reporterFixture() {
 }
 }
 
 
 describe('automatic error upload privacy boundary', () => {
 describe('automatic error upload privacy boundary', () => {
+  it.each([undefined, false])('does not upload without an explicit diagnostics opt-in (%s)', async (enabled) => {
+    const { reporter, requests } = reporterFixture(() => enabled);
+    reporter.report({ event_type: 'llm_request_failure', event_log: '{}', occurred_at_ms: 1, code_location: 'synthetic' });
+    await reporter.flush();
+    expect(requests).toEqual([]);
+  });
+
+  it.each(['MCODE_DISABLE_TELEMETRY', 'DO_NOT_TRACK'])('%s overrides the diagnostics opt-in', async (key) => {
+    vi.stubEnv(key, '1');
+    try {
+      const { reporter, requests } = reporterFixture(() => true);
+      reporter.report({ event_type: 'llm_request_failure', event_log: '{}', occurred_at_ms: 1, code_location: 'synthetic' });
+      await reporter.flush();
+      expect(requests).toEqual([]);
+    } finally {
+      vi.unstubAllEnvs();
+    }
+  });
+
+  it.each(['config', 'MCODE_DISABLE_TELEMETRY', 'DO_NOT_TRACK'])('drops buffered diagnostics when %s revokes consent before flushing', async (source) => {
+    let enabled = true;
+    const { reporter, requests } = reporterFixture(() => enabled);
+    try {
+      reporter.report({ event_type: 'llm_request_failure', event_log: '{}', occurred_at_ms: 1, code_location: 'synthetic' });
+      if (source === 'config') enabled = false;
+      else vi.stubEnv(source, '1');
+      await reporter.flush();
+      expect(requests).toEqual([]);
+      enabled = true;
+      vi.unstubAllEnvs();
+      await reporter.flush();
+      expect(requests).toEqual([]);
+    } finally {
+      await reporter.close();
+      vi.unstubAllEnvs();
+    }
+  });
+
   it('captures the final HTTP batch and decrypts it with receiver credentials without recovering provider content', async () => {
   it('captures the final HTTP batch and decrypts it with receiver credentials without recovering provider content', async () => {
     const { reporter, requests } = reporterFixture();
     const { reporter, requests } = reporterFixture();
     const headers = new Headers({
     const headers = new Headers({

+ 55 - 0
packages/local-runtime/test/unit/metrics-telemetry-privacy.test.ts

@@ -0,0 +1,55 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { buildLocalRuntimeMetricsClient } from '../../src/runtime/host-metrics.js';
+import type { MetricsClient } from '../../src/common/metrics.js';
+
+const clients: MetricsClient[] = [];
+const fetchRequest = vi.fn<typeof fetch>();
+beforeEach(() => {
+  vi.stubEnv('__MAVIS_RUNTIME_MANAGED', '1');
+  vi.stubEnv('MAVIS_BUILD_ENV', 'prod');
+  vi.stubEnv('MAVIS_REGION', 'en');
+  vi.stubEnv('MCODE_DISABLE_TELEMETRY', '');
+  vi.stubEnv('DO_NOT_TRACK', '');
+  fetchRequest.mockReset().mockResolvedValue(new Response('{}', { status: 200 }));
+  vi.stubGlobal('fetch', fetchRequest);
+});
+afterEach(async () => {
+  for (const client of clients.splice(0)) await client.close();
+  vi.unstubAllGlobals();
+  vi.unstubAllEnvs();
+});
+
+function fixture(metrics?: boolean) {
+  const client = buildLocalRuntimeMetricsClient({
+    runtimeOwnerKind: 'tui',
+    appVersion: '0.4.12',
+    readTelemetryEnabled: () => metrics,
+  });
+  clients.push(client);
+  return client;
+}
+
+describe('automatic runtime metrics consent', () => {
+  it.each([undefined, false])('does not send production metrics without an explicit opt-in (%s)', async (enabled) => {
+    const client = fixture(enabled);
+    client.counter('started_total', 1);
+    await client.flush();
+    expect(fetchRequest).not.toHaveBeenCalled();
+  });
+
+  it('sends metrics only after the metrics opt-in', async () => {
+    const client = fixture(true);
+    client.counter('started_total', 1);
+    await client.flush();
+    expect(fetchRequest).toHaveBeenCalledOnce();
+    expect(String(fetchRequest.mock.calls[0]![0])).toBe('https://agent.minimax.io/matrix/api/v1/metrics/batch');
+  });
+
+  it.each(['MCODE_DISABLE_TELEMETRY', 'DO_NOT_TRACK'])('%s overrides the metrics opt-in', async (key) => {
+    vi.stubEnv(key, '1');
+    const client = fixture(true);
+    client.counter('started_total', 1);
+    await client.flush();
+    expect(fetchRequest).not.toHaveBeenCalled();
+  });
+});

+ 15 - 4
packages/tui/src/observability/incident-reporter.ts

@@ -12,7 +12,7 @@ import {
 import { arch, platform } from 'node:os';
 import { arch, platform } from 'node:os';
 import { basename, dirname, join } from 'node:path';
 import { basename, dirname, join } from 'node:path';
 
 
-import type { MavisBuildEnv, MavisRegion } from '@mavis/config';
+import { isTelemetryChannelEnabled, type MavisBuildEnv, type MavisRegion } from '@mavis/config';
 
 
 export type TuiIncidentPhase = 'startup' | 'runtime' | 'shutdown';
 export type TuiIncidentPhase = 'startup' | 'runtime' | 'shutdown';
 export type TuiIncidentSeverity = 'fatal' | 'error' | 'warning';
 export type TuiIncidentSeverity = 'fatal' | 'error' | 'warning';
@@ -66,6 +66,8 @@ export interface TuiIncidentAuthContext {
 }
 }
 
 
 export interface CreateTuiIncidentReporterOptions {
 export interface CreateTuiIncidentReporterOptions {
+  /** Explicit `telemetry.diagnostics` opt-in; environment opt-outs always take precedence. */
+  readonly readTelemetryEnabled?: () => boolean | undefined;
   readonly dataDir: string;
   readonly dataDir: string;
   readonly appVersion: string;
   readonly appVersion: string;
   readonly region: MavisRegion;
   readonly region: MavisRegion;
@@ -313,7 +315,10 @@ class LocalTuiIncidentReporter implements TuiIncidentReporter {
       };
       };
       writeJsonAtomically(
       writeJsonAtomically(
         this.directory,
         this.directory,
-        join(this.directory, `pending-${occurredAtMs}-${incidentId}.json`),
+        join(
+          this.directory,
+          `${this.uploadEnabled() ? 'pending' : 'local'}-${occurredAtMs}-${incidentId}.json`,
+        ),
         stored,
         stored,
       );
       );
       this.prune();
       this.prune();
@@ -379,6 +384,7 @@ class LocalTuiIncidentReporter implements TuiIncidentReporter {
   }
   }
 
 
   private async drainPending(): Promise<void> {
   private async drainPending(): Promise<void> {
+    if (!this.uploadEnabled()) return;
     const resolveAuthContext = this.options.resolveAuthContext;
     const resolveAuthContext = this.options.resolveAuthContext;
     if (!resolveAuthContext) return;
     if (!resolveAuthContext) return;
     let auth: TuiIncidentAuthContext | undefined;
     let auth: TuiIncidentAuthContext | undefined;
@@ -415,7 +421,7 @@ class LocalTuiIncidentReporter implements TuiIncidentReporter {
     accessToken: string,
     accessToken: string,
     realUserID: string,
     realUserID: string,
   ): Promise<boolean> {
   ): Promise<boolean> {
-    if (this.networkDrainStopped) return false;
+    if (this.networkDrainStopped || !this.uploadEnabled()) return false;
     const requestController = new AbortController();
     const requestController = new AbortController();
     const requestTimeout = setTimeout(
     const requestTimeout = setTimeout(
       () => requestController.abort(),
       () => requestController.abort(),
@@ -502,10 +508,14 @@ class LocalTuiIncidentReporter implements TuiIncidentReporter {
     }
     }
   }
   }
 
 
+  private uploadEnabled(): boolean {
+    return isTelemetryChannelEnabled('diagnostics', this.options.readTelemetryEnabled);
+  }
+
   private prune(): void {
   private prune(): void {
     const nowMs = this.nowMs();
     const nowMs = this.nowMs();
     const incidentFiles = safeReadDirectory(this.directory)
     const incidentFiles = safeReadDirectory(this.directory)
-      .filter((entry) => /^(?:pending|sent)-.*\.json$/u.test(entry))
+      .filter((entry) => /^(?:pending|sent|local)-.*\.json$/u.test(entry))
       .flatMap((entry) => {
       .flatMap((entry) => {
         const path = join(this.directory, entry);
         const path = join(this.directory, entry);
         try {
         try {
@@ -527,6 +537,7 @@ class LocalTuiIncidentReporter implements TuiIncidentReporter {
     }
     }
     const retained = incidentFiles.filter((file) => nowMs - file.modifiedAtMs <= RETENTION_MS);
     const retained = incidentFiles.filter((file) => nowMs - file.modifiedAtMs <= RETENTION_MS);
     const deletionOrder = [
     const deletionOrder = [
+      ...retained.filter((file) => basename(file.path).startsWith('local-')),
       ...retained.filter((file) => basename(file.path).startsWith('sent-')),
       ...retained.filter((file) => basename(file.path).startsWith('sent-')),
       ...retained.filter((file) => basename(file.path).startsWith('pending-')),
       ...retained.filter((file) => basename(file.path).startsWith('pending-')),
     ];
     ];

+ 2 - 2
packages/tui/test/unit/headless-config.test.ts

@@ -58,7 +58,7 @@ describe('explicit headless config', () => {
         minCandidateKiB: 3,
         minCandidateKiB: 3,
         keepRecentRounds: 2,
         keepRecentRounds: 2,
       },
       },
-      telemetry: { enabled: true },
+      telemetry: { enabled: true, metrics: false, diagnostics: false },
     });
     });
   });
   });
 
 
@@ -87,7 +87,7 @@ describe('explicit headless config', () => {
         minCandidateKiB: 2,
         minCandidateKiB: 2,
         keepRecentRounds: 5,
         keepRecentRounds: 5,
       },
       },
-      telemetry: { enabled: false },
+      telemetry: { enabled: false, metrics: false, diagnostics: false },
     });
     });
   });
   });
 });
 });

+ 54 - 3
packages/tui/test/unit/incident-reporter-privacy.test.ts

@@ -10,6 +10,7 @@ import {
 import type {
 import type {
   TuiIncidentCapture,
   TuiIncidentCapture,
   TuiIncidentReporter,
   TuiIncidentReporter,
+  CreateTuiIncidentReporterOptions,
 } from '../../src/observability/incident-reporter.js';
 } from '../../src/observability/incident-reporter.js';
 
 
 const privateText = 'Unannounced acquisition of Example Company /home/private/client-plan.txt';
 const privateText = 'Unannounced acquisition of Example Company /home/private/client-plan.txt';
@@ -29,13 +30,19 @@ function temporaryDirectory() {
   return dataDir;
   return dataDir;
 }
 }
 
 
-function fixture(dataDir = temporaryDirectory(), authenticated = true) {
+function fixture(
+  dataDir = temporaryDirectory(),
+  authenticated = true,
+  readTelemetryEnabled: () => boolean | undefined = () => true,
+  resolveAuthContext?: CreateTuiIncidentReporterOptions['resolveAuthContext'],
+) {
   const requests: Array<{ url: string; init: RequestInit }> = [];
   const requests: Array<{ url: string; init: RequestInit }> = [];
   const fetchImpl = vi.fn<typeof fetch>(async (url, init) => {
   const fetchImpl = vi.fn<typeof fetch>(async (url, init) => {
     requests.push({ url: String(url), init: init! });
     requests.push({ url: String(url), init: init! });
     return new Response(null, { status: 204 });
     return new Response(null, { status: 204 });
   });
   });
   const reporter = createTuiIncidentReporter({
   const reporter = createTuiIncidentReporter({
+    readTelemetryEnabled,
     dataDir,
     dataDir,
     appVersion: '0.4.12',
     appVersion: '0.4.12',
     region: 'en',
     region: 'en',
@@ -46,8 +53,8 @@ function fixture(dataDir = temporaryDirectory(), authenticated = true) {
     terminal: privateText,
     terminal: privateText,
     osVersion: privateText,
     osVersion: privateText,
     tuiMode: privateText,
     tuiMode: privateText,
-    resolveAuthContext: () =>
-      authenticated ? { accessToken: token, realUserID: userId } : undefined,
+    resolveAuthContext: resolveAuthContext ?? (() =>
+      authenticated ? { accessToken: token, realUserID: userId } : undefined),
     fetchImpl,
     fetchImpl,
   });
   });
   reporters.push(reporter);
   reporters.push(reporter);
@@ -109,6 +116,50 @@ function diskRecords(directory: string) {
 }
 }
 
 
 describe('TUI automatic incident HTTP privacy boundary', () => {
 describe('TUI automatic incident HTTP privacy boundary', () => {
+  it.each([undefined, false])('keeps incidents local without an explicit diagnostics opt-in (%s)', async (enabled) => {
+    const { reporter, requests, directory } = fixture(undefined, true, () => enabled);
+    reporter.capture(input(new Error('synthetic')));
+    await reporter.drain();
+    expect(requests).toEqual([]);
+    const files = readdirSync(directory);
+    expect(files.filter((name) => name.startsWith('local-'))).toHaveLength(1);
+    expect(files.some((name) => name.startsWith('pending-'))).toBe(false);
+  });
+
+  it.each(['MCODE_DISABLE_TELEMETRY', 'DO_NOT_TRACK'])('%s overrides the diagnostics opt-in', async (key) => {
+    vi.stubEnv(key, '1');
+    try {
+      const { reporter, requests } = fixture(undefined, true, () => true);
+      reporter.capture(input(new Error('synthetic')));
+      await reporter.drain();
+      expect(requests).toEqual([]);
+    } finally {
+      vi.unstubAllEnvs();
+    }
+  });
+
+  it.each(['config', 'MCODE_DISABLE_TELEMETRY', 'DO_NOT_TRACK'])('does not upload when %s revokes consent during authentication', async (source) => {
+    let enabled = true;
+    let resolveAuth!: (auth: { accessToken: string; realUserID: string }) => void;
+    const auth = new Promise<{ accessToken: string; realUserID: string }>((resolve) => {
+      resolveAuth = resolve;
+    });
+    const resolveAuthContext = vi.fn(() => auth);
+    const { reporter, requests } = fixture(undefined, true, () => enabled, resolveAuthContext);
+    try {
+      reporter.capture(input(new Error('synthetic')));
+      const drain = reporter.drain();
+      expect(resolveAuthContext).toHaveBeenCalled();
+      if (source === 'config') enabled = false;
+      else vi.stubEnv(source, '1');
+      resolveAuth({ accessToken: token, realUserID: userId });
+      await drain;
+      expect(requests).toEqual([]);
+    } finally {
+      vi.unstubAllEnvs();
+    }
+  });
+
   it('decrypts the final fetch payload without recovering private text from any capture field', async () => {
   it('decrypts the final fetch payload without recovering private text from any capture field', async () => {
     const { reporter, requests, directory } = fixture();
     const { reporter, requests, directory } = fixture();
     const getter = vi.fn(() => privateText);
     const getter = vi.fn(() => privateText);

+ 2 - 0
release/public-source.json

@@ -447,6 +447,7 @@
     "packages/config/src/skill-evolve-config.ts",
     "packages/config/src/skill-evolve-config.ts",
     "packages/config/src/skills-config.ts",
     "packages/config/src/skills-config.ts",
     "packages/config/src/source-provenance.ts",
     "packages/config/src/source-provenance.ts",
+    "packages/config/src/telemetry-policy.ts",
     "packages/config/src/test-port/index.ts",
     "packages/config/src/test-port/index.ts",
     "packages/config/src/tool-result-compaction-config.ts",
     "packages/config/src/tool-result-compaction-config.ts",
     "packages/config/src/tui-config.ts",
     "packages/config/src/tui-config.ts",
@@ -2624,6 +2625,7 @@
     "packages/local-runtime/test/unit/local-thread-goal-orchestrator.test.ts",
     "packages/local-runtime/test/unit/local-thread-goal-orchestrator.test.ts",
     "packages/local-runtime/test/unit/local-thread-goal-store.test.ts",
     "packages/local-runtime/test/unit/local-thread-goal-store.test.ts",
     "packages/local-runtime/test/unit/local-thread-goal-wiring.test.ts",
     "packages/local-runtime/test/unit/local-thread-goal-wiring.test.ts",
+    "packages/local-runtime/test/unit/metrics-telemetry-privacy.test.ts",
     "packages/local-runtime/test/unit/thread-goal-kickoff-host.test.ts",
     "packages/local-runtime/test/unit/thread-goal-kickoff-host.test.ts",
     "packages/local-runtime/test/unit/thread-goal-verifier-contract.test.ts",
     "packages/local-runtime/test/unit/thread-goal-verifier-contract.test.ts",
     "packages/local-runtime/test/unit/thread-goal/contract.test.ts",
     "packages/local-runtime/test/unit/thread-goal/contract.test.ts",

+ 1 - 0
test/vitest-suites.json

@@ -15,6 +15,7 @@
       "packages/tui/test/unit/daily-checkin-application.test.ts",
       "packages/tui/test/unit/daily-checkin-application.test.ts",
       "packages/tui/test/unit/daily-checkin-http-gateway.test.ts",
       "packages/tui/test/unit/daily-checkin-http-gateway.test.ts",
       "packages/local-runtime/test/unit/error-reporting-privacy.test.ts",
       "packages/local-runtime/test/unit/error-reporting-privacy.test.ts",
+      "packages/local-runtime/test/unit/metrics-telemetry-privacy.test.ts",
       "packages/tui/test/unit/runtime-feedback-service.test.ts",
       "packages/tui/test/unit/runtime-feedback-service.test.ts",
       "packages/tui/test/unit/runtime-feedback-diagnostic-upload.test.ts",
       "packages/tui/test/unit/runtime-feedback-diagnostic-upload.test.ts",
       "packages/tui/test/unit/update-service.test.ts",
       "packages/tui/test/unit/update-service.test.ts",