@testsprite/testsprite-cli 0.12.0 → 0.13.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 (91) hide show
  1. package/README.md +11 -4
  2. package/dist/commands/agent.js +16 -13
  3. package/dist/commands/auth.d.ts +19 -0
  4. package/dist/commands/auth.js +60 -24
  5. package/dist/commands/ci.d.ts +86 -1
  6. package/dist/commands/ci.js +436 -5
  7. package/dist/commands/doctor.d.ts +2 -0
  8. package/dist/commands/doctor.js +22 -9
  9. package/dist/commands/init.js +14 -11
  10. package/dist/commands/project-env.js +9 -9
  11. package/dist/commands/project.d.ts +5 -5
  12. package/dist/commands/project.js +42 -42
  13. package/dist/commands/schedule.d.ts +2 -0
  14. package/dist/commands/schedule.js +18 -10
  15. package/dist/commands/test.d.ts +73 -27
  16. package/dist/commands/test.js +1756 -413
  17. package/dist/commands/testlist.js +49 -19
  18. package/dist/commands/tunnel.d.ts +26 -3
  19. package/dist/commands/tunnel.js +211 -14
  20. package/dist/commands/usage.d.ts +3 -0
  21. package/dist/commands/usage.js +12 -5
  22. package/dist/index.js +34 -20
  23. package/dist/lib/agent-targets.d.ts +3 -3
  24. package/dist/lib/agent-targets.js +2 -2
  25. package/dist/lib/billing-refusal.d.ts +43 -0
  26. package/dist/lib/billing-refusal.js +171 -0
  27. package/dist/lib/bundle.d.ts +5 -0
  28. package/dist/lib/bundle.js +43 -13
  29. package/dist/lib/ci-linkage.d.ts +90 -0
  30. package/dist/lib/ci-linkage.js +181 -0
  31. package/dist/lib/client-factory.d.ts +4 -1
  32. package/dist/lib/client-factory.js +23 -2
  33. package/dist/lib/config.d.ts +17 -0
  34. package/dist/lib/config.js +20 -1
  35. package/dist/lib/conflict-reason.d.ts +27 -3
  36. package/dist/lib/conflict-reason.js +53 -4
  37. package/dist/lib/credentials.js +56 -14
  38. package/dist/lib/dry-run/samples.d.ts +13 -1
  39. package/dist/lib/dry-run/samples.js +51 -7
  40. package/dist/lib/errors.d.ts +18 -11
  41. package/dist/lib/errors.js +111 -13
  42. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  43. package/dist/lib/failing-fe-resolver.js +3 -3
  44. package/dist/lib/gh-output.d.ts +1 -0
  45. package/dist/lib/gh-output.js +13 -4
  46. package/dist/lib/history-retention.d.ts +8 -0
  47. package/dist/lib/history-retention.js +24 -0
  48. package/dist/lib/http.d.ts +37 -19
  49. package/dist/lib/http.js +46 -24
  50. package/dist/lib/interrupt.d.ts +21 -13
  51. package/dist/lib/interrupt.js +32 -21
  52. package/dist/lib/junit-report.d.ts +11 -1
  53. package/dist/lib/junit-report.js +15 -3
  54. package/dist/lib/local-target.d.ts +1 -1
  55. package/dist/lib/local-target.js +1 -1
  56. package/dist/lib/plan-poll.d.ts +11 -11
  57. package/dist/lib/plan-poll.js +12 -12
  58. package/dist/lib/plans.types.d.ts +9 -9
  59. package/dist/lib/plans.types.js +3 -3
  60. package/dist/lib/poll.d.ts +2 -2
  61. package/dist/lib/poll.js +9 -3
  62. package/dist/lib/render-error.d.ts +2 -0
  63. package/dist/lib/render-error.js +13 -0
  64. package/dist/lib/response-schemas.d.ts +54 -12
  65. package/dist/lib/response-schemas.js +88 -7
  66. package/dist/lib/runs.types.d.ts +59 -10
  67. package/dist/lib/secret-file.js +72 -14
  68. package/dist/lib/skill-nudge.d.ts +6 -1
  69. package/dist/lib/skill-nudge.js +32 -5
  70. package/dist/lib/target-url-preflight.d.ts +6 -4
  71. package/dist/lib/target-url-preflight.js +64 -51
  72. package/dist/lib/target-url.js +6 -6
  73. package/dist/lib/telemetry.d.ts +4 -1
  74. package/dist/lib/telemetry.js +13 -13
  75. package/dist/lib/ticker.js +93 -4
  76. package/dist/lib/tunnel-session.d.ts +13 -0
  77. package/dist/lib/tunnel-session.js +4 -1
  78. package/dist/lib/tunnel.types.d.ts +12 -2
  79. package/dist/lib/tunnel.types.js +2 -2
  80. package/dist/lib/wait-exit.d.ts +8 -0
  81. package/dist/lib/wait-exit.js +76 -4
  82. package/dist/lib/workspace-status.d.ts +23 -0
  83. package/dist/lib/workspace-status.js +15 -0
  84. package/dist/version-guard.d.ts +7 -1
  85. package/dist/version-guard.js +19 -1
  86. package/dist/version.d.ts +1 -1
  87. package/dist/version.js +1 -1
  88. package/package.json +4 -4
  89. package/skills/testsprite-onboard.skill.md +4 -4
  90. package/skills/testsprite-verify.codex.md +59 -57
  91. package/skills/testsprite-verify.skill.md +53 -38
