@testsprite/testsprite-cli 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import { type RunConflict } from './conflict-reason.js';
1
2
  /**
2
3
  * Max time the flush-before-exit will wait on the beacon POST. Kept short so a
3
4
  * slow/unreachable backend adds at most this to a command's exit (including
@@ -17,6 +18,23 @@ export interface TelemetryOutcomeInput extends Partial<WaitTimeoutTelemetry> {
17
18
  exitCode: number;
18
19
  /** Stable machine error code (e.g. `VALIDATION_ERROR`) — never a message. */
19
20
  errorCode?: string;
21
+ /**
22
+ * Whether `errorCode` was actually classified by the backend
23
+ * ('server') or fabricated client-side ('client' — a `--wait` timeout
24
+ * conversion, local pre-flight validation, a transport failure, an
25
+ * uncaught exception, …). Without this, a client-fabricated `UNSUPPORTED`
26
+ * (the `--wait` timeout bucket, exit 7) is indistinguishable in telemetry
27
+ * from a genuine backend 501 — see `classifyCliError()` for the exact
28
+ * discriminator.
29
+ */
30
+ errorOrigin?: 'client' | 'server';
31
+ /**
32
+ * The effective timeout deadline (seconds) for an error event caused by a
33
+ * client-side timeout — either a per-request timeout (`RequestTimeoutError`)
34
+ * or a `--wait`/`--timeout` poll deadline surfaced as `UNSUPPORTED`. Absent
35
+ * for every other error.
36
+ */
37
+ timeoutSeconds?: number;
20
38
  durationMs: number;
21
39
  /** Global flags, used to resolve config + fill context. */
22
40
  profile?: string;
@@ -52,12 +70,120 @@ export interface ResolvedTelemetryAuth {
52
70
  apiKey?: string;
53
71
  apiUrl: string;
54
72
  }
