@testsprite/testsprite-cli 0.4.0 → 0.6.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.
Files changed (56) hide show
  1. package/README.md +27 -1
  2. package/dist/commands/agent.js +17 -6
  3. package/dist/commands/auth.d.ts +46 -0
  4. package/dist/commands/auth.js +37 -2
  5. package/dist/commands/completion.d.ts +36 -0
  6. package/dist/commands/completion.js +111 -0
  7. package/dist/commands/doctor.js +20 -2
  8. package/dist/commands/init.d.ts +32 -1
  9. package/dist/commands/init.js +40 -10
  10. package/dist/commands/project.d.ts +77 -3
  11. package/dist/commands/project.js +176 -43
  12. package/dist/commands/test.d.ts +200 -10
  13. package/dist/commands/test.js +1636 -351
  14. package/dist/commands/usage.d.ts +56 -17
  15. package/dist/commands/usage.js +144 -29
  16. package/dist/index.js +132 -26
  17. package/dist/lib/browser.d.ts +6 -0
  18. package/dist/lib/browser.js +54 -0
  19. package/dist/lib/bundle.d.ts +32 -31
  20. package/dist/lib/bundle.js +125 -83
  21. package/dist/lib/client-factory.d.ts +23 -0
  22. package/dist/lib/client-factory.js +33 -1
  23. package/dist/lib/config.js +7 -3
  24. package/dist/lib/credentials.d.ts +17 -1
  25. package/dist/lib/credentials.js +175 -16
  26. package/dist/lib/dry-run/samples.js +15 -1
  27. package/dist/lib/errors.d.ts +6 -1
  28. package/dist/lib/errors.js +70 -19
  29. package/dist/lib/flaky.d.ts +12 -1
  30. package/dist/lib/flaky.js +7 -12
  31. package/dist/lib/gh-output.d.ts +84 -0
  32. package/dist/lib/gh-output.js +202 -0
  33. package/dist/lib/http.d.ts +33 -15
  34. package/dist/lib/http.js +141 -7
  35. package/dist/lib/org-render.d.ts +52 -0
  36. package/dist/lib/org-render.js +59 -0
  37. package/dist/lib/poll.js +72 -36
  38. package/dist/lib/render-error.d.ts +14 -0
  39. package/dist/lib/render-error.js +30 -0
  40. package/dist/lib/response-schemas.d.ts +83 -0
  41. package/dist/lib/response-schemas.js +282 -0
  42. package/dist/lib/runs.types.d.ts +53 -8
  43. package/dist/lib/skill-nudge.d.ts +17 -0
  44. package/dist/lib/skill-nudge.js +19 -0
  45. package/dist/lib/telemetry.d.ts +90 -0
  46. package/dist/lib/telemetry.js +171 -0
  47. package/dist/lib/text-table.d.ts +14 -0
  48. package/dist/lib/text-table.js +45 -0
  49. package/dist/lib/v3-advisory.d.ts +30 -1
  50. package/dist/lib/v3-advisory.js +35 -4
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +17 -5
  54. package/schemas/plan.schema.json +61 -0
  55. package/skills/testsprite-verify.codex.md +2 -2
  56. package/skills/testsprite-verify.skill.md +3 -3
@@ -1,4 +1,6 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, } from 'node:fs';
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { randomUUID } from 'node:crypto';
2
4
  import { homedir } from 'node:os';
3
5
  import { dirname, join } from 'node:path';
4
6
  import { localValidationError } from './errors.js';
@@ -40,6 +42,9 @@ const FIELD_TO_FILE_KEY = {
40
42
  apiKey: 'api_key',
41
43
  apiUrl: 'api_url',
42
44
  };