@@ -57,6 +57,11 @@ const FIELD_TO_FILE_KEY = {
57
57
  };
58
58
  const CREDENTIALS_LOCK_RETRY_MS = 25;
59
59
  const CREDENTIALS_LOCK_WAIT_MS = 5_000;
60
+ // On Windows a lock file that another process is closing or deleting (or that
61
+ // a scanner briefly holds) reports EPERM/EBUSY/EACCES instead of EEXIST. That
62
+ // clears within milliseconds; one that persists this long is a real permission
63
+ // problem and is surfaced as such.
64
+ const CREDENTIALS_LOCK_TRANSIENT_WAIT_MS = 1_000;
60
65
  const CREDENTIALS_LOCK_STALE_MS = 30_000;
61
66
  export function parseCredentials(content) {
62
67
  const result = {};
@@ -263,6 +268,7 @@ function acquireCredentialsLock(path) {
263
268
  createdAt: Date.now(),
264
269
  token,
265
270
  };
271
+ let transientSince;
266
272
  while (true) {
267
273
  try {
268
274
  writeFileSync(lockPath, `${JSON.stringify(lockInfo)}\n`, {
@@ -276,10 +282,30 @@ function acquireCredentialsLock(path) {
276
282
  };
277
283
  }
278
284
  catch (error) {
279
- if (!isErrnoException(error) || error.code !== 'EEXIST') {
285
+ let transient = undefined;
286
+ if (isErrnoException(error) && error.code === 'EEXIST') {
287
+ transient = reclaimStaleCredentialsLock(lockPath);
288
+ }
289
+ else if (isWindowsLockContention(error)) {
290
+ transient = error;
291
+ }
292
+ else {
280
293
  rethrowCredentialsWriteError(error);
281
294
  }
282
- reclaimStaleCredentialsLock(lockPath);
295
+ if (transient === undefined) {
296
+ transientSince = undefined;
297
+ }
298
+ else {
299
+ transientSince ??= Date.now();
300
+ if (Date.now() - transientSince >= CREDENTIALS_LOCK_TRANSIENT_WAIT_MS ||
301
+ Date.now() >= deadline) {
302
+ // Persistent, so not contention: fail exactly as the non-Windows
303
+ // path does for the same error.
304
+ if (transient === error)
305
+ rethrowCredentialsWriteError(error);
306
+ throw transient;
307
+ }
308
+ }
283
309
  if (Date.now() >= deadline) {
284
310
  throw localValidationError('credentialsLock', 'timed out waiting for another credential update to finish; retry the command', undefined, 'field');
285
311
  }
@@ -315,6 +341,10 @@ function acquireCredentialsLock(path) {
315
341
  * succeeding on the next `wx` attempt, so there is no need for this function
316
342
  * to draw that conclusion itself.
317
343
  */
344
+ /**
345
+ * Returns a Windows lock-contention error from the removal attempt so the
346
+ * caller can retry it within the transient budget; any other failure throws.
347
+ */
318
348
  function reclaimStaleCredentialsLock(lockPath) {
319
349
  let lockInfo;
320
350
  try {
@@ -346,10 +376,13 @@ function reclaimStaleCredentialsLock(lockPath) {
346
376
  unlinkSync(lockPath);
347
377
  }
348
378
  catch (error) {
349
- if (!isErrnoException(error) || error.code !== 'ENOENT') {
350
- throw error;
351
- }
379
+ if (isErrnoException(error) && error.code === 'ENOENT')
380
+ return undefined;
381
+ if (isWindowsLockContention(error))
382
+ return error;
383
+ throw error;
352
384
  }
385
+ return undefined;
353
386
  }
354
387
  function assertCredentialsLockHeld(lockPath, token) {
355
388
  const lockInfo = readCredentialsLockInfo(lockPath);
@@ -358,18 +391,27 @@ function assertCredentialsLockHeld(lockPath, token) {
358
391
  throw localValidationError('credentialsLock', 'lost ownership of the credential update lock; retry the command', undefined, 'field');
359
392
  }
360
393
  function releaseCredentialsLock(lockPath, token) {
361
- const lockInfo = readCredentialsLockInfo(lockPath);
362
- if (lockInfo?.token !== token)
363
- return;
364
- try {
365
- unlinkSync(lockPath);
366
- }
367
- catch (error) {
368
- if (!isErrnoException(error) || error.code !== 'ENOENT') {
369
- throw error;
394
+ const deadline = Date.now() + CREDENTIALS_LOCK_TRANSIENT_WAIT_MS;
395
+ while (readCredentialsLockInfo(lockPath)?.token === token) {
396
+ try {
397
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- `lockPath` is `${path}.lock`, derived from the internal credentials-file path; same risk profile as the other lock fs calls in this file.
398
+ unlinkSync(lockPath);
399
+ return;
400
+ }
401
+ catch (error) {
402
+ if (isErrnoException(error) && error.code === 'ENOENT')
403
+ return;
404
+ if (!isWindowsLockContention(error) || Date.now() >= deadline)
405
+ throw error;
406
+ sleepSync(CREDENTIALS_LOCK_RETRY_MS);
370
407
  }
371
408
  }
372
409
  }
410
+ function isWindowsLockContention(error) {
411
+ return (process.platform === 'win32' &&
412
+ isErrnoException(error) &&
413
+ (error.code === 'EPERM' || error.code === 'EBUSY' || error.code === 'EACCES'));
414
+ }
373
415
  function readCredentialsLockInfo(lockPath) {
374
416
  try {
375
417
  return JSON.parse(readFileSync(lockPath, 'utf-8'));
@@ -37,6 +37,15 @@ export interface DryRunSampleEntry {
37
37
  */
38
38
  body: (requestBody?: unknown) => unknown;
39
39
  }
40
+ /**
41
+ * Build the matcher RegExp for a route template, e.g.
42
+ * `/tests/{testId}/code` → /^\/tests\/[^/]+\/code$/. Splits on the
43
+ * `{param}` placeholders first, then regex-escapes every literal segment in
44
+ * between (including any literal backslash) so a route literal containing a
45
+ * regex metacharacter is matched literally instead of being reinterpreted as
46
+ * part of the pattern.
47
+ */
48
+ declare function buildPathPattern(pathTemplate: string): RegExp;
40
49
  /**
41
50
  * Resolve a fetch URL to its canned sample. Matches against the path
42
51
  * portion only (query string is ignored — auto-pagination's `cursor`
@@ -55,10 +64,13 @@ export interface DryRunSampleEntry {
55
64
  * `undefined`. For dry-run paths that resolve samples DIRECTLY (bypassing the
56
65
  * dry-run fetch impl, which has its own loud INTERNAL envelope for this):
57
66
  * without the throw, a lost registry entry surfaces as a raw TypeError deep
58
- * in a renderer (DEV-384 review F6 — `samples.ts` is a real merge-conflict
67
+ * in a renderer (`samples.ts` is a real merge-conflict
59
68
  * hotspot, so a silently dropped entry is a live hazard, not a hypothetical).
60
69
  */
61
70
  export declare function findSampleOrThrow(method: string, url: string, requestBody?: unknown): DryRunSampleEntry;
62
71
  export declare function findSample(method: string, url: string, requestBody?: unknown): DryRunSampleEntry | undefined;
63
72
  /** Test-only export so `samples.test.ts` can iterate the catalog. */
64
73
  export declare const DRY_RUN_SAMPLE_ENTRIES: ReadonlyArray<DryRunSampleEntry>;
74
+ /** Test-only export so `samples.test.ts` can verify the route-template matcher directly. */
75
+ export declare const buildDryRunPathPattern: typeof buildPathPattern;
76
+ export {};
@@ -10,6 +10,8 @@ const SAMPLE_TEST_ID_BLOCKED = 'test_blocked_4f7a';
10
10
  export const SAMPLE_RUN_ID = 'run_abc';
11
11
  const SAMPLE_SCHEDULE_ID = 'sch_7d21ac48';
12
12
  const SAMPLE_SCHEDULE_RUN_ID = 'exec_5c08f1b2';
13
+ const SAMPLE_TUNNEL_ID_1 = '00000000-0000-4000-8000-000000000001';
14
+ const SAMPLE_TUNNEL_ID_2 = '00000000-0000-4000-8000-000000000002';
13
15
  // Documented sentinel for `test steps --run-id run_failed_sample --dry-run`:
14
16
  // keeps wait flows on the default passed sample while still demonstrating a
15
17
  // run-scoped failed step offline.
@@ -440,10 +442,31 @@ const failedRunSample = {
440
442
  ],
441
443
  };
442
444
  const PATH_PREFIX = '/api/cli/v1';
445
+ // Regex metacharacters that must be escaped when a literal string is spliced
446
+ // into a `new RegExp(...)` source string, so the literal matches only itself.
447
+ const REGEXP_METACHAR = /[.*+?^${}()|[\]\\]/g;
448
+ function escapeRegExpLiteral(literal) {
449
+ return literal.replace(REGEXP_METACHAR, '\\$&');
450
+ }
451
+ /**
452
+ * Build the matcher RegExp for a route template, e.g.
453
+ * `/tests/{testId}/code` → /^\/tests\/[^/]+\/code$/. Splits on the
454
+ * `{param}` placeholders first, then regex-escapes every literal segment in
455
+ * between (including any literal backslash) so a route literal containing a
456
+ * regex metacharacter is matched literally instead of being reinterpreted as
457
+ * part of the pattern.
458
+ */
459
+ function buildPathPattern(pathTemplate) {
460
+ const regexSrc = pathTemplate
461
+ .split(/(\{[^}]+\})/g)
462
+ .map(part => (/^\{[^}]+\}$/.test(part) ? '[^/]+' : escapeRegExpLiteral(part)))
463
+ .join('');
464
+ return new RegExp(`^${regexSrc}$`);
465
+ }
443
466
  const ENTRIES = [
444
467
  entry('whoami', 'GET', '/me', me),
445
468
  entry('listProjects', 'GET', '/projects', pageOf(projects)),
446
- // DEV-384 V3-B — plan-generation surface. All three MUST be registered
469
+ // Plan-generation surface. All three MUST be registered
447
470
  // BEFORE `getProject`: findSample is first-match-wins and the projects/*
448
471
  // family shares the `/projects/…` prefix, so the more specific plans
449
472
  // paths are listed first (same defensive convention as `/tests/{id}/runs`
@@ -516,7 +539,7 @@ const ENTRIES = [
516
539
  caseKeys: ids.map(id => `case_dryrun_${id}`),
517
540
  };
518
541
  }),
519
- // DEV-384 piece V3-D — `project docs upload` two-step facade routes.
542
+ // `project docs upload` two-step facade routes.
520
543
  // Registered BEFORE the broader project patterns (design doc §7 ordering
521
544
  // rule; findSample is first-match-wins) and with `/docs/upload-url` before
522
545
  // `/docs`. NOT consumed by the command's dry-run path: `project docs
@@ -868,7 +891,7 @@ const ENTRIES = [
868
891
  // returning status: "failed" for `test wait --dry-run`.
869
892
  entry('getRun', 'GET', `/runs/${SAMPLE_FAILED_RUN_ID}`, failedRunSample),
870
893
  entry('getRun', 'GET', '/runs/{runId}', passedRunSample),
871
- // DEV-331 piece 3 — POST /runs/{runId}/cancel. Method-guarded in
894
+ // POST /runs/{runId}/cancel. Method-guarded in
872
895
  // `findSample` (POST vs `getRun`'s GET), so this can't be shadowed by the
873
896
  // broader `/runs/{runId}` pattern above despite sharing its path prefix.
874
897
  // `alreadyCancelled: false` — a fresh cancel is the more instructive shape
@@ -927,16 +950,35 @@ const ENTRIES = [
927
950
  entry('deleteSchedule', 'DELETE', '/schedules/{scheduleId}', {
928
951
  scheduleId: SAMPLE_SCHEDULE_ID,
929
952
  }),
953
+ entry('listTunnels', 'GET', '/tunnel', {
954
+ tunnels: [
955
+ {
956
+ clientId: SAMPLE_TUNNEL_ID_1,
957
+ status: 'online',
958
+ createdAt: '2026-01-01T00:00:00.000Z',
959
+ expiresAt: '2026-01-01T01:00:00.000Z',
960
+ },
961
+ {
962
+ clientId: SAMPLE_TUNNEL_ID_2,
963
+ status: 'offline',
964
+ createdAt: null,
965
+ expiresAt: '2026-01-01T02:00:00.000Z',
966
+ },
967
+ ],
968
+ }),
969
+ entry('getTunnelStatus', 'GET', '/tunnel/{clientId}', {
970
+ clientId: SAMPLE_TUNNEL_ID_1,
971
+ status: 'online',
972
+ expiresAt: '2026-01-01T01:00:00.000Z',
973
+ }),
930
974
  ];
931
975
  function entry(operationId, method, pathTemplate, body) {
932
- // Convert `/tests/{testId}/code` → /^\/tests\/[^/]+\/code$/
933
- const regexSrc = pathTemplate.replace(/\{[^}]+\}/g, '[^/]+').replace(/\//g, '\\/');
934
976
  const bodyFn = typeof body === 'function' ? body : () => body;
935
977
  return {
936
978
  operationId,
937
979
  method,
938
980
  pathTemplate,
939
- pattern: new RegExp(`^${regexSrc}$`),
981
+ pattern: buildPathPattern(pathTemplate),
940
982
  body: bodyFn,
941
983
  };
942
984
  }
@@ -965,7 +1007,7 @@ function pageOf(items) {
965
1007
  * `undefined`. For dry-run paths that resolve samples DIRECTLY (bypassing the
966
1008
  * dry-run fetch impl, which has its own loud INTERNAL envelope for this):
967
1009
  * without the throw, a lost registry entry surfaces as a raw TypeError deep
968
- * in a renderer (DEV-384 review F6 — `samples.ts` is a real merge-conflict
1010
+ * in a renderer (`samples.ts` is a real merge-conflict
969
1011
  * hotspot, so a silently dropped entry is a live hazard, not a hypothetical).
970
1012
  */
971
1013
  export function findSampleOrThrow(method, url, requestBody) {
@@ -1013,4 +1055,6 @@ function extractPath(url) {
1013
1055
  }
1014
1056
  /** Test-only export so `samples.test.ts` can iterate the catalog. */
1015
1057
  export const DRY_RUN_SAMPLE_ENTRIES = ENTRIES;
1058
+ /** Test-only export so `samples.test.ts` can verify the route-template matcher directly. */
1059
+ export const buildDryRunPathPattern = buildPathPattern;
1016
1060
  //# sourceMappingURL=samples.js.map
@@ -63,10 +63,9 @@ export declare const TERMINATION_EXIT_CODES: {
63
63
  };
64
64
  export type TerminationSignal = keyof typeof TERMINATION_EXIT_CODES;
65
65
  /**
66
- * User-initiated interrupt (SIGINT/SIGTERM/SIGHUP) observed while a
67
- * graceful-detach scope (the `--wait` polling window) was armed — see
68
- * `interrupt.ts::ShutdownController`. The `--wait` catch blocks render the
69
- * honest partial envelope + re-attach hint, then rethrow to `index.ts`.
66
+ * User-initiated interrupt (SIGINT/SIGTERM/SIGHUP) observed during an armed
67
+ * wait or a disarmed request. Run/wait paths mark the error so `index.ts` can give
68
+ * recovery guidance only when there is a run to re-attach to.
70
69
  *
71
70
  * Deliberately NOT in `ERROR_CODES` — on a signal the CLI
72
71
  * exits 130/143 without consulting the error catalog. The JSON-mode stderr
@@ -75,6 +74,7 @@ export type TerminationSignal = keyof typeof TERMINATION_EXIT_CODES;
75
74
  */
76
75
  export declare class InterruptError extends CLIError {
77
76
  readonly signal: TerminationSignal;
77
+ runWaitContext: boolean;
78
78
  constructor(signal: TerminationSignal);
79
79
  }
80
80
  export declare class NotImplementedError extends CLIError {
@@ -91,18 +91,18 @@ export interface ErrorEnvelope {
91
91
  error: ErrorEnvelopeBody;
92
92
  }
93
93
  /**
94
- * Server-returned API error. The CLI never invents `code`, `nextAction`,
95
- * or `requestId` — it forwards what the facade returned (or, for
96
- * locally-detected pre-flight conditions like a missing API key,
97
- * constructs an envelope with the same shape so the user sees identical
98
- * wording across paths).
94
+ * Server-returned API error. The CLI preserves the facade's nonempty
95
+ * `nextAction` and synthesizes one for billing refusals that omit it.
96
+ * Locally-detected pre-flight conditions use the same envelope shape.
99
97
  */
100
98
  export declare class ApiError extends CLIError {
101
99
  readonly code: ErrorCode;
102
100
  readonly requestId: string;
103
101
  readonly nextAction: string;
102
+ readonly serverNextAction: string;
104
103
  readonly details: Record<string, unknown>;
105
104
  readonly httpStatus: number | undefined;
105
+ readonly apiUrl: string | undefined;
106
106
  /**
107
107
  * Parsed `Retry-After` header value in milliseconds, when present on the
108
108
  * HTTP response. Only set for `RATE_LIMITED` (429) responses where the
@@ -111,7 +111,7 @@ export declare class ApiError extends CLIError {
111
111
  * absent or unparseable.
112
112
  */
113
113
  readonly retryAfterMs: number | undefined;
114
- constructor(envelope: ErrorEnvelopeBody, httpStatus?: number, retryAfterMs?: number);
114
+ constructor(envelope: ErrorEnvelopeBody, httpStatus?: number, retryAfterMs?: number, apiUrl?: string, serverNextAction?: string);
115
115
  /**
116
116
  * @param apiUrl Optional API endpoint the failing request targeted. Used to
117
117
  * resolve environment-correct portal links in synthesized `nextAction`
@@ -139,7 +139,14 @@ export declare class ApiError extends CLIError {
139
139
  * AUTH_REQUIRED template so the user sees the same thing whether the
140
140
  * miss was detected before or after sending the request.
141
141
  */
142
- static authRequired(requestId?: string): ApiError;
142
+ /**
143
+ * `profile` is supplied only when a NON-default profile was selected — by
144
+ * `--profile` or by `TESTSPRITE_PROFILE`. Naming it matters because the
145
+ * selection is invisible otherwise: a typo in either one picks a profile
146
+ * that has no credentials, and the generic message sends the reader off to
147
+ * configure the default profile they already have.
148
+ */
149
+ static authRequired(requestId?: string, profile?: string): ApiError;
143
150
  }
144
151
  /**
145
152
  * Fabricate a locally-detected VALIDATION_ERROR envelope using the same
@@ -1,4 +1,5 @@
1
1
  import { resolvePortalBase } from './facade.js';
2
+ import { classifyBillingRefusal, gateRefusalOf } from './billing-refusal.js';
2
3
  /**
3
4
  * Error codes shared with the backend facade and the MCP plugin.
4
5
  * Must stay in sync across all three.
@@ -165,10 +166,9 @@ export const TERMINATION_EXIT_CODES = {
165
166
  SIGHUP: 129, // 128 + 1
166
167
  };
167
168
  /**
168
- * User-initiated interrupt (SIGINT/SIGTERM/SIGHUP) observed while a
169
- * graceful-detach scope (the `--wait` polling window) was armed — see
170
- * `interrupt.ts::ShutdownController`. The `--wait` catch blocks render the
171
- * honest partial envelope + re-attach hint, then rethrow to `index.ts`.
169
+ * User-initiated interrupt (SIGINT/SIGTERM/SIGHUP) observed during an armed
170
+ * wait or a disarmed request. Run/wait paths mark the error so `index.ts` can give
171
+ * recovery guidance only when there is a run to re-attach to.
172
172
  *
173
173
  * Deliberately NOT in `ERROR_CODES` — on a signal the CLI
174
174
  * exits 130/143 without consulting the error catalog. The JSON-mode stderr
@@ -177,6 +177,7 @@ export const TERMINATION_EXIT_CODES = {
177
177
  */
178
178
  export class InterruptError extends CLIError {
179
179
  signal;
180
+ runWaitContext = false;
180
181
  constructor(signal) {
181
182
  super(`Interrupted by ${signal}.`, TERMINATION_EXIT_CODES[signal], 'INTERRUPTED');
182
183
  this.name = 'InterruptError';
@@ -190,11 +191,9 @@ export class NotImplementedError extends CLIError {
190
191
  }
191
192
  }
192
193
  /**
193
- * Server-returned API error. The CLI never invents `code`, `nextAction`,
194
- * or `requestId` — it forwards what the facade returned (or, for
195
- * locally-detected pre-flight conditions like a missing API key,
196
- * constructs an envelope with the same shape so the user sees identical
197
- * wording across paths).
194
+ * Server-returned API error. The CLI preserves the facade's nonempty
195
+ * `nextAction` and synthesizes one for billing refusals that omit it.
196
+ * Locally-detected pre-flight conditions use the same envelope shape.
198
197
  */
199
198
  export class ApiError extends CLIError {
200
199
  // `override`: CLIError now declares its own `code: string` (defaulting
@@ -209,8 +208,10 @@ export class ApiError extends CLIError {
209
208
  code;
210
209
  requestId;
211
210
  nextAction;
211
+ serverNextAction;
212
212
  details;
213
213
  httpStatus;
214
+ apiUrl;
214
215
  /**
215
216
  * Parsed `Retry-After` header value in milliseconds, when present on the
216
217
  * HTTP response. Only set for `RATE_LIMITED` (429) responses where the
@@ -219,14 +220,16 @@ export class ApiError extends CLIError {
219
220
  * absent or unparseable.
220
221
  */
221
222
  retryAfterMs;
222
- constructor(envelope, httpStatus, retryAfterMs) {
223
+ constructor(envelope, httpStatus, retryAfterMs, apiUrl, serverNextAction) {
223
224
  super(envelope.message, exitCodeFor(envelope.code));
224
225
  this.name = 'ApiError';
225
226
  this.code = envelope.code;
226
227
  this.requestId = envelope.requestId;
227
228
  this.nextAction = envelope.nextAction;
229
+ this.serverNextAction = serverNextAction ?? envelope.nextAction;
228
230
  this.details = envelope.details;
229
231
  this.httpStatus = httpStatus;
232
+ this.apiUrl = apiUrl;
230
233
  this.retryAfterMs = retryAfterMs;
231
234
  }
232
235
  /**
@@ -236,7 +239,17 @@ export class ApiError extends CLIError {
236
239
  */
237
240
  static fromEnvelope(raw, httpStatus, retryAfterMs, apiUrl) {
238
241
  const envelope = parseEnvelopeBody(raw, httpStatus, apiUrl);
239
- return new ApiError(envelope, httpStatus, retryAfterMs);
242
+ const serverNextAction = envelope.nextAction;
243
+ if (!envelope.nextAction) {
244
+ const refusal = classifyBillingRefusal({ ...envelope, apiUrl });
245
+ if (refusal) {
246
+ envelope.nextAction =
247
+ envelope.code === 'INSUFFICIENT_CREDITS'
248
+ ? insufficientCreditsNextAction(apiUrl)
249
+ : refusal.nextAction;
250
+ }
251
+ }
252
+ return new ApiError(envelope, httpStatus, retryAfterMs, apiUrl, serverNextAction);
240
253
  }
241
254
  /**
242
255
  * Type-safe accessor for a single key inside `details`. Avoids the
@@ -270,7 +283,31 @@ export class ApiError extends CLIError {
270
283
  * AUTH_REQUIRED template so the user sees the same thing whether the
271
284
  * miss was detected before or after sending the request.
272
285
  */
273
- static authRequired(requestId = 'local') {
286
+ /**
287
+ * `profile` is supplied only when a NON-default profile was selected — by
288
+ * `--profile` or by `TESTSPRITE_PROFILE`. Naming it matters because the
289
+ * selection is invisible otherwise: a typo in either one picks a profile
290
+ * that has no credentials, and the generic message sends the reader off to
291
+ * configure the default profile they already have.
292
+ */
293
+ static authRequired(requestId = 'local', profile) {
294
+ if (profile !== undefined) {
295
+ return new ApiError({
296
+ code: 'AUTH_REQUIRED',
297
+ // `message` stays byte-identical to the default-profile case: the
298
+ // wording is stable per error code, so callers can pattern-match on it.
299
+ // The profile belongs in the remediation and in `details`, which are
300
+ // the per-error context.
301
+ message: 'Authentication is required.',
302
+ nextAction: `No credentials are stored for profile "${profile}". Run \`testsprite setup --profile ${profile}\`` +
303
+ ' to configure it, or drop the profile selection if you did not mean to use one' +
304
+ ' (`--profile` flag, TESTSPRITE_PROFILE env var). `testsprite doctor` prints the profile in use.',
305
+ requestId,
306
+ // Safe to echo: every credential read passes the profile name through
307
+ // `assertValidProfileName` first, so it matches /^[A-Za-z0-9._-]+$/.
308
+ details: { profile },
309
+ });
310
+ }
274
311
  return new ApiError({
275
312
  code: 'AUTH_REQUIRED',
276
313
  message: 'Authentication is required.',
@@ -462,6 +499,67 @@ function parseEnvelopeBody(raw, httpStatus, apiUrl) {
462
499
  };
463
500
  }
464
501
  const obj = raw;
502
+ const wireCode = typeof obj.code === 'string' ? obj.code : '';
503
+ // The exact wire codes the workspace-gate body can send — checked on their
504
+ // own (not just the open-ended `_limit_exceeded` suffix) so a body with no
505
+ // HTTP status attached still has something narrow to match against.
506
+ const isKnownGateWireCode = wireCode === 'feature_not_entitled' ||
507
+ wireCode === 'workspace_paused' ||
508
+ wireCode === 'environment_limit_exceeded' ||
509
+ wireCode === 'testlist_limit_exceeded' ||
510
+ wireCode === 'schedule_limit_exceeded' ||
511
+ wireCode === 'github_repo_limit_exceeded' ||
512
+ wireCode === 'fixture_limit_exceeded' ||
513
+ wireCode === 'project_limit_exceeded';
514
+ // Only take this raw shape for the HTTP statuses the gate actually answers
515
+ // with (402/403) — matching purely on `code` let an unrelated 429 body that
516
+ // happens to end in `_limit_exceeded` (e.g. a future `rate_limit_exceeded`)
517
+ // get reclassified as a non-retriable FEATURE_GATED and stop being retried.
518
+ // With no status at all, only the exact known codes above qualify: the
519
+ // open-ended suffix match is too permissive without a status to corroborate it.
520
+ const takesRawGateShape = httpStatus === 402 || httpStatus === 403
521
+ ? isKnownGateWireCode || /_limit_exceeded$/.test(wireCode)
522
+ : httpStatus === undefined && isKnownGateWireCode;
523
+ if (takesRawGateShape) {
524
+ // A `reason` on the body is the server's and passes through as-is.
525
+ // Otherwise the wire code says which gate refusal it is, named as the
526
+ // gate names it.
527
+ const reason = typeof obj.reason === 'string' && obj.reason !== ''
528
+ ? obj.reason
529
+ : wireCode.endsWith('_limit_exceeded')
530
+ ? 'limit_exceeded'
531
+ : wireCode === 'workspace_paused'
532
+ ? 'paused'
533
+ : 'not_entitled';
534
+ const details = { reason };
535
+ for (const key of [
536
+ 'feature',
537
+ 'plan',
538
+ 'limit',
539
+ 'current',
540
+ 'requiredPlan',
541
+ 'orgId',
542
+ 'billingUrl',
543
+ 'action',
544
+ 'pauseKind',
545
+ 'pauseTarget',
546
+ ]) {
547
+ if (obj[key] !== undefined && obj[key] !== null)
548
+ details[key] = obj[key];
549
+ }
550
+ if (gateRefusalOf(reason) === 'limit_exceeded' && details.feature === undefined) {
551
+ details.feature = wireCode.slice(0, -'_limit_exceeded'.length);
552
+ }
553
+ return {
554
+ code: 'FEATURE_GATED',
555
+ message: typeof obj.message === 'string'
556
+ ? obj.message
557
+ : 'This action is unavailable on the current plan.',
558
+ nextAction: typeof obj.nextAction === 'string' ? obj.nextAction : '',
559
+ requestId: typeof obj.requestId === 'string' ? obj.requestId : 'unknown',
560
+ details,
561
+ };
562
+ }
465
563
  // Raw Nest/Express 404 shape: `{ message, error: "Not Found", statusCode }`.
466
564
  // The current parser was matching `obj.error` (a string) and falling to
467
565
  // `Server error.` while losing the actual `message` from the body
@@ -478,7 +576,7 @@ function parseEnvelopeBody(raw, httpStatus, apiUrl) {
478
576
  ? `${message} — endpoint not available on the current backend deployment.`
479
577
  : message,
480
578
  nextAction: isRouteMissing404
481
- ? 'Verify the CLI is targeting the right environment (check `testsprite auth status` for `env`), and confirm the backend has the corresponding M3.3 piece deployed.'
579
+ ? 'Verify the CLI is targeting the right environment (check `testsprite auth status` for `env`), and confirm that backend deployment includes this endpoint — it may need a newer backend release.'
482
580
  : '',
483
581
  requestId: 'unknown',
484
582
  details: { statusCode: obj.statusCode },
@@ -44,7 +44,7 @@ export interface ResolverOptions {
44
44
  */
45
45
  maxPages?: number;
46
46
  /**
47
- * DEV-393: the operator's pinned `failingFrontendTestId` (the static value
47
+ * The operator's pinned `failingFrontendTestId` (the static value
48
48
  * from fixtures.local.json). "Freshest failed" alone is fragile in a shared
49
49
  * project: any OTHER FE test that fails more recently than a dedicated,
50
50
  * permanently-red fixture silently steals the slot (live-reproduced
@@ -26,7 +26,7 @@
26
26
  export async function resolveFailingFrontendTestId(opts) {
27
27
  const { baseUrl, apiKey, projectId, maxPages = 5, preferredId } = opts;
28
28
  const fetchImpl = opts.fetchImpl ?? fetch;
29
- // DEV-393 (codex F3): probe the pinned fixture directly first, so the
29
+ // Probe the pinned fixture directly first, so the
30
30
  // preference cannot be defeated by the maxPages list-scan cap (a pinned
31
31
  // fixture beyond page `maxPages` would otherwise silently lose the slot to
32
32
  // an incidental fresher failure). Any probe error or non-failed status
@@ -44,7 +44,7 @@ export async function resolveFailingFrontendTestId(opts) {
44
44
  });
45
45
  if (resp.ok) {
46
46
  const test = (await resp.json());
47
- // The probe must honor the resolver's project scope (codex round 2):
47
+ // The probe must honor the resolver's project scope:
48
48
  // the list path filters by projectId server-side, so a pin that
49
49
  // points at a failed FE test in a DIFFERENT project must not win
50
50
  // here either. A response without a matching projectId (absent or
@@ -118,7 +118,7 @@ export async function resolveFailingFrontendTestId(opts) {
118
118
  reason: 'No frontend tests with status=failed found in project; falling back to static fixture',
119
119
  };
120
120
  }
121
- // DEV-393: a pinned, dedicated "always red" fixture wins over freshest
121
+ // A pinned, dedicated "always red" fixture wins over freshest
122
122
  // whenever it is still in the failed set — see the doc comment on
123
123
  // ResolverOptions.preferredId for why "freshest" alone is not enough.
124
124
  if (preferredId) {
@@ -43,6 +43,7 @@ export interface CiSummary {
43
43
  timedOut: number;
44
44
  runs: CiRunRow[];
45
45
  }
46
+ export declare function isNonDispatchedStatus(status: string): boolean;
46
47
  /**
47
48
  * Reduce the batch command's JSON payload into the CI summary. The parse is
48
49
  * defensive: it reads the same `accepted[]` rows the automation contract
@@ -1,4 +1,5 @@
1
1
  import { appendFileSync, writeFileSync } from 'node:fs';
2
+ import { describeConflict } from './conflict-reason.js';
2
3
  /**
3
4
  * Row statuses that mean "this test never ran" as opposed to "this run did not
4
5
  * pass". They count as `skipped` in the summary (not `failed`) and annotate as
@@ -12,6 +13,9 @@ const NON_DISPATCHED_STATUSES = new Set([
12
13
  'skipped',
13
14
  'no_tests',
14
15
  ]);
16
+ export function isNonDispatchedStatus(status) {
17
+ return NON_DISPATCHED_STATUSES.has(status);
18
+ }
15
19
  /**
16
20
  * Reduce a non-dispatched bucket (`deferred` / `conflicts` / `notFound`) into
17
21
  * CI rows. Items are either bare testId strings (`notFound`) or
@@ -29,7 +33,7 @@ function bucketRows(bucket, status, note) {
29
33
  testId,
30
34
  status,
31
35
  ...(currentRunId ? { runId: currentRunId } : {}),
32
- error: note,
36
+ error: typeof note === 'string' ? note : note(item),
33
37
  };
34
38
  });
35
39
  }
@@ -81,7 +85,12 @@ export function summarizeAcceptedPayload(capturedJson, opts = {}) {
81
85
  const rows = [
82
86
  ...acceptedRows,
83
87
  ...bucketRows(payload.deferred, 'deferred', 'rate-deferred (not dispatched)'),
84
- ...bucketRows(payload.conflicts, 'conflict', 'already in flight (not dispatched)'),
88
+ ...bucketRows(payload.conflicts, 'conflict', item => {
89
+ const conflict = item;
90
+ return conflict && typeof conflict.testId === 'string' && conflict.reason
91
+ ? `${describeConflict(conflict)} (not dispatched)`
92
+ : 'already in flight (not dispatched)';
93
+ }),
85
94
  // Default note is `test rerun`'s cause (a not-found id has no replayable
86
95
  // run). `testlist run` passes its own — a not-found `--case` id is one that
87
96
  // is not a member of the list — so the annotation/artifact don't state the
@@ -90,7 +99,7 @@ export function summarizeAcceptedPayload(capturedJson, opts = {}) {
90
99
  ];
91
100
  const passed = rows.filter(row => row.status === 'passed').length;
92
101
  const timedOut = rows.filter(row => row.status === 'timeout').length;
93
- const skipped = rows.filter(row => NON_DISPATCHED_STATUSES.has(row.status)).length;
102
+ const skipped = rows.filter(row => isNonDispatchedStatus(row.status)).length;
94
103
  const failed = rows.length - passed - timedOut - skipped;
95
104
  return { total: rows.length, passed, failed, skipped, timedOut, runs: rows };
96
105
  }
@@ -113,7 +122,7 @@ export function summarizeSingleRun(run) {
113
122
  };
114
123
  const passed = row.status === 'passed' ? 1 : 0;
115
124
  const timedOut = row.status === 'timeout' ? 1 : 0;
116
- const skipped = NON_DISPATCHED_STATUSES.has(row.status) ? 1 : 0;
125
+ const skipped = isNonDispatchedStatus(row.status) ? 1 : 0;
117
126
  const failed = 1 - passed - timedOut - skipped;
118
127
  return { total: 1, passed, failed, skipped, timedOut, runs: [row] };
119
128
  }
@@ -0,0 +1,8 @@
1
+ export interface HistoryRetentionMeta {
2
+ tier?: string;
3
+ retentionDays?: number | null;
4
+ hiddenCount?: number;
5
+ billingUrl?: string;
6
+ }
7
+ /** Returns no text for older backends, unlimited history, or an unhidden page. */
8
+ export declare function historyRetentionNote(meta: HistoryRetentionMeta | undefined, apiUrl: string, derived?: boolean): string | undefined;