73
+ export type CiProvider = 'github' | 'gitlab' | 'circleci' | 'buildkite' | 'other' | 'none';
74
+ export type CiEvent = 'push' | 'pull_request' | 'schedule' | 'workflow_dispatch' | 'other';
75
+ /**
76
+ * Which CI system the process is running under, from the standard env markers
77
+ * each vendor documents. `other` is any CI that only sets the generic `CI`
78
+ * variable; `none` is an interactive/unknown context.
79
+ */
80
+ export declare function detectCiProvider(env: NodeJS.ProcessEnv): CiProvider;
81
+ /**
82
+ * The GitHub Actions event that triggered the workflow, bucketed to a fixed
83
+ * vocabulary (`other` for everything outside it, e.g. `release`). Only
84
+ * meaningful under GitHub; undefined for every other provider and when the
85
+ * runner did not set `GITHUB_EVENT_NAME`.
86
+ */
87
+ export declare function detectCiEvent(env: NodeJS.ProcessEnv, provider: CiProvider): CiEvent | undefined;
88
+ /**
89
+ * Stable, non-reversible grouping key for a CI repository: the first 16 hex
90
+ * chars of `sha256('testsprite-ci-repo:' + slug)`. The salt prefix keeps the
91
+ * digest from matching a plain `sha256(slug)` lookup table; the slug itself
92
+ * never leaves the runner.
93
+ */
94
+ export declare function hashRepository(slug: string): string;
95
+ /** The CI-context slice of the event (provider always present; the rest only when known). */
96
+ export declare function buildCiContext(env: NodeJS.ProcessEnv): {
97
+ ciProvider: CiProvider;
98
+ ciEvent?: CiEvent;
99
+ repoHash?: string;
100
+ };
101
+ /**
102
+ * Conflict reasons the beacon accepts for `conflictReason` (the backend DTO
103
+ * whitelist-strips anything else). Deliberately a SEPARATE vocabulary from
104
+ * `conflict-reason.ts`'s rendering type: `tunnel-required` is a server reason
105
+ * this CLI has no label for yet, and `not_found` is rendered but not counted.
106
+ */
107
+ export type TelemetryConflictReason = 'in_flight' | 'insufficient_credits' | 'billing_hold' | 'mcp_view_only' | 'local_address' | 'tunnel-required' | 'error';
108
+ /**
109
+ * Low-cardinality facts a command records about its own outcome before it
110
+ * returns, merged into the one event `index.ts` fires. Counts are non-negative
111
+ * integers; enums are closed. Nothing here can carry an id, a URL, or a message.
112
+ */
113
+ export interface TelemetryExtras {
114
+ /** Batch dispatch accounting (`test run --all`, `testlist run`). */
115
+ accepted?: number;
116
+ conflicts?: number;
117
+ deferred?: number;
118
+ skipped?: number;
119
+ /** Terminal verdict counts over the polled runs (`--wait` paths; 0/1 for a single run). */
120
+ passed?: number;
121
+ failed?: number;
122
+ blocked?: number;
123
+ timedOut?: number;
124
+ /** The most frequent conflict reason of the batch. */
125
+ conflictReason?: TelemetryConflictReason;
126
+ /** `ci init` facts. */
127
+ platform?: 'github';
128
+ force?: boolean;
129
+ workflowExisted?: boolean;
130
+ projectResolved?: 'flag' | 'auto';
131
+ }
132
+ /** What callers may hand the sanitizer: the typed shape, or an arbitrary bag it filters. */
133
+ export type TelemetryExtrasInput = TelemetryExtras | Readonly<Record<string, unknown>>;
134
+ /**
135
+ * Keep only the allowlisted keys with a value of the right shape. Pure: this is
136
+ * the single gate both the sink and the event builder run, so a stray field or
137
+ * a mistyped value can never reach the wire from either direction.
138
+ */
139
+ export declare function sanitizeTelemetryExtras(partial: TelemetryExtrasInput): TelemetryExtras;
140
+ /**
141
+ * Record outcome facts for the event this process will fire. Called by a
142
+ * command just before it returns/throws; merged per key, so a later call for
143
+ * the same key wins and different commands' keys never collide. Values outside
144
+ * the allowlist (or of the wrong shape) are dropped silently — a caller can
145
+ * never widen the wire contract from here.
146
+ */
147
+ export declare function recordTelemetryExtras(partial: TelemetryExtrasInput): void;
148
+ /** Return everything recorded so far and clear the sink (one event per process). */
149
+ export declare function takeTelemetryExtras(): TelemetryExtras;
150
+ /**
151
+ * Disjoint verdict counts over a set of polled runs — `passed` + `failed` +
152
+ * `blocked` + `timedOut` = total. Unlike the CI summary's `failed` (which folds
153
+ * blocked in), `blocked` is split out here because it is the signal that
154
+ * separates a broken target from a failing assertion.
155
+ */
156
+ export declare function batchOutcomeCounts(results: ReadonlyArray<{
157
+ status: string;
158
+ }>): {
159
+ passed: number;
160
+ failed: number;
161
+ blocked: number;
162
+ timedOut: number;
163
+ };
164
+ /**
165
+ * Record a batch command's dispatch accounting (and, under `--wait`, its
166
+ * verdict counts) in one call, so `test run --all` and `testlist run` cannot
167
+ * drift in how they count. `conflictReason` is the dominant reason of the
168
+ * batch; `results` are the polled runs (omit for a non-wait dispatch).
169
+ */
170
+ export declare function recordBatchOutcome(batch: {
171
+ accepted: number;
172
+ conflicts: readonly RunConflict[];
173
+ deferred: number;
174
+ skipped: number;
175
+ results?: ReadonlyArray<{
176
+ status: string;
177
+ }>;
178
+ }): void;
55
179
  /** The exact wire body — a flat allowlist mirroring the backend DTO. */