45
+ const CREDENTIALS_LOCK_RETRY_MS = 25;
46
+ const CREDENTIALS_LOCK_WAIT_MS = 5_000;
47
+ const CREDENTIALS_LOCK_STALE_MS = 30_000;
43
48
  export function parseCredentials(content) {
44
49
  const result = {};
45
50
  let currentEntry = null;
@@ -122,40 +127,194 @@ export function readProfile(profile, options = {}) {
122
127
  export function writeProfile(profile, entry, options = {}) {
123
128
  assertValidProfileName(profile);
124
129
  const path = resolvePath(options);
125
- const file = readCredentialsFile(options);
126
- file[profile] = { ...file[profile], ...entry };
127
- writeCredentialsAtomic(path, file);
130
+ mutateCredentialsFile(path, file => {
131
+ file[profile] = { ...file[profile], ...entry };
132
+ return file;
133
+ });
128
134
  }
129
135
  export function deleteProfile(profile, options = {}) {
130
136
  assertValidProfileName(profile);
131
137
  const path = resolvePath(options);
132
- const file = readCredentialsFile(options);
133
- if (!(profile in file))
138
+ if (!existsSync(path))
134
139
  return false;
135
- delete file[profile];
136
- if (Object.keys(file).length === 0) {
137
- writeCredentialsAtomic(path, {});
138
- }
139
- else {
140
- writeCredentialsAtomic(path, file);
141
- }
142
- return true;
140
+ let removed = false;
141
+ mutateCredentialsFile(path, file => {
142
+ if (!(profile in file))
143
+ return undefined;
144
+ removed = true;
145
+ delete file[profile];
146
+ return file;
147
+ });
148
+ return removed;
143
149
  }
144
- export function ensureRestrictiveMode(path) {
150
+ /**
151
+ * Enforce restrictive access on the credentials file after atomic writes.
152
+ * POSIX hosts use chmod(0600); Windows hosts use ACL tightening via icacls.
153
+ */
154
+ export function ensureRestrictiveMode(path, options = {}) {
145
155
  if (!existsSync(path))
146
156
  return;
157
+ if ((options.platform ?? process.platform) === 'win32') {
158
+ ensureWindowsRestrictiveAcl(path, options);
159
+ return;
160
+ }
147
161
  const overpermissive = (statSync(path).mode & 0o077) !== 0;
148
162
  if (overpermissive)
149
163
  chmodSync(path, 0o600);
150
164
  }
165
+ /**
166
+ * Restrict a Windows credentials file to the current user using icacls.
167
+ * The command is invoked with an args array so credential paths are never shell-interpreted.
168
+ */
169
+ function ensureWindowsRestrictiveAcl(path, options) {
170
+ const username = (options.env ?? process.env).USERNAME?.trim();
171
+ if (!username) {
172
+ warnWindowsAcl('could not determine the Windows username; credentials file permissions were not tightened', options);
173
+ return;
174
+ }
175
+ const run = options.spawnSync ?? spawnSync;
176
+ const result = run('icacls', [path, '/inheritance:r', '/grant:r', `${username}:F`], {
177
+ shell: false,
178
+ stdio: 'ignore',
179
+ windowsHide: true,
180
+ });
181
+ if (result.error) {
182
+ warnWindowsAcl(`icacls failed while tightening credentials file permissions: ${result.error.message}`, options);
183
+ return;
184
+ }
185
+ if (result.status !== 0) {
186
+ warnWindowsAcl(`icacls exited with status ${result.status ?? 'unknown'}; credentials file permissions may be too broad`, options);
187
+ }
188
+ }
189
+ /** Emit an explicit warning when Windows ACL tightening cannot be completed. */
190
+ function warnWindowsAcl(message, options) {
191
+ const warn = options.warn ?? ((line) => process.stderr.write(`${line}\n`));
192
+ warn(`[warning] ${message}`);
193
+ }
151
194
  function resolvePath(options) {
152
195
  return options.path ?? defaultCredentialsPath();
153
196
  }
154
- function writeCredentialsAtomic(path, file) {
197
+ function mutateCredentialsFile(path, mutate) {
155
198
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
199
+ const lock = acquireCredentialsLock(path);
200
+ try {
201
+ const file = readCredentialsFile({ path });
202
+ const nextFile = mutate(file);
203
+ if (nextFile === undefined)
204
+ return;
205
+ lock.assertHeld();
206
+ writeCredentialsAtomic(path, nextFile);
207
+ }
208
+ finally {
209
+ lock.release();
210
+ }
211
+ }
212
+ function writeCredentialsAtomic(path, file) {
156
213
  const tmp = `${path}.tmp.${process.pid}`;
157
214
  writeFileSync(tmp, serializeCredentials(file), { mode: 0o600, encoding: 'utf8' });
158
215
  renameSync(tmp, path);
159
216
  ensureRestrictiveMode(path);
160
217
  }
218
+ function acquireCredentialsLock(path) {
219
+ const lockPath = `${path}.lock`;
220
+ const deadline = Date.now() + CREDENTIALS_LOCK_WAIT_MS;
221
+ const token = `${process.pid}:${Date.now()}:${randomUUID()}`;
222
+ const lockInfo = {
223
+ pid: process.pid,
224
+ createdAt: Date.now(),
225
+ token,
226
+ };
227
+ while (true) {
228
+ try {
229
+ writeFileSync(lockPath, `${JSON.stringify(lockInfo)}\n`, {
230
+ encoding: 'utf8',
231
+ flag: 'wx',
232
+ mode: 0o600,
233
+ });
234
+ return {
235
+ assertHeld: () => assertCredentialsLockHeld(lockPath, token),
236
+ release: () => releaseCredentialsLock(lockPath, token),
237
+ };
238
+ }
239
+ catch (error) {
240
+ if (!isErrnoException(error) || error.code !== 'EEXIST') {
241
+ throw error;
242
+ }
243
+ reclaimStaleCredentialsLock(lockPath);
244
+ if (Date.now() >= deadline) {
245
+ throw localValidationError('credentialsLock', 'timed out waiting for another credential update to finish; retry the command', undefined, 'field');
246
+ }
247
+ sleepSync(CREDENTIALS_LOCK_RETRY_MS);
248
+ }
249
+ }
250
+ }
251
+ function reclaimStaleCredentialsLock(lockPath) {
252
+ let lockInfo;
253
+ try {
254
+ lockInfo = JSON.parse(readFileSync(lockPath, 'utf-8'));
255
+ }
256
+ catch {
257
+ lockInfo = undefined;
258
+ }
259
+ const createdAt = typeof lockInfo?.createdAt === 'number' ? lockInfo.createdAt : undefined;
260
+ const ageMs = createdAt === undefined ? Number.POSITIVE_INFINITY : Date.now() - createdAt;
261
+ const pid = typeof lockInfo?.pid === 'number' ? lockInfo.pid : undefined;
262
+ if (ageMs <= CREDENTIALS_LOCK_STALE_MS && (pid === undefined || isProcessAlive(pid))) {
263
+ return;
264
+ }
265
+ try {
266
+ unlinkSync(lockPath);
267
+ }
268
+ catch (error) {
269
+ if (!isErrnoException(error) || error.code !== 'ENOENT') {
270
+ throw error;
271
+ }
272
+ }
273
+ }
274
+ function assertCredentialsLockHeld(lockPath, token) {
275
+ const lockInfo = readCredentialsLockInfo(lockPath);
276
+ if (lockInfo?.token === token)
277
+ return;
278
+ throw localValidationError('credentialsLock', 'lost ownership of the credential update lock; retry the command', undefined, 'field');
279
+ }
280
+ function releaseCredentialsLock(lockPath, token) {
281
+ const lockInfo = readCredentialsLockInfo(lockPath);
282
+ if (lockInfo?.token !== token)
283
+ return;
284
+ try {
285
+ unlinkSync(lockPath);
286
+ }
287
+ catch (error) {
288
+ if (!isErrnoException(error) || error.code !== 'ENOENT') {
289
+ throw error;
290
+ }
291
+ }
292
+ }
293
+ function readCredentialsLockInfo(lockPath) {
294
+ try {
295
+ return JSON.parse(readFileSync(lockPath, 'utf-8'));
296
+ }
297
+ catch {
298
+ return undefined;
299
+ }
300
+ }
301
+ function isProcessAlive(pid) {
302
+ if (pid === process.pid)
303
+ return true;
304
+ try {
305
+ process.kill(pid, 0);
306
+ return true;
307
+ }
308
+ catch (error) {
309
+ if (isErrnoException(error) && error.code === 'ESRCH')
310
+ return false;
311
+ return true;
312
+ }
313
+ }
314
+ function isErrnoException(error) {
315
+ return error instanceof Error && 'code' in error;
316
+ }
317
+ function sleepSync(ms) {
318
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
319
+ }
161
320
  //# sourceMappingURL=credentials.js.map
@@ -59,6 +59,15 @@ const me = {
59
59
  scopes: ['read:projects', 'read:tests', 'write:tests', 'run:tests'],
60
60
  env: 'development',
61
61
  v3Enabled: true,
62
+ activeOrg: {
63
+ id: '22222222-2222-4222-8222-222222222222',
64
+ name: 'Dry Run Workspace',
65
+ plan: 'Standard',
66
+ role: 'owner',
67
+ remaining: 1650,
68
+ includedCredits: 1600,
69
+ seats: 1,
70
+ },
62
71
  };
63
72
  const projects = [
64
73
  {
@@ -291,7 +300,10 @@ const ENTRIES = [
291
300
  entry('getProject', 'GET', '/projects/{projectId}', projects[0]),
292
301
  // P6 — POST /projects (create project). The id uses a stable dry-run
293
302
  // sentinel so agents can see a coherent field shape without a real key.
303
+ // Both `projectId` (the live field) and `id` (legacy/
304
+ // fallback) are shown — see `CliCreateProjectResponse`.
294
305
  entry('createProject', 'POST', '/projects', {
306
+ projectId: 'p_dryrun_create_2026',
295
307
  id: 'p_dryrun_create_2026',
296
308
  type: 'frontend',
297
309
  name: 'Dry-run project',
@@ -299,8 +311,10 @@ const ENTRIES = [
299
311
  createdAt: '2026-05-16T00:00:00.000Z',
300
312
  updatedAt: '2026-05-16T00:00:00.000Z',
301
313
  }),
302
- // P7 — PATCH /projects/{id} (update project).
314
+ // P7 — PATCH /projects/{id} (update project). Both id
315
+ // field names shown — see `CliUpdateProjectResponse`.
303
316
  entry('updateProject', 'PATCH', '/projects/{projectId}', {
317
+ projectId: SAMPLE_PROJECT_ID,
304
318
  id: SAMPLE_PROJECT_ID,
305
319
  updatedFields: ['name'],
306
320
  updatedAt: '2026-05-16T00:00:00.000Z',
@@ -2,7 +2,7 @@
2
2
  * Error codes shared with the backend facade and the MCP plugin.
3
3
  * Must stay in sync across all three.
4
4
  */
5
- export declare const ERROR_CODES: readonly ["AUTH_REQUIRED", "AUTH_INVALID", "AUTH_FORBIDDEN", "NOT_FOUND", "VALIDATION_ERROR", "PAYLOAD_TOO_LARGE", "CONFLICT", "PRECONDITION_FAILED", "IDEMPOTENCY_BODY_MISMATCH", "RATE_LIMITED", "INSUFFICIENT_CREDITS", "FEATURE_GATED", "UNSUPPORTED", "CLIENT_TOO_OLD", "INTERNAL", "UNAVAILABLE"];
5
+ export declare const ERROR_CODES: readonly ["AUTH_REQUIRED", "AUTH_INVALID", "AUTH_FORBIDDEN", "NOT_FOUND", "VALIDATION_ERROR", "PAYLOAD_TOO_LARGE", "CONFLICT", "PRECONDITION_FAILED", "IDEMPOTENCY_BODY_MISMATCH", "RATE_LIMITED", "INSUFFICIENT_CREDITS", "FEATURE_GATED", "AMBIGUOUS_ORG", "UNSUPPORTED", "CLIENT_TOO_OLD", "INTERNAL", "UNAVAILABLE"];
6
6
  export type ErrorCode = (typeof ERROR_CODES)[number];
7
7
  export declare function isErrorCode(value: unknown): value is ErrorCode;
8
8
  /**
@@ -120,6 +120,11 @@ export declare class ApiError extends CLIError {
120
120
  *
121
121
  * Use `'field'` for JSON-body paths to avoid fabricating a `--fieldName`
122
122
  * flag that doesn't exist in the CLI surface.
123
+ *
124
+ * `reason` is trailed with a period UNLESS it already ends with one — some
125
+ * call sites compose `reason` from multiple already-punctuated sentences
126
+ * (e.g. `'... Remove --target-url.'`), and unconditionally appending a
127
+ * second period produced a doubled `..` at the end of the rendered message.
123
128
  */
124
129
  export declare function localValidationError(field: string, reason: string, accepted?: unknown, kind?: 'flag' | 'field'): ApiError;
125
130
  /**
@@ -25,24 +25,33 @@ export const ERROR_CODES = [
25
25
  // "a Portal write is in flight."
26
26
  'IDEMPOTENCY_BODY_MISMATCH',
27
27
  'RATE_LIMITED',
28
- // Client-side re-map of the credits sub-case of a RATE_LIMITED envelope.
29
- // Detected when the backend returns RATE_LIMITED (HTTP 429) with a
30
- // message matching /insufficient credits/i or details.required present.
31
- // Exit 12: non-retriable — out-of-credits cannot self-heal with retries.
32
- // The genuine per-minute throttle, 60/min/key ("Run trigger rate limit exceeded")
33
- // retains code RATE_LIMITED / exit 11 / retriable.
34
- // Note: backend will emit a distinct code in a future release; this is
35
- // CLI-side detection only, bridging the gap.
28
+ // Emitted natively by the backend as HTTP 402 with `details.required` (the
29
+ // shortfall) — non-retriable, exit 12: out-of-credits cannot self-heal with
30
+ // retries. The CLI additionally re-maps the legacy credits sub-case of a
31
+ // RATE_LIMITED envelope (message matching /insufficient credits/i or
32
+ // details.required present) for older backends. The genuine per-minute
33
+ // throttle, 60/min/key ("Run trigger rate limit exceeded") retains code
34
+ // RATE_LIMITED / exit 11 / retriable.
36
35
  'INSUFFICIENT_CREDITS',
37
- // Client-side code for plan-gated features that the server silently downgrades
38
- // rather than emitting a 4xx. Used when the CLI detects a paid-tier feature was
39
- // requested but the response shows it was not applied (e.g. autoHeal: false when
40
- // autoHeal: true was sent on a Free key). This is NOT thrown as an error by
41
- // default (the command still succeeds with verbatim replay) — it is used by
42
- // callers that want to programmatically detect plan-downgrade events.
43
- // Exit code: 13 (non-retriable). Backend follow-up: emit natively from the server
44
- // so the CLI can drop the client-side detection heuristic.
36
+ // Emitted natively by the backend as a fatal HTTP 403 when a plan-gated
37
+ // feature is requested by a tier that doesn't include it (e.g. auto-auth on
38
+ // a Free-plan org). `details` carries `{feature, plan, reason: 'plan'}`;
39
+ // exit code 13 (non-retriable) — the fix is an upgrade, not a retry.
40
+ // Distinct from silent tier DOWNGRADES (a request that still succeeds with
41
+ // the feature dropped): those are surfaced via the response's advisory
42
+ // fields, not this error.
45
43
  'FEATURE_GATED',
44
+ // Client-side re-map of the org-ambiguity sub-case of a CONFLICT (409)
45
+ // envelope. Raised when a membership-key caller's testId resolves to
46
+ // projects in more than one of their organizations (uuid-derived ids
47
+ // should not normally collide, so this is pathological — a shared-id
48
+ // union-resolution edge case, not a transient snapshot race). Detected
49
+ // when the backend returns `code: "CONFLICT"` with
50
+ // `details.reason === "ambiguous_org"`. Same exit-code family as CONFLICT
51
+ // (exit 6) but kept as a distinct code — unlike a generic CONFLICT this is
52
+ // never retried (retrying resolves the same ambiguity again) and
53
+ // `details.candidates[]` needs its own rendering.
54
+ 'AMBIGUOUS_ORG',
46
55
  'UNSUPPORTED',
47
56
  // The running CLI is older than the backend's minimum supported version.
48
57
  // Backend emits this as HTTP 426 when version enforcement is enabled. Exit
@@ -75,6 +84,7 @@ export function exitCodeFor(code) {
75
84
  case 'CONFLICT':
76
85
  case 'PRECONDITION_FAILED':
77
86
  case 'IDEMPOTENCY_BODY_MISMATCH':
87
+ case 'AMBIGUOUS_ORG':
78
88
  return 6;
79
89
  case 'UNSUPPORTED':
80
90
  return 7;
@@ -233,16 +243,22 @@ export class ApiError extends CLIError {
233
243
  *
234
244
  * Use `'field'` for JSON-body paths to avoid fabricating a `--fieldName`
235
245
  * flag that doesn't exist in the CLI surface.
246
+ *
247
+ * `reason` is trailed with a period UNLESS it already ends with one — some
248
+ * call sites compose `reason` from multiple already-punctuated sentences
249
+ * (e.g. `'... Remove --target-url.'`), and unconditionally appending a
250
+ * second period produced a doubled `..` at the end of the rendered message.
236
251
  */
237
252
  export function localValidationError(field, reason, accepted, kind = 'flag') {
238
253
  const subject = kind === 'flag'
239
254
  ? `Flag \`--${field.replace(/[A-Z]/g, ch => `-${ch.toLowerCase()}`)}\``
240
255
  : `Field \`${field}\``;
256
+ const punctuatedReason = reason.endsWith('.') ? reason : `${reason}.`;
241
257
  return ApiError.fromEnvelope({
242
258
  error: {
243
259
  code: 'VALIDATION_ERROR',
244
260
  message: 'Invalid request.',
245
- nextAction: `${subject} is invalid: ${reason}.`,
261
+ nextAction: `${subject} is invalid: ${punctuatedReason}`,
246
262
  requestId: 'local',
247
263
  details: accepted === undefined ? { field, reason } : { field, reason, accepted },
248
264
  },
@@ -298,6 +314,8 @@ function codeFromHttpStatus(status) {
298
314
  return 'VALIDATION_ERROR';
299
315
  case 401:
300
316
  return 'AUTH_INVALID';
317
+ case 402:
318
+ return 'INSUFFICIENT_CREDITS';
301
319
  case 403:
302
320
  return 'AUTH_FORBIDDEN';
303
321
  case 404:
@@ -343,6 +361,16 @@ function isInsufficientCredits(rawCode, message, details) {
343
361
  const hasCreditsMessage = /insufficient credits/i.test(message);
344
362
  return hasRequiredField || hasCreditsMessage;
345
363
  }
364
+ /**
365
+ * Detect the "ambiguous org" sub-case of a CONFLICT (409) envelope: a
366
+ * membership-key caller's testId resolved to projects in more than one of
367
+ * their organizations. `details.reason === "ambiguous_org"` is the backend's
368
+ * stable discriminator (see `CliAmbiguousTestError` server-side) — distinct
369
+ * from the default CONFLICT meaning (snapshot in flight).
370
+ */
371
+ function isAmbiguousOrgConflict(rawCode, details) {
372
+ return rawCode === 'CONFLICT' && details.reason === 'ambiguous_org';
373
+ }
346
374
  function parseEnvelopeBody(raw, httpStatus, apiUrl) {
347
375
  if (typeof raw !== 'object' || raw === null) {
348
376
  const fallbackCode = codeFromHttpStatus(httpStatus);
@@ -402,12 +430,21 @@ function parseEnvelopeBody(raw, httpStatus, apiUrl) {
402
430
  // Portal links resolve per environment from the API endpoint (dev and
403
431
  // prod portals live on different domains); unknown hosts get the route
404
432
  // only — a hardcoded domain would point at the wrong environment.
433
+ //
434
+ // V3 API keys are membership-bound: a key minted for a team org spends
435
+ // THAT org's wallet, not the holder's personal one, and there is no
436
+ // request-scoped signal here (this branch fires client-side, purely
437
+ // from the HTTP status/body) to tell which kind of key just failed. So
438
+ // this synthesized hint deliberately does NOT assert "top up your
439
+ // (personal) credits" as the only path — it offers the personal-key
440
+ // link (still correct for the common case) alongside an honest
441
+ // org-bound alternative, rather than guessing.
405
442
  const portalBase = apiUrl === undefined ? undefined : resolvePortalBase(apiUrl);
406
443
  const billingNextAction = nextAction !== ''
407
444
  ? nextAction
408
445
  : (portalBase !== undefined
409
- ? `Top up your credits at ${portalBase}/dashboard/settings/billing or upgrade your plan at ${portalBase}/pricing.`
410
- : 'Top up your credits on the portal Billing page (/dashboard/settings/billing) or upgrade your plan (/pricing).') +
446
+ ? `Top up credits at ${portalBase}/dashboard/settings/billing (personal keys) — ask an org admin if this key is organization-bound — or upgrade your plan at ${portalBase}/pricing.`
447
+ : 'Top up credits on the portal Billing page (/dashboard/settings/billing) if this is a personal key — ask an org admin if it is organization-bound — or upgrade your plan (/pricing).') +
411
448
  ' Run `testsprite usage` to check your current balance before the next run.';
412
449
  return {
413
450
  code: 'INSUFFICIENT_CREDITS',
@@ -417,6 +454,20 @@ function parseEnvelopeBody(raw, httpStatus, apiUrl) {
417
454
  details,
418
455
  };
419
456
  }
457
+ // Client-side re-map: CONFLICT with the ambiguous-org discriminator ->
458
+ // AMBIGUOUS_ORG. Same message/nextAction as the backend supplied — the
459
+ // server already writes an actionable template — but a distinct `code`
460
+ // so the retry decision (http.ts) and the candidates rendering (index.ts)
461
+ // can key off it directly instead of re-parsing `details.reason`.
462
+ if (isAmbiguousOrgConflict(rawCode, details)) {
463
+ return {
464
+ code: 'AMBIGUOUS_ORG',
465
+ message,
466
+ nextAction,
467
+ requestId,
468
+ details,
469
+ };
470
+ }
420
471
  return {
421
472
  code: rawCode,
422
473
  message,
@@ -8,6 +8,7 @@
8
8
  * (deterministic, no network / credentials), matching the repo's mock-based
9
9
  * test convention.
10
10
  */
11
+ import type { RerunAdvisory } from './runs.types.js';
11
12
  /**
12
13
  * Outcome of a single flaky-detector attempt. The first four mirror the
13
14
  * terminal `RunStatus` values; `timeout` and `error` are orchestration
@@ -55,6 +56,16 @@ export interface FlakyReport {
55
56
  verdict: FlakyVerdict;
56
57
  /** Non-passing attempts, in attempt order. */
57
58
  failures: FlakyFailure[];
59
+ /**
60
+ * Server-side advisories collected across all replay attempts and deduped
61
+ * (by `feature`+`message`) — surfaced ONCE per probe, not once per attempt.
62
+ * Empty when the server sent none, which is the common case: absent on
63
+ * every V2 response and every V3 response that isn't a V3-routed rerun
64
+ * with an explicit `autoHeal:false` opt-out (see `RerunAdvisory`). `test
65
+ * flaky` always sends `autoHeal:false`, so this is populated whenever the
66
+ * probe's reruns are routed to V3.
67
+ */
68
+ advisories: RerunAdvisory[];
58
69
  }
59
70
  /**
60
71
  * Aggregate per-attempt outcomes into a stability report.
@@ -66,7 +77,7 @@ export interface FlakyReport {
66
77
  * An empty attempt list (no runs observed) is reported as `failing` with a
67
78
  * `0` ratio — there is no evidence the test is stable.
68
79
  */
69
- export declare function summarizeFlaky(testId: string, attempts: FlakyAttempt[]): FlakyReport;
80
+ export declare function summarizeFlaky(testId: string, attempts: FlakyAttempt[], advisories?: RerunAdvisory[]): FlakyReport;
70
81
  /**
71
82
  * Exit code for the command: `0` only when the verdict is `stable` (every
72
83
  * observed attempt passed). Anything else is non-zero so CI can gate a merge
package/dist/lib/flaky.js CHANGED
@@ -1,13 +1,3 @@
1
- /**
2
- * Pure aggregation + rendering for `test flaky` — the repeat-run flaky-test
3
- * detector. This module performs no I/O: the orchestrator in
4
- * `commands/test.ts` feeds it the per-attempt outcomes, and it returns a
5
- * machine-readable stability report plus the text rendering and exit code.
6
- *
7
- * Keeping the scoring logic pure makes it trivially unit-testable in isolation
8
- * (deterministic, no network / credentials), matching the repo's mock-based
9
- * test convention.
10
- */
11
1
  /**
12
2
  * Aggregate per-attempt outcomes into a stability report.
13
3
  *
@@ -18,7 +8,7 @@
18
8
  * An empty attempt list (no runs observed) is reported as `failing` with a
19
9
  * `0` ratio — there is no evidence the test is stable.
20
10
  */
21
- export function summarizeFlaky(testId, attempts) {
11
+ export function summarizeFlaky(testId, attempts, advisories = []) {
22
12
  const runs = attempts.length;
23
13
  const passed = attempts.filter(a => a.outcome === 'passed').length;
24
14
  const failed = runs - passed;
@@ -32,7 +22,7 @@ export function summarizeFlaky(testId, attempts) {
32
22
  outcome: a.outcome,
33
23
  failureKind: a.failureKind ?? null,
34
24
  }));
35
- return { testId, runs, passed, failed, stableRatio, verdict, failures };
25
+ return { testId, runs, passed, failed, stableRatio, verdict, failures, advisories };
36
26
  }
37
27
  /**
38
28
  * Exit code for the command: `0` only when the verdict is `stable` (every
@@ -71,6 +61,11 @@ export function renderFlakyText(report) {
71
61
  lines.push(` #${f.attempt} ${rid} ${f.outcome}${kind}`);
72
62
  }
73
63
  }
64
+ if (report.advisories.length > 0) {
65
+ for (const advisory of report.advisories) {
66
+ lines.push(` [advisory] ${advisory.message}`);
67
+ }
68
+ }
74
69
  return lines.join('\n');
75
70
  }
76
71
  //# sourceMappingURL=flaky.js.map
@@ -0,0 +1,84 @@
1
+ /**
2
+ * CI-native output layer for the run path (issue #99, reshaped from
3
+ * the withdrawn top-level `ci` command per the #264 review). Covers both a
4
+ * single `test run <test-id> --wait` and the `test run --all --wait` batch.
5
+ *
6
+ * A `--wait` run presents its result in the formats CI consumes:
7
+ * (a) a stable machine summary `{total, passed, failed, timedOut, runs[]}`
8
+ * written to `--summary-file <path>` when requested,
9
+ * (b) a Markdown results table appended to `$GITHUB_STEP_SUMMARY` when
10
+ * running under GitHub Actions,
11
+ * (c) one `::error::` workflow-command line per non-passed run so failures
12
+ * annotate the PR checks tab.
13
+ * Activation: `GITHUB_ACTIONS=true` in the environment, or the explicit
14
+ * `--gh-output` flag (which forces the annotations even off-Actions, so the
15
+ * behavior is previewable locally). All writes are best-effort: a broken
16
+ * summary file must never mask the batch gate's exit code.
17
+ */
18
+ export interface CiRunRow {
19
+ testId: string;
20
+ runId?: string;
21
+ status: string;
22
+ dashboardUrl?: string;
23
+ error?: string;
24
+ }
25
+ export interface CiSummary {
26
+ total: number;
27
+ passed: number;
28
+ failed: number;
29
+ timedOut: number;
30
+ runs: CiRunRow[];
31
+ }
32
+ /**
33
+ * Reduce the batch command's JSON payload into the CI summary. The parse is
34
+ * defensive: it reads the same `accepted[]` rows the automation contract
35
+ * documents, and anything unparseable (dry-run envelope, partial output
36
+ * after a timeout) reduces to an empty run list rather than a crash.
37
+ *
38
+ * Non-dispatched work (`deferred` / `conflicts` / `notFound`) is folded in as
39
+ * non-passed rows: those buckets already force a non-zero exit (deferred /
40
+ * timeout → 7, all-conflict → 6) but were previously absent from the summary,
41
+ * so a partial batch like `1 accepted passed + 1 deferred` read as "1/1 passed"
42
+ * with no annotation. (`skippedFrontend` / `skippedIntegration` are NOT folded
43
+ * in — they exit 0 and are the Action layer's allow-partial concern.)
44
+ */
45
+ export declare function summarizeAcceptedPayload(capturedJson: string): CiSummary;
46
+ /**
47
+ * Reduce a single `test run <test-id> --wait` result into the same CI summary
48
+ * shape as the batch path, so `--gh-output` / `--summary-file` behave
49
+ * identically for a one-test CI job. Unlike the batch envelope, a single
50
+ * RunResponse carries `error` as a raw string (not `{ message }`) and
51
+ * `dashboardUrl` as `string | null`; both are normalized here.
52
+ */
53
+ export declare function summarizeSingleRun(run: {
54
+ testId?: string;
55
+ runId?: string;
56
+ status?: string;
57
+ dashboardUrl?: string | null;
58
+ error?: string | null;
59
+ }): CiSummary;
60
+ /** Markdown table for the GitHub job summary. */
61
+ export declare function renderJobSummaryMarkdown(summary: CiSummary): string;
62
+ /**
63
+ * Emit the GitHub-native surfaces. Self-gating on the standard env vars:
64
+ * `$GITHUB_STEP_SUMMARY` (a file path Actions provides) receives the Markdown
65
+ * table; `GITHUB_ACTIONS=true` enables one `::error::` workflow command per
66
+ * non-passed run on stdout (Actions parses workflow commands from stdout).
67
+ * `force` (the `--gh-output` flag) emits the annotations even off-Actions;
68
+ * the step summary still requires the env-provided file path to exist.
69
+ * Both writes are best-effort: a broken summary file must not mask the gate.
70
+ */
71
+ export declare function emitGithubOutputs(summary: CiSummary, env: NodeJS.ProcessEnv, sinks: {
72
+ stdout: (line: string) => void;
73
+ stderr: (line: string) => void;
74
+ appendFile: (path: string, content: string) => void;
75
+ /**
76
+ * Where `::error::` workflow-command lines go. Defaults to `stdout`; the
77
+ * caller passes stderr under `--output json` so the machine envelope on
78
+ * stdout stays parseable (the Actions runner processes workflow commands
79
+ * on both streams).
80
+ */
81
+ annotations?: (line: string) => void;
82
+ }, opts?: {
83
+ force?: boolean;
84
+ }): void;