56
- export interface TelemetryEvent extends Partial<WaitTimeoutTelemetry> {
180
+ export interface TelemetryEvent extends Partial<WaitTimeoutTelemetry>, TelemetryExtras {
57
181
  command: string;
58
182
  outcome: TelemetryOutcome;
59
183
  exitCode?: number;
60
184
  errorCode?: string;
185
+ errorOrigin?: 'client' | 'server';
186
+ timeoutSeconds?: number;
61
187
  durationMs?: number;
62
188
  cliVersion?: string;
63
189
  os?: string;
@@ -66,21 +192,61 @@ export interface TelemetryEvent extends Partial<WaitTimeoutTelemetry> {
66
192
  ci?: boolean;
67
193
  /** Present (always `true`) only for a `test run --local` invocation; absent otherwise. */
68
194
  local?: boolean;
195
+ /** The validated `TESTSPRITE_CLIENT` tag (e.g. `github-action/v1`); absent when unset/invalid. */
196
+ client?: string;
197
+ ciProvider?: CiProvider;
198
+ ciEvent?: CiEvent;
199
+ repoHash?: string;
69
200
  }
70
201
  /**
71
202
  * Map a thrown CLI error to its telemetry disposition — mirrors the exit-code
72
203
  * mapping in `index.ts`'s top-level catch so telemetry and the process exit
73
204
  * code never disagree. Pure; safe to unit-test.
205
+ *
206
+ * Every branch below now fills `errorCode` — the two fallback branches
207
+ * (`CLIError`, and the final catch-all for a non-CLIError throw) previously
208
+ * left it `undefined`, which is why a meaningful share of `test run`
209
+ * invocations and `setup` failures landed in telemetry with `errorCode=None`.
210
+ *
211
+ * `errorOrigin` ('client' | 'server') resolves a real UNSUPPORTED
212
+ * misclassification: prod data showed genuine backend 501 UNSUPPORTED
213
+ * responses are rare compared to the PostHog events carrying that code,
214
+ * because every `--wait` timeout is ALSO converted to a client-fabricated
215
+ * `UNSUPPORTED`/exit-7 envelope (exit 7 is the timeout bucket by design;
216
+ * this patch does not touch that contract, only observability).
217
+ *
218
+ * Discriminator: for an `ApiError`, `err.httpStatus !== undefined` iff the
219
+ * code came from a real HTTP response (http.ts passes `response.status` into
220
+ * `ApiError.fromEnvelope` on every non-OK response it parses) — every
221
+ * CLI-fabricated envelope (`localValidationError`, `ApiError.authRequired()`,
222
+ * `TransportError`, and every `throw ApiError.fromEnvelope({... requestId:
223
+ * 'local' ...})` timeout conversion in commands/test.ts) never passes an
224
+ * `httpStatus`, so it reads `undefined`. `requestId` was considered and
225
+ * REJECTED as the discriminator: http.ts stamps a real, non-'local'
226
+ * `x-request-id` (`newRequestId()`) on every OUTGOING request before it knows
227
+ * whether a response will ever arrive, so `TransportError` (a DNS/TLS
228
+ * failure that never got a response) carries a real requestId despite being
229
+ * 100% client-side — `requestId === 'local'` would have misclassified it as
230
+ * 'server'. All non-`ApiError` branches (`RequestTimeoutError`,
231
+ * `InterruptError`, a plain `CLIError`, `CommanderError`, and a genuinely
232
+ * uncaught exception) never involve an HTTP response at all, so they are
233
+ * unconditionally 'client'.
74
234
  */
75
235
  export declare function classifyCliError(err: unknown): {
76
236
  outcome: TelemetryOutcome;
77
237
  exitCode: number;
78
238
  errorCode?: string;
239
+ errorOrigin?: 'client' | 'server';
240
+ timeoutSeconds?: number;
79
241
  };
80
242
  /** True when the operator has opted out via either supported env var. */
81
243
  export declare function isTelemetryOptedOut(env: NodeJS.ProcessEnv): boolean;
82
- /** Assemble the allowlisted wire event. No URL / message / flag value ever. */
83
- export declare function buildTelemetryEvent(input: TelemetryOutcomeInput, env: NodeJS.ProcessEnv, isTTY: boolean): TelemetryEvent;
244
+ /**
245
+ * Assemble the allowlisted wire event. No URL / message / flag value ever.
246
+ * `extras` are the per-command facts the sink collected (re-sanitized here so a
247
+ * direct caller cannot bypass the allowlist).
248
+ */
249
+ export declare function buildTelemetryEvent(input: TelemetryOutcomeInput, env: NodeJS.ProcessEnv, isTTY: boolean, extras?: TelemetryExtrasInput): TelemetryEvent;
84
250
  /**
85
251
  * Resolve just the (apiKey, apiUrl) pair telemetry needs. Called once from the
86
252
  * `index.ts` preAction hook — BEFORE the command's own action runs — so a
@@ -19,13 +19,37 @@
19
19
  * would be cut off before delivery anyway).
20
20
  *
21
21
  * Privacy: the event is a fixed allowlist of low-cardinality, PII-free fields.
22
- * It NEVER carries target URLs, api keys, flag values, arg values, or error
23
- * messages — `errorCode` is a stable machine code, never the human message.
22
+ * It NEVER carries target URLs, api keys, arg values, error messages, or
23
+ * repository names — `errorCode` is a stable machine code, never the human
24
+ * message, and the CI repository is reduced to a salted, truncated hash so
25
+ * runs from one repo can be grouped without the slug ever leaving the runner.
26
+ * `timeoutSeconds` is the one field derived from a flag, and it is allowed
27
+ * for a narrow, checkable reason, not a case-by-case judgment call: it is the
28
+ * literal integer value of `--timeout`/`--request-timeout` as typed by the
29
+ * operator — not a path, not a URL, not free text, and not derived from
30
+ * anything the target application returned. It carries no more information
31
+ * than `exitCode` or `durationMs` already do, and is included so a `--wait`
32
+ * timeout is distinguishable from a genuinely slow backend (see `errorOrigin`
33
+ * below). Anyone auditing this allowlist can verify that reasoning against
34
+ * the two call sites that set it (`RequestTimeoutError.timeoutMs`, and the
35
+ * `ApiError` `details.timeoutSeconds` a `--wait` deadline conversion stamps)
36
+ * without having to trust a one-off exception.
37
+ *
38
+ * `errorOrigin` ('client' | 'server') and `timeoutSeconds` are sent by this
39
+ * revision of the CLI. The telemetry endpoint validates against an allowlist
40
+ * and silently DROPS fields it does not declare rather than rejecting the
41
+ * request, so a server that predates these two fields accepts the event and
42
+ * discards them — inert, not an error. Declaring a field is also not enough
43
+ * on its own: the server has a separate mapping step onto the analytics
44
+ * event, so a field can pass validation and still not be recorded.
24
45
  */
46
+ import { createHash } from 'node:crypto';
25
47
  import { CommanderError } from 'commander';
48
+ import { buildUserAgent, resolveClientTag } from './client-tag.js';
49
+ import { dominantConflictReason } from './conflict-reason.js';
26
50
  import { loadConfig } from './config.js';
27
51
  import { defaultCredentialsPath } from './credentials.js';
28
- import { ApiError, CLIError, InterruptError, RequestTimeoutError } from './errors.js';
52
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, extractNodeErrorCode, } from './errors.js';
29
53
  import { facadeBaseUrl } from './facade.js';
30
54
  import { VERSION } from '../version.js';
31
55
  /**
@@ -35,20 +59,234 @@ import { VERSION } from '../version.js';
35
59
  * dropping the event is the correct best-effort behavior.
36
60
  */
37
61
  export const TELEMETRY_TIMEOUT_MS = 1000;
62
+ /**
63
+ * Which CI system the process is running under, from the standard env markers
64
+ * each vendor documents. `other` is any CI that only sets the generic `CI`
65
+ * variable; `none` is an interactive/unknown context.
66
+ */
67
+ export function detectCiProvider(env) {
68
+ if (env.GITHUB_ACTIONS === 'true')
69
+ return 'github';
70
+ if (isTruthyEnv(env.GITLAB_CI))
71
+ return 'gitlab';
72
+ if (isTruthyEnv(env.CIRCLECI))
73
+ return 'circleci';
74
+ if (isTruthyEnv(env.BUILDKITE))
75
+ return 'buildkite';
76
+ if (isTruthyEnv(env.CI))
77
+ return 'other';
78
+ return 'none';
79
+ }
80
+ const CI_EVENTS = new Set([
81
+ 'push',
82
+ 'pull_request',
83
+ 'schedule',
84
+ 'workflow_dispatch',
85
+ ]);
86
+ /**
87
+ * The GitHub Actions event that triggered the workflow, bucketed to a fixed
88
+ * vocabulary (`other` for everything outside it, e.g. `release`). Only
89
+ * meaningful under GitHub; undefined for every other provider and when the
90
+ * runner did not set `GITHUB_EVENT_NAME`.
91
+ */
92
+ export function detectCiEvent(env, provider) {
93
+ if (provider !== 'github')
94
+ return undefined;
95
+ const name = env.GITHUB_EVENT_NAME;
96
+ if (typeof name !== 'string' || name === '')
97
+ return undefined;
98
+ return CI_EVENTS.has(name) ? name : 'other';
99
+ }
100
+ /**
101
+ * Stable, non-reversible grouping key for a CI repository: the first 16 hex
102
+ * chars of `sha256('testsprite-ci-repo:' + slug)`. The salt prefix keeps the
103
+ * digest from matching a plain `sha256(slug)` lookup table; the slug itself
104
+ * never leaves the runner.
105
+ */
106
+ export function hashRepository(slug) {
107
+ return createHash('sha256').update(`testsprite-ci-repo:${slug}`).digest('hex').slice(0, 16);
108
+ }
109
+ /** The CI-context slice of the event (provider always present; the rest only when known). */
110
+ export function buildCiContext(env) {
111
+ const ciProvider = detectCiProvider(env);
112
+ const ciEvent = detectCiEvent(env, ciProvider);
113
+ const repo = env.GITHUB_REPOSITORY;
114
+ return {
115
+ ciProvider,
116
+ ...(ciEvent !== undefined ? { ciEvent } : {}),
117
+ ...(typeof repo === 'string' && repo !== '' ? { repoHash: hashRepository(repo) } : {}),
118
+ };
119
+ }
120
+ const COUNT_KEYS = [
121
+ 'accepted',
122
+ 'conflicts',
123
+ 'deferred',
124
+ 'skipped',
125
+ 'passed',
126
+ 'failed',
127
+ 'blocked',
128
+ 'timedOut',
129
+ ];
130
+ const BOOLEAN_KEYS = ['force', 'workflowExisted'];
131
+ const ENUM_KEYS = {
132
+ conflictReason: new Set([
133
+ 'in_flight',
134
+ 'insufficient_credits',
135
+ 'billing_hold',
136
+ 'mcp_view_only',
137
+ 'local_address',
138
+ 'tunnel-required',
139
+ 'error',
140
+ ]),
141
+ platform: new Set(['github']),
142
+ projectResolved: new Set(['flag', 'auto']),
143
+ };
144
+ /**
145
+ * Keep only the allowlisted keys with a value of the right shape. Pure: this is
146
+ * the single gate both the sink and the event builder run, so a stray field or
147
+ * a mistyped value can never reach the wire from either direction.
148
+ */
149
+ export function sanitizeTelemetryExtras(partial) {
150
+ const rec = partial;
151
+ const out = {};
152
+ for (const key of COUNT_KEYS) {
153
+ const v = rec[key];
154
+ if (typeof v === 'number' && Number.isInteger(v) && v >= 0)
155
+ out[key] = v;
156
+ }
157
+ for (const key of BOOLEAN_KEYS) {
158
+ const v = rec[key];
159
+ if (typeof v === 'boolean')
160
+ out[key] = v;
161
+ }
162
+ for (const key of Object.keys(ENUM_KEYS)) {
163
+ const v = rec[key];
164
+ if (typeof v === 'string' && ENUM_KEYS[key].has(v)) {
165
+ out[key] = v;
166
+ }
167
+ }
168
+ return out;
169
+ }
170
+ /** Module-level sink: the extras the running command has recorded so far. */
171
+ let pendingExtras = {};
172
+ /**
173
+ * Record outcome facts for the event this process will fire. Called by a
174
+ * command just before it returns/throws; merged per key, so a later call for
175
+ * the same key wins and different commands' keys never collide. Values outside
176
+ * the allowlist (or of the wrong shape) are dropped silently — a caller can
177
+ * never widen the wire contract from here.
178
+ */
179
+ export function recordTelemetryExtras(partial) {
180
+ pendingExtras = { ...pendingExtras, ...sanitizeTelemetryExtras(partial) };
181
+ }
182
+ /** Return everything recorded so far and clear the sink (one event per process). */
183
+ export function takeTelemetryExtras() {
184
+ const taken = pendingExtras;
185
+ pendingExtras = {};
186
+ return taken;
187
+ }
188
+ /**
189
+ * Disjoint verdict counts over a set of polled runs — `passed` + `failed` +
190
+ * `blocked` + `timedOut` = total. Unlike the CI summary's `failed` (which folds
191
+ * blocked in), `blocked` is split out here because it is the signal that
192
+ * separates a broken target from a failing assertion.
193
+ */
194
+ export function batchOutcomeCounts(results) {
195
+ let passed = 0;
196
+ let blocked = 0;
197
+ let timedOut = 0;
198
+ for (const r of results) {
199
+ if (r.status === 'passed')
200
+ passed++;
201
+ else if (r.status === 'blocked')
202
+ blocked++;
203
+ else if (r.status === 'timeout')
204
+ timedOut++;
205
+ }
206
+ return { passed, failed: results.length - passed - blocked - timedOut, blocked, timedOut };
207
+ }
208
+ /**
209
+ * Record a batch command's dispatch accounting (and, under `--wait`, its
210
+ * verdict counts) in one call, so `test run --all` and `testlist run` cannot
211
+ * drift in how they count. `conflictReason` is the dominant reason of the
212
+ * batch; `results` are the polled runs (omit for a non-wait dispatch).
213
+ */
214
+ export function recordBatchOutcome(batch) {
215
+ recordTelemetryExtras({
216
+ accepted: batch.accepted,
217
+ conflicts: batch.conflicts.length,
218
+ deferred: batch.deferred,
219
+ skipped: batch.skipped,
220
+ conflictReason: dominantConflictReason(batch.conflicts),
221
+ ...(batch.results !== undefined ? batchOutcomeCounts(batch.results) : {}),
222
+ });
223
+ }
38
224
  /**
39
225
  * Map a thrown CLI error to its telemetry disposition — mirrors the exit-code
40
226
  * mapping in `index.ts`'s top-level catch so telemetry and the process exit
41
227
  * code never disagree. Pure; safe to unit-test.
228
+ *
229
+ * Every branch below now fills `errorCode` — the two fallback branches
230
+ * (`CLIError`, and the final catch-all for a non-CLIError throw) previously
231
+ * left it `undefined`, which is why a meaningful share of `test run`
232
+ * invocations and `setup` failures landed in telemetry with `errorCode=None`.
233
+ *
234
+ * `errorOrigin` ('client' | 'server') resolves a real UNSUPPORTED
235
+ * misclassification: prod data showed genuine backend 501 UNSUPPORTED
236
+ * responses are rare compared to the PostHog events carrying that code,
237
+ * because every `--wait` timeout is ALSO converted to a client-fabricated
238
+ * `UNSUPPORTED`/exit-7 envelope (exit 7 is the timeout bucket by design;
239
+ * this patch does not touch that contract, only observability).
240
+ *
241
+ * Discriminator: for an `ApiError`, `err.httpStatus !== undefined` iff the
242
+ * code came from a real HTTP response (http.ts passes `response.status` into
243
+ * `ApiError.fromEnvelope` on every non-OK response it parses) — every
244
+ * CLI-fabricated envelope (`localValidationError`, `ApiError.authRequired()`,
245
+ * `TransportError`, and every `throw ApiError.fromEnvelope({... requestId:
246
+ * 'local' ...})` timeout conversion in commands/test.ts) never passes an
247
+ * `httpStatus`, so it reads `undefined`. `requestId` was considered and
248
+ * REJECTED as the discriminator: http.ts stamps a real, non-'local'
249
+ * `x-request-id` (`newRequestId()`) on every OUTGOING request before it knows
250
+ * whether a response will ever arrive, so `TransportError` (a DNS/TLS
251
+ * failure that never got a response) carries a real requestId despite being
252
+ * 100% client-side — `requestId === 'local'` would have misclassified it as
253
+ * 'server'. All non-`ApiError` branches (`RequestTimeoutError`,
254
+ * `InterruptError`, a plain `CLIError`, `CommanderError`, and a genuinely
255
+ * uncaught exception) never involve an HTTP response at all, so they are
256
+ * unconditionally 'client'.
42
257
  */
43
258
  export function classifyCliError(err) {
44
259
  if (err instanceof InterruptError) {
45
- return { outcome: 'abort', exitCode: err.exitCode, errorCode: 'INTERRUPTED' };
260
+ // err.code is 'INTERRUPTED' (set in its constructor) — read it rather
261
+ // than re-hardcoding the literal, so there is exactly one place that
262
+ // knows InterruptError's telemetry code.
263
+ return {
264
+ outcome: 'abort',
265
+ exitCode: err.exitCode,
266
+ errorCode: err.code,
267
+ errorOrigin: 'client',
268
+ };
46
269
  }
47
270
  if (err instanceof RequestTimeoutError) {
48
- return { outcome: 'error', exitCode: err.exitCode, errorCode: 'REQUEST_TIMEOUT' };
271
+ // err.code is 'REQUEST_TIMEOUT' (set in its constructor) — same reasoning.
272
+ return {
273
+ outcome: 'error',
274
+ exitCode: err.exitCode,
275
+ errorCode: err.code,
276
+ errorOrigin: 'client',
277
+ timeoutSeconds: Math.round(err.timeoutMs / 1000),
278
+ };
49
279
  }
50
280
  if (err instanceof ApiError) {
51
- return { outcome: 'error', exitCode: err.exitCode, errorCode: err.code };
281
+ const errorOrigin = err.httpStatus !== undefined ? 'server' : 'client';
282
+ const timeoutSeconds = err.getDetail('timeoutSeconds', (v) => typeof v === 'number');
283
+ return {
284
+ outcome: 'error',
285
+ exitCode: err.exitCode,
286
+ errorCode: err.code,
287
+ errorOrigin,
288
+ ...(timeoutSeconds !== undefined ? { timeoutSeconds } : {}),
289
+ };
52
290
  }
53
291
  if (err instanceof CommanderError) {
54
292
  // Help / version are user-requested successes (exit 0); everything else
@@ -58,12 +296,22 @@ export function classifyCliError(err) {
58
296
  err.code === 'commander.version') {
59
297
  return { outcome: 'success', exitCode: 0 };
60
298
  }
61
- return { outcome: 'error', exitCode: 5, errorCode: 'VALIDATION_ERROR' };
299
+ return {
300
+ outcome: 'error',
301
+ exitCode: 5,
302
+ errorCode: 'VALIDATION_ERROR',
303
+ errorOrigin: 'client',
304
+ };
62
305
  }
63
306
  if (err instanceof CLIError) {
64
- return { outcome: 'error', exitCode: err.exitCode };
307
+ return { outcome: 'error', exitCode: err.exitCode, errorCode: err.code, errorOrigin: 'client' };
65
308
  }
66
- return { outcome: 'error', exitCode: 1 };
309
+ return {
310
+ outcome: 'error',
311
+ exitCode: 1,
312
+ errorCode: extractNodeErrorCode(err) ?? 'UNCAUGHT_EXCEPTION',
313
+ errorOrigin: 'client',
314
+ };
67
315
  }
68
316
  /** True when the operator has opted out via either supported env var. */
69
317
  export function isTelemetryOptedOut(env) {
@@ -75,19 +323,28 @@ function isTruthyEnv(v) {
75
323
  const t = v.trim().toLowerCase();
76
324
  return t !== '' && t !== '0' && t !== 'false';
77
325
  }
78
- /** Assemble the allowlisted wire event. No URL / message / flag value ever. */
79
- export function buildTelemetryEvent(input, env, isTTY) {
326
+ /**
327
+ * Assemble the allowlisted wire event. No URL / message / flag value ever.
328
+ * `extras` are the per-command facts the sink collected (re-sanitized here so a
329
+ * direct caller cannot bypass the allowlist).
330
+ */
331
+ export function buildTelemetryEvent(input, env, isTTY, extras = {}) {
332
+ const client = resolveClientTag(env);
80
333
  return {
81
334
  command: input.command,
82
335
  outcome: input.outcome,
83
336
  exitCode: input.exitCode,
84
337
  ...(input.errorCode ? { errorCode: input.errorCode } : {}),
338
+ ...(input.errorOrigin ? { errorOrigin: input.errorOrigin } : {}),
339
+ ...(typeof input.timeoutSeconds === 'number' ? { timeoutSeconds: input.timeoutSeconds } : {}),
85
340
  durationMs: input.durationMs,
86
341
  cliVersion: VERSION,
87
342
  os: process.platform,
88
343
  nodeVersion: process.versions.node,
89
344
  ...(input.output === 'json' || input.output === 'text' ? { output: input.output } : {}),
90
345
  ci: isTruthyEnv(env.CI) || !isTTY,
346
+ ...(client !== undefined ? { client } : {}),
347
+ ...buildCiContext(env),
91
348
  ...(input.local ? { local: true } : {}),
92
349
  ...(input.outcome === 'error' && input.reason === 'wait_timeout'
93
350
  ? {
@@ -101,6 +358,7 @@ export function buildTelemetryEvent(input, env, isTTY) {
101
358
  : {}),
102
359
  }
103
360
  : {}),
361
+ ...sanitizeTelemetryExtras(extras),
104
362
  };
105
363
  }
106
364
  /**
@@ -127,6 +385,9 @@ export function resolveTelemetryAuth(opts, deps = {}) {
127
385
  * command, or when no api-key is configured.
128
386
  */
129
387
  export async function recordOutcome(input, deps = {}) {
388
+ // Drain the sink unconditionally — one event per process, and a gated-out
389
+ // flush must not leave a previous command's facts behind for the next test.
390
+ const extras = takeTelemetryExtras();
130
391
  try {
131
392
  const env = deps.env ?? process.env;
132
393
  if (isTelemetryOptedOut(env))
@@ -154,7 +415,7 @@ export async function recordOutcome(input, deps = {}) {
154
415
  return; // authenticated-only
155
416
  const url = `${facadeBaseUrl(config.apiUrl)}/telemetry`;
156
417
  const isTTY = deps.isTTY ?? process.stderr.isTTY === true;
157
- const body = buildTelemetryEvent(input, env, isTTY);
418
+ const body = buildTelemetryEvent(input, env, isTTY, extras);
158
419
  const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
159
420
  const controller = new AbortController();
160
421
  const timer = setTimeout(() => controller.abort(), TELEMETRY_TIMEOUT_MS);
@@ -167,7 +428,7 @@ export async function recordOutcome(input, deps = {}) {
167
428
  headers: {
168
429
  'content-type': 'application/json',
169
430
  'x-api-key': config.apiKey,
170
- 'user-agent': `testsprite-cli/${VERSION}`,
431
+ 'user-agent': buildUserAgent(env),
171
432
  },
172
433
  body: JSON.stringify(body),
173
434
  signal: controller.signal,
@@ -21,17 +21,36 @@ export interface VersionNoticeDeps {
21
21
  * dry-run, and non-TTY all suppress. Pure — no side effects, no process state.
22
22
  */
23
23
  export declare function shouldWarnBelowFloor(info: ServerVersionInfo, deps?: VersionNoticeDeps): boolean;
24
+ /**
25
+ * True when the below-floor state should be surfaced as a GitHub Actions
26
+ * `::warning::` annotation: running under Actions (`GITHUB_ACTIONS=true`), not
27
+ * opted out, not dry-run, and strictly below the floor. Deliberately NOT gated
28
+ * on TTY or `--output json` — an Actions job is never a TTY, and a workflow
29
+ * command is parsed by the runner from either stream, so it can ride stderr
30
+ * without touching a JSON envelope on stdout.
31
+ */
32
+ export declare function shouldWarnPinnedInActions(info: ServerVersionInfo, deps?: VersionNoticeDeps): boolean;
24
33
  /**
25
34
  * The single advisory line. Names the floor (the backend's authority) and the
26
35
  * upgrade command — it deliberately does NOT name a target release; the npm
27
36
  * update-notice is the single source of truth for the newest version.
28
37
  */
29
38
  export declare function formatBelowFloorNotice(currentVersion: string, minVersion: string): string;
39
+ /**
40
+ * The GitHub Actions workflow-command form of the advisory. Names the pinned
41
+ * (running) version, the floor it has fallen below, and the one command that
42
+ * re-pins the workflow to a current release. Both versions come from semver
43
+ * strings that already parsed (see `isBelowFloor`), so no command-data escaping
44
+ * is needed — neither can carry `%`, CR or LF.
45
+ */
46
+ export declare function formatPinnedVersionWarning(currentVersion: string, minVersion: string): string;
30
47
  /** Test-only: reset the once-per-process guard between cases. */
31
48
  export declare function resetBelowFloorNoticeState(): void;
32
49
  /**
33
50
  * Emit the below-floor advisory at most once per process. Wired to the HTTP
34
51
  * client's `onServerVersion` hook. Never throws — an advisory must not break or
35
- * delay the command it rides along with.
52
+ * delay the command it rides along with. Under GitHub Actions the advisory is
53
+ * the `::warning::` workflow command (annotates the job) instead of the plain
54
+ * TTY line; exactly one of the two is ever emitted.
36
55
  */
37
56
  export declare function noteServerVersion(info: ServerVersionInfo, deps?: VersionNoticeDeps): void;