@testsprite/testsprite-cli 0.11.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 (99) hide show
  1. package/README.md +52 -44
  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 +470 -9
  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.d.ts +90 -0
  11. package/dist/commands/project-env.js +486 -0
  12. package/dist/commands/project.d.ts +15 -5
  13. package/dist/commands/project.js +88 -92
  14. package/dist/commands/schedule.d.ts +2 -0
  15. package/dist/commands/schedule.js +18 -10
  16. package/dist/commands/test.d.ts +102 -30
  17. package/dist/commands/test.js +1949 -419
  18. package/dist/commands/testlist.js +77 -21
  19. package/dist/commands/tunnel.d.ts +26 -3
  20. package/dist/commands/tunnel.js +211 -14
  21. package/dist/commands/usage.d.ts +3 -0
  22. package/dist/commands/usage.js +12 -5
  23. package/dist/index.js +47 -23
  24. package/dist/lib/agent-targets.d.ts +3 -3
  25. package/dist/lib/agent-targets.js +2 -2
  26. package/dist/lib/billing-refusal.d.ts +43 -0
  27. package/dist/lib/billing-refusal.js +171 -0
  28. package/dist/lib/bundle.d.ts +5 -0
  29. package/dist/lib/bundle.js +43 -13
  30. package/dist/lib/ci-linkage.d.ts +90 -0
  31. package/dist/lib/ci-linkage.js +181 -0
  32. package/dist/lib/client-factory.d.ts +4 -1
  33. package/dist/lib/client-factory.js +25 -2
  34. package/dist/lib/client-tag.d.ts +13 -0
  35. package/dist/lib/client-tag.js +44 -0
  36. package/dist/lib/config.d.ts +17 -0
  37. package/dist/lib/config.js +20 -1
  38. package/dist/lib/conflict-reason.d.ts +67 -2
  39. package/dist/lib/conflict-reason.js +148 -13
  40. package/dist/lib/credentials.js +56 -14
  41. package/dist/lib/cron.js +8 -1
  42. package/dist/lib/dry-run/samples.d.ts +13 -1
  43. package/dist/lib/dry-run/samples.js +51 -7
  44. package/dist/lib/errors.d.ts +62 -12
  45. package/dist/lib/errors.js +180 -25
  46. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  47. package/dist/lib/failing-fe-resolver.js +3 -3
  48. package/dist/lib/gh-output.d.ts +26 -11
  49. package/dist/lib/gh-output.js +47 -15
  50. package/dist/lib/history-retention.d.ts +8 -0
  51. package/dist/lib/history-retention.js +24 -0
  52. package/dist/lib/http.d.ts +44 -19
  53. package/dist/lib/http.js +53 -26
  54. package/dist/lib/interrupt.d.ts +21 -13
  55. package/dist/lib/interrupt.js +32 -21
  56. package/dist/lib/junit-report.d.ts +11 -1
  57. package/dist/lib/junit-report.js +15 -3
  58. package/dist/lib/local-target.d.ts +33 -1
  59. package/dist/lib/local-target.js +78 -1
  60. package/dist/lib/output.d.ts +27 -1
  61. package/dist/lib/output.js +22 -3
  62. package/dist/lib/plan-poll.d.ts +11 -11
  63. package/dist/lib/plan-poll.js +12 -12
  64. package/dist/lib/plans.types.d.ts +9 -9
  65. package/dist/lib/plans.types.js +3 -3
  66. package/dist/lib/poll.d.ts +2 -2
  67. package/dist/lib/poll.js +9 -3
  68. package/dist/lib/render-error.d.ts +2 -0
  69. package/dist/lib/render-error.js +13 -0
  70. package/dist/lib/response-schemas.d.ts +54 -12
  71. package/dist/lib/response-schemas.js +106 -7
  72. package/dist/lib/runs.types.d.ts +92 -6
  73. package/dist/lib/secret-file.js +72 -14
  74. package/dist/lib/skill-nudge.d.ts +6 -1
  75. package/dist/lib/skill-nudge.js +32 -5
  76. package/dist/lib/target-url-preflight.d.ts +6 -4
  77. package/dist/lib/target-url-preflight.js +64 -51
  78. package/dist/lib/target-url.js +31 -12
  79. package/dist/lib/telemetry.d.ts +172 -3
  80. package/dist/lib/telemetry.js +276 -15
  81. package/dist/lib/ticker.js +93 -4
  82. package/dist/lib/tunnel-session.d.ts +13 -0
  83. package/dist/lib/tunnel-session.js +4 -1
  84. package/dist/lib/tunnel.types.d.ts +12 -2
  85. package/dist/lib/tunnel.types.js +2 -2
  86. package/dist/lib/version-notice.d.ts +20 -1
  87. package/dist/lib/version-notice.js +59 -12
  88. package/dist/lib/wait-exit.d.ts +8 -0
  89. package/dist/lib/wait-exit.js +76 -4
  90. package/dist/lib/workspace-status.d.ts +23 -0
  91. package/dist/lib/workspace-status.js +15 -0
  92. package/dist/version-guard.d.ts +7 -1
  93. package/dist/version-guard.js +19 -1
  94. package/dist/version.d.ts +1 -1
  95. package/dist/version.js +1 -1
  96. package/package.json +4 -4
  97. package/skills/testsprite-onboard.skill.md +4 -4
  98. package/skills/testsprite-verify.codex.md +59 -57
  99. package/skills/testsprite-verify.skill.md +53 -36
@@ -4,7 +4,8 @@ import { ApiError } from './errors.js';
4
4
  import type { CliTestListRunResponse } from './testlist.types.js';
5
5
  import type { TriggerRunBody, TriggerRunResponse, RunResponse, RerunRequest, RerunResponse, BatchRerunRequest, BatchRerunResponse, BatchRunFreshRequest, BatchRunFreshResponse, ListRunsQuery, ListRunsResponse, CancelRunResponse } from './runs.types.js';
6
6
  import type { CliAcceptPlansResponse, CliGeneratePlansResponse, CliGetPlansResponse } from './plans.types.js';
7
- import type { MintTunnelBody, TunnelMintResponse, TunnelStatusResponse } from './tunnel.types.js';
7
+ import type { MintTunnelBody, TunnelListResponse, TunnelMintResponse, TunnelStatusResponse } from './tunnel.types.js';
8
+ import type { ShutdownHandle } from './interrupt.js';
8
9
  export type FetchImpl = typeof globalThis.fetch;
9
10
  export type DebugEventKind = 'request' | 'response' | 'retry' | 'error';
10
11
  export interface DebugEvent {
@@ -67,6 +68,12 @@ export interface HttpClientOptions {
67
68
  onServerVersion?: (info: {
68
69
  minVersion?: string;
69
70
  }) => void;
71
+ /**
72
+ * Environment the client reads the optional `TESTSPRITE_CLIENT` tag from
73
+ * (see `client-tag.ts`) to build its User-Agent. Defaults to `process.env`;
74
+ * injectable so tests never depend on the developer's shell.
75
+ */
76
+ env?: NodeJS.ProcessEnv;
70
77
  /**
71
78
  * Per-request wall-clock timeout in milliseconds applied to every outgoing
72
79
  * fetch. The signal fires independently of any caller-supplied signal — the
@@ -81,7 +88,7 @@ export interface HttpClientOptions {
81
88
  */
82
89
  requestTimeoutMs?: number;
83
90
  /**
84
- * Process-lifetime shutdown signal (DEV-331 piece 1). Composed into every
91
+ * Process-lifetime shutdown signal. Composed into every
85
92
  * outgoing fetch so an armed SIGINT/SIGTERM aborts an in-flight request
86
93
  * (a `--wait` long-poll can sit inside a single fetch for minutes) instead
87
94
  * of waiting out its window. Aborts with an `InterruptError` reason, which
@@ -90,6 +97,13 @@ export interface HttpClientOptions {
90
97
  * `globalShutdown.signal` via the client factory.
91
98
  */
92
99
  shutdownSignal?: AbortSignal;
100
+ /**
101
+ * Tracks the request through dispatch, body reading, and retries so a
102
+ * disarmed signal can let it drain.
103
+ * Unlike `shutdownSignal`, this does not cancel the request. Omit it for
104
+ * requests that should remain untracked.
105
+ */
106
+ shutdown?: Pick<ShutdownHandle, 'runCriticalOperation'>;
93
107
  /**
94
108
  * Upper bound (bytes) on a successful JSON response body the client will
95
109
  * buffer before parsing. A response whose declared `Content-Length` — or
@@ -177,9 +191,11 @@ export interface RequestOptions<T = unknown> {
177
191
  }
178
192
  /**
179
193
  * 429 reasons that name a STANDING condition rather than a passing throttle —
180
- * e.g. the per-user cap on live tunnel bindings. Retrying cannot succeed until
181
- * the caller frees the resource, so the retry budget is skipped and the
182
- * server's nextAction (e.g. `testsprite tunnel stop`) surfaces immediately.
194
+ * e.g. the per-user cap on live tunnel bindings, or already having the maximum
195
+ * number of runs in flight. Retrying cannot succeed until the caller frees the
196
+ * resource, so the retry budget is skipped and the server's nextAction (e.g.
197
+ * `testsprite tunnel stop`) surfaces immediately. `Retry-After` on these says
198
+ * when a retry COULD first succeed, not that the condition clears on its own.
183
199
  */
184
200
  export declare const STANDING_RATE_LIMIT_REASONS: ReadonlySet<string>;
185
201
  /** True for a RATE_LIMITED error whose envelope names a standing condition. */
@@ -204,12 +220,13 @@ export declare class HttpClient {
204
220
  private readonly onServerVersion?;
205
221
  private readonly requestTimeoutMs;
206
222
  private readonly shutdownSignal?;
223
+ private readonly shutdown?;
207
224
  private readonly maxResponseBytes;
225
+ private readonly userAgent;
208
226
  constructor(options: HttpClientOptions);
209
227
  /** The resolved facade base URL (trailing slash trimmed). Read-only —
210
228
  * callers that bypass the client for a side-channel request (e.g. the
211
- * presigned S3 PUT) use it to reason about the facade's locality
212
- * (DEV-384 review F3). */
229
+ * presigned S3 PUT) use it to reason about the facade's locality. */
213
230
  get resolvedBaseUrl(): string;
214
231
  /**
215
232
  * Read the backend's supported-floor header off a response and forward it to
@@ -227,7 +244,7 @@ export declare class HttpClient {
227
244
  /**
228
245
  * Like `get` / `post` / etc. but returns the full `RequestResult` including
229
246
  * `requestId` and `status`, so callers can surface the requestId in
230
- * happy-path output (dogfood item 1).
247
+ * happy-path output.
231
248
  */
232
249
  getWithMeta<T>(path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
233
250
  postWithMeta<T>(path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
@@ -358,6 +375,13 @@ export declare class HttpClient {
358
375
  mintTunnel(body: MintTunnelBody, options?: {
359
376
  signal?: AbortSignal;
360
377
  }): Promise<TunnelMintResponse>;
378
+ /**
379
+ * GET /api/cli/v1/tunnel — list this account's live bindings.
380
+ * Secret-free, partition-scoped by the server; requires `run:tunnel`.
381
+ */
382
+ listTunnels(options?: {
383
+ signal?: AbortSignal;
384
+ }): Promise<TunnelListResponse>;
361
385
  /**
362
386
  * GET /api/cli/v1/tunnel/{clientId} — is this binding's client connected?
363
387
  *
@@ -365,7 +389,8 @@ export declare class HttpClient {
365
389
  * deliberately not an existence oracle for client ids. Callers must not
366
390
  * translate a transport failure or a non-200 into `offline` — "the tunnel is
367
391
  * down" and "we could not reach TestSprite to ask" are different answers,
368
- * and collapsing them is what DEV-1005 was.
392
+ * and collapsing them would misreport a transient network failure as a
393
+ * dead tunnel.
369
394
  */
370
395
  getTunnelStatus(clientId: string, options?: {
371
396
  signal?: AbortSignal;
@@ -383,8 +408,8 @@ export declare class HttpClient {
383
408
  }): Promise<void>;
384
409
  /**
385
410
  * POST /api/cli/v1/runs/{runId}/cancel
386
- * User-initiated cancel of a queued/running run (DEV-331 piece 3). No
387
- * body, no `Idempotency-Key` — the endpoint is naturally idempotent (D10):
411
+ * User-initiated cancel of a queued/running run. No
412
+ * body, no `Idempotency-Key` — the endpoint is naturally idempotent:
388
413
  * re-cancel → 200 `alreadyCancelled: true`; already-terminal (passed/
389
414
  * failed/blocked) → 409 CONFLICT; unknown/cross-tenant runId → 404.
390
415
  *
@@ -396,7 +421,7 @@ export declare class HttpClient {
396
421
  signal?: AbortSignal;
397
422
  }): Promise<CancelRunResponse>;
398
423
  /**
399
- * POST /api/cli/v1/projects/{projectId}/plans/generate (DEV-384 V3-B)
424
+ * POST /api/cli/v1/projects/{projectId}/plans/generate
400
425
  * Start whichever generation stage the project is missing next. The body
401
426
  * is empty by contract — the server decides which rung fires. 202 both
402
427
  * for `accepted` (a stage started) and `nothing_to_start` (proposals are
@@ -412,7 +437,7 @@ export declare class HttpClient {
412
437
  signal?: AbortSignal;
413
438
  }): Promise<CliGeneratePlansResponse>;
414
439
  /**
415
- * GET /api/cli/v1/projects/{projectId}/plans (DEV-384 V3-B)
440
+ * GET /api/cli/v1/projects/{projectId}/plans
416
441
  * Pure read: the facade-synthesized generation status, the staged
417
442
  * proposal list (stable proposalIds — what `accept --only` consumes),
418
443
  * and a best-effort credits block. When `waitSeconds` (1–25) is
@@ -424,7 +449,7 @@ export declare class HttpClient {
424
449
  signal?: AbortSignal;
425
450
  }): Promise<CliGetPlansResponse>;
426
451
  /**
427
- * POST /api/cli/v1/projects/{projectId}/plans/accept (DEV-384 V3-B)
452
+ * POST /api/cli/v1/projects/{projectId}/plans/accept
428
453
  * Convert staged proposals into real test cases. `only` is ALWAYS an
429
454
  * explicit, non-empty id list — the caller enforces the two §3.3 safety
430
455
  * rules (full list when the user didn't subset; an empty selection is a
@@ -445,13 +470,13 @@ export declare class HttpClient {
445
470
  */
446
471
  private rethrowIfAbort;
447
472
  requestWithMeta<T>(method: string, path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
473
+ private requestWithMetaUntracked;
448
474
  private buildHeaders;
449
475
  /**
450
- * Retry-delay sleep that bails the moment the shutdown signal fires
451
- * (DEV-331, codex finding 1): a RATE_LIMITED `Retry-After: 60` or a
452
- * transport backoff must not delay the honest-detach exit by up to a
453
- * minute — reject with the InterruptError reason immediately. Mirrors
454
- * poll.ts::sleepUnlessInterrupted.
476
+ * Retry-delay sleep that bails the moment the shutdown signal fires: a
477
+ * RATE_LIMITED `Retry-After: 60` or a transport backoff must not delay the
478
+ * honest-detach exit by up to a minute — reject with the InterruptError
479
+ * reason immediately. Mirrors poll.ts::sleepUnlessInterrupted.
455
480
  */
456
481
  private sleepBeforeRetry;
457
482
  private debug;
package/dist/lib/http.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import * as v from 'valibot';
3
3
  import { ApiError, InterruptError, RequestTimeoutError, TransportError } from './errors.js';
4
- import { VERSION } from '../version.js';
5
- import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_RESPONSE_SCHEMA, CANCEL_RUN_RESPONSE_SCHEMA, LIST_RUNS_RESPONSE_SCHEMA, RERUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TESTLIST_RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, TUNNEL_MINT_RESPONSE_SCHEMA, TUNNEL_STATUS_RESPONSE_SCHEMA, } from './response-schemas.js';
4
+ import { buildUserAgent } from './client-tag.js';
5
+ import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_RESPONSE_SCHEMA, CANCEL_RUN_RESPONSE_SCHEMA, LIST_RUNS_RESPONSE_SCHEMA, RERUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TESTLIST_RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, TUNNEL_LIST_RESPONSE_SCHEMA, TUNNEL_MINT_RESPONSE_SCHEMA, TUNNEL_STATUS_RESPONSE_SCHEMA, } from './response-schemas.js';
6
6
  /**
7
7
  * Default per-request timeout (120s). Comfortably covers every metadata/read
8
8
  * request and every <=25s long-poll request (`?waitSeconds` is capped at 25
@@ -41,11 +41,16 @@ const MAX_ATTEMPTS_INTERNAL = 2;
41
41
  const MAX_RATE_LIMITED_DELAY_MS = 60_000;
42
42
  /**
43
43
  * 429 reasons that name a STANDING condition rather than a passing throttle —
44
- * e.g. the per-user cap on live tunnel bindings. Retrying cannot succeed until
45
- * the caller frees the resource, so the retry budget is skipped and the
46
- * server's nextAction (e.g. `testsprite tunnel stop`) surfaces immediately.
44
+ * e.g. the per-user cap on live tunnel bindings, or already having the maximum
45
+ * number of runs in flight. Retrying cannot succeed until the caller frees the
46
+ * resource, so the retry budget is skipped and the server's nextAction (e.g.
47
+ * `testsprite tunnel stop`) surfaces immediately. `Retry-After` on these says
48
+ * when a retry COULD first succeed, not that the condition clears on its own.
47
49
  */
48
- export const STANDING_RATE_LIMIT_REASONS = new Set(['tunnel_binding_limit']);
50
+ export const STANDING_RATE_LIMIT_REASONS = new Set([
51
+ 'tunnel_binding_limit',
52
+ 'inflight_cap',
53
+ ]);
49
54
  /** True for a RATE_LIMITED error whose envelope names a standing condition. */
50
55
  export function isStandingRateLimit(err) {
51
56
  if (err.code !== 'RATE_LIMITED')
@@ -78,11 +83,16 @@ export class HttpClient {
78
83
  onServerVersion;
79
84
  requestTimeoutMs;
80
85
  shutdownSignal;
86
+ shutdown;
81
87
  maxResponseBytes;
88
+ userAgent;
82
89
  constructor(options) {
83
90
  this.baseUrl = trimTrailingSlash(options.baseUrl);
84
91
  this.apiKey = options.apiKey;
85
92
  this.shutdownSignal = options.shutdownSignal;
93
+ this.shutdown = options.shutdown;
94
+ // Resolved once: the tag is process-wide configuration, not per-request.
95
+ this.userAgent = buildUserAgent(options.env ?? process.env);
86
96
  this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
87
97
  this.sleep = options.sleep ?? defaultSleep;
88
98
  this.random = options.random ?? Math.random;
@@ -94,8 +104,7 @@ export class HttpClient {
94
104
  }
95
105
  /** The resolved facade base URL (trailing slash trimmed). Read-only —
96
106
  * callers that bypass the client for a side-channel request (e.g. the
97
- * presigned S3 PUT) use it to reason about the facade's locality
98
- * (DEV-384 review F3). */
107
+ * presigned S3 PUT) use it to reason about the facade's locality. */
99
108
  get resolvedBaseUrl() {
100
109
  return this.baseUrl;
101
110
  }
@@ -137,7 +146,7 @@ export class HttpClient {
137
146
  /**
138
147
  * Like `get` / `post` / etc. but returns the full `RequestResult` including
139
148
  * `requestId` and `status`, so callers can surface the requestId in
140
- * happy-path output (dogfood item 1).
149
+ * happy-path output.
141
150
  */
142
151
  async getWithMeta(path, options = {}) {
143
152
  return this.requestWithMeta('GET', path, options);
@@ -283,6 +292,8 @@ export class HttpClient {
283
292
  q.source = query.source;
284
293
  if (query.since !== undefined)
285
294
  q.since = query.since;
295
+ if (query.environment !== undefined)
296
+ q.environment = query.environment;
286
297
  return this.get(`/tests/${encodeURIComponent(testId)}/runs`, {
287
298
  query: q,
288
299
  signal: options.signal,
@@ -338,6 +349,16 @@ export class HttpClient {
338
349
  retryOnConflict: false,
339
350
  }).then(r => r.body);
340
351
  }
352
+ /**
353
+ * GET /api/cli/v1/tunnel — list this account's live bindings.
354
+ * Secret-free, partition-scoped by the server; requires `run:tunnel`.
355
+ */
356
+ async listTunnels(options = {}) {
357
+ return this.get('/tunnel', {
358
+ signal: options.signal,
359
+ schema: TUNNEL_LIST_RESPONSE_SCHEMA,
360
+ });
361
+ }
341
362
  /**
342
363
  * GET /api/cli/v1/tunnel/{clientId} — is this binding's client connected?
343
364
  *
@@ -345,7 +366,8 @@ export class HttpClient {
345
366
  * deliberately not an existence oracle for client ids. Callers must not
346
367
  * translate a transport failure or a non-200 into `offline` — "the tunnel is
347
368
  * down" and "we could not reach TestSprite to ask" are different answers,
348
- * and collapsing them is what DEV-1005 was.
369
+ * and collapsing them would misreport a transient network failure as a
370
+ * dead tunnel.
349
371
  */
350
372
  async getTunnelStatus(clientId, options = {}) {
351
373
  return this.get(`/tunnel/${encodeURIComponent(clientId)}`, {
@@ -370,8 +392,8 @@ export class HttpClient {
370
392
  }
371
393
  /**
372
394
  * POST /api/cli/v1/runs/{runId}/cancel
373
- * User-initiated cancel of a queued/running run (DEV-331 piece 3). No
374
- * body, no `Idempotency-Key` — the endpoint is naturally idempotent (D10):
395
+ * User-initiated cancel of a queued/running run. No
396
+ * body, no `Idempotency-Key` — the endpoint is naturally idempotent:
375
397
  * re-cancel → 200 `alreadyCancelled: true`; already-terminal (passed/
376
398
  * failed/blocked) → 409 CONFLICT; unknown/cross-tenant runId → 404.
377
399
  *
@@ -387,7 +409,7 @@ export class HttpClient {
387
409
  });
388
410
  }
389
411
  /**
390
- * POST /api/cli/v1/projects/{projectId}/plans/generate (DEV-384 V3-B)
412
+ * POST /api/cli/v1/projects/{projectId}/plans/generate
391
413
  * Start whichever generation stage the project is missing next. The body
392
414
  * is empty by contract — the server decides which rung fires. 202 both
393
415
  * for `accepted` (a stage started) and `nothing_to_start` (proposals are
@@ -407,7 +429,7 @@ export class HttpClient {
407
429
  });
408
430
  }
409
431
  /**
410
- * GET /api/cli/v1/projects/{projectId}/plans (DEV-384 V3-B)
432
+ * GET /api/cli/v1/projects/{projectId}/plans
411
433
  * Pure read: the facade-synthesized generation status, the staged
412
434
  * proposal list (stable proposalIds — what `accept --only` consumes),
413
435
  * and a best-effort credits block. When `waitSeconds` (1–25) is
@@ -421,7 +443,7 @@ export class HttpClient {
421
443
  });
422
444
  }
423
445
  /**
424
- * POST /api/cli/v1/projects/{projectId}/plans/accept (DEV-384 V3-B)
446
+ * POST /api/cli/v1/projects/{projectId}/plans/accept
425
447
  * Convert staged proposals into real test cases. `only` is ALWAYS an
426
448
  * explicit, non-empty id list — the caller enforces the two §3.3 safety
427
449
  * rules (full list when the user didn't subset; an empty selection is a
@@ -445,7 +467,7 @@ export class HttpClient {
445
467
  * continue its own error handling (transport retry / envelope parse).
446
468
  */
447
469
  rethrowIfAbort(err, timeoutSignal, callerSignal, requestId, effectiveSignal = timeoutSignal) {
448
- // A user interrupt (DEV-331) outranks every other classification: once the
470
+ // A user interrupt outranks every other classification: once the
449
471
  // shutdown signal fired, whatever error surfaced from the aborted fetch or
450
472
  // body read is the interrupt. Throw its InterruptError reason so the wait
451
473
  // paths can render the honest detach UX — never a RequestTimeoutError, and
@@ -467,6 +489,10 @@ export class HttpClient {
467
489
  async requestWithMeta(method, path, options = {}) {
468
490
  if (!this.apiKey)
469
491
  throw ApiError.authRequired();
492
+ const operation = () => this.requestWithMetaUntracked(method, path, options);
493
+ return this.shutdown ? this.shutdown.runCriticalOperation(operation) : operation();
494
+ }
495
+ async requestWithMetaUntracked(method, path, options = {}) {
470
496
  const url = buildUrl(this.baseUrl, path, options.query);
471
497
  const requestId = options.requestId ?? newRequestId();
472
498
  const allowRetry = options.retry !== false;
@@ -494,7 +520,7 @@ export class HttpClient {
494
520
  const composedSignals = [timeoutSignal];
495
521
  if (options.signal != null)
496
522
  composedSignals.push(options.signal);
497
- // Shutdown composition (DEV-331): an armed SIGINT/SIGTERM aborts the
523
+ // Shutdown composition: an armed SIGINT/SIGTERM aborts the
498
524
  // in-flight fetch immediately (reason: InterruptError) instead of
499
525
  // letting a long-poll drain its window before the interrupt surfaces.
500
526
  if (this.shutdownSignal != null)
@@ -532,7 +558,7 @@ export class HttpClient {
532
558
  // The instanceof check matters even without `this.shutdownSignal`:
533
559
  // the polling path composes the shutdown signal into its per-
534
560
  // iteration caller signal, so the fetch can reject with the
535
- // InterruptError reason directly (DEV-331).
561
+ // InterruptError reason directly.
536
562
  if (err instanceof InterruptError)
537
563
  throw err;
538
564
  // A timeout/abort during the fetch itself: classify it (RequestTimeoutError
@@ -761,7 +787,7 @@ export class HttpClient {
761
787
  const headers = {
762
788
  'x-request-id': requestId,
763
789
  accept: 'application/json',
764
- 'user-agent': `testsprite-cli/${VERSION}`,
790
+ 'user-agent': this.userAgent,
765
791
  };
766
792
  // The CLI v1 facade authenticates via `x-api-key`.
767
793
  // (securitySchemes.ApiKeyAuth). Sending only Authorization Bearer would be
@@ -780,11 +806,10 @@ export class HttpClient {
780
806
  return headers;
781
807
  }
782
808
  /**
783
- * Retry-delay sleep that bails the moment the shutdown signal fires
784
- * (DEV-331, codex finding 1): a RATE_LIMITED `Retry-After: 60` or a
785
- * transport backoff must not delay the honest-detach exit by up to a
786
- * minute — reject with the InterruptError reason immediately. Mirrors
787
- * poll.ts::sleepUnlessInterrupted.
809
+ * Retry-delay sleep that bails the moment the shutdown signal fires: a
810
+ * RATE_LIMITED `Retry-After: 60` or a transport backoff must not delay the
811
+ * honest-detach exit by up to a minute — reject with the InterruptError
812
+ * reason immediately. Mirrors poll.ts::sleepUnlessInterrupted.
788
813
  */
789
814
  sleepBeforeRetry(ms) {
790
815
  const signal = this.shutdownSignal;
@@ -936,8 +961,10 @@ async function safeReadJson(response) {
936
961
  return await response.json();
937
962
  }
938
963
  catch (err) {
939
- // Don't swallow client-side aborts/timeouts as a null body — the caller must
940
- // be able to classify a mid-body-read timeout as a RequestTimeoutError.
964
+ // Don't swallow interrupts, aborts, or timeouts as a null body — the caller
965
+ // must preserve the interruption or classify a timeout correctly.
966
+ if (err instanceof InterruptError)
967
+ throw err;
941
968
  if (isAbortError(err) || isTimeoutError(err))
942
969
  throw err;
943
970
  return null;
@@ -24,6 +24,11 @@ import { type TerminationSignal } from './errors.js';
24
24
  export { TERMINATION_EXIT_CODES, type TerminationSignal } from './errors.js';
25
25
  /** Back-compat alias: SIGINT's conventional exit code. */
26
26
  export declare const SIGINT_EXIT_CODE: 130;
27
+ export declare const INTERRUPT_EXIT_BACKSTOP_MS = 3000;
28
+ export declare function armInterruptExitBackstop(code: number, deps?: {
29
+ setTimer?: (callback: () => void, delayMs: number) => Pick<NodeJS.Timeout, 'unref'>;
30
+ exit?: (code: number) => void;
31
+ }): void;
27
32
  /**
28
33
  * Structural view of {@link ShutdownController} threaded through the DI
29
34
  * surfaces (`TestDeps`, `PollOptions`) — commands and the polling loop need
@@ -34,12 +39,12 @@ export interface ShutdownHandle {
34
39
  readonly signal: AbortSignal;
35
40
  /** Enter a graceful-detach scope. Returns the disposer that leaves it. */
36
41
  arm(): () => void;
37
- /** Run and track cleanup that a repeated signal may briefly wait for. */
42
+ /** Run and track work that a repeated signal may briefly wait for. */
38
43
  runCriticalOperation<T>(operation: () => Promise<T>): Promise<T>;
39
44
  }
40
45
  /**
41
46
  * Process-lifetime coordinator between the signal handler and the `--wait`
42
- * polling paths (DEV-331 piece 1).
47
+ * polling paths.
43
48
  *
44
49
  * Two modes, chosen by whether a graceful-detach scope is armed when the
45
50
  * signal arrives:
@@ -50,12 +55,12 @@ export interface ShutdownHandle {
50
55
  * the cleanup (finalize the ticker, print the honest partial envelope +
51
56
  * re-attach hint, rethrow to `index.ts` → exit 130/143/129).
52
57
  * - **Disarmed** (no wait in progress — prompts, one-shot commands, local
53
- * FS work): the handler prints the generic explanation and exits
54
- * immediately, preserving the pre-DEV-331 behavior. An abort nobody
55
- * observes must never leave the process hanging at e.g. a readline prompt.
58
+ * FS work): the handler prints the generic explanation. An in-flight HTTP
59
+ * request can unwind through the top-level catch; idle work such as a
60
+ * readline prompt exits immediately because it cannot observe the abort.
56
61
  *
57
62
  * A repeated signal still provides a bounded escape hatch: the second waits
58
- * briefly only when critical cleanup is in flight, and the third exits at once.
63
+ * briefly when cleanup or an HTTP request is in flight, and the third exits at once.
59
64
  */
60
65
  export declare class ShutdownController {
61
66
  private readonly controller;
@@ -72,14 +77,14 @@ export declare class ShutdownController {
72
77
  * Returns an idempotent disposer.
73
78
  */
74
79
  arm(): () => void;
75
- /** Whether teardown currently has work whose abrupt loss is security-sensitive. */
80
+ /** Whether cleanup or an HTTP request is in flight and needs time to settle. */
76
81
  get hasCriticalOperations(): boolean;
77
82
  /**
78
- * Register cleanup before it starts and remove it automatically when it
83
+ * Register an operation before it starts and remove it automatically when it
79
84
  * settles. Rejections retain their original semantics for the caller.
80
85
  */
81
86
  runCriticalOperation<T>(operation: () => Promise<T>): Promise<T>;
82
- /** Wait until all current and directly chained critical cleanup settles. */
87
+ /** Wait until all current and directly chained tracked work settles. */
83
88
  waitForCriticalOperations(): Promise<void>;
84
89
  /** Record the signal and abort with an `InterruptError` carrying it. */
85
90
  interrupt(signal: TerminationSignal): void;
@@ -106,6 +111,8 @@ export interface InterruptDeps {
106
111
  stderr?: (line: string) => void;
107
112
  /** Process exit. Defaults to `process.exit`. */
108
113
  exit?: (code: number) => void;
114
+ /** Set the exit code while allowing in-flight work to drain. */
115
+ setExitCode?: (code: number) => void;
109
116
  /** Shutdown coordinator. Defaults to {@link globalShutdown}. */
110
117
  shutdown?: ShutdownController;
111
118
  }
@@ -114,10 +121,11 @@ export interface InterruptDeps {
114
121
  * single top-level call in `index.ts`; not designed to be installed twice.
115
122
  *
116
123
  * First signal, armed scope: abort-only — the `--wait` catch paths own the
117
- * honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
118
- * First signal, disarmed: print the generic explanation + exit `128+signum`.
119
- * Second signal: exit immediately unless critical cleanup is registered; when
120
- * it is, wait at most two seconds before exiting. Third signal: always exit
124
+ * honest-detach UX and the exit (Ctrl-C detaches; it never cancels the run).
125
+ * First signal, disarmed: print the generic explanation, then drain an in-flight
126
+ * request or exit `128+signum` immediately when idle.
127
+ * Second signal: exit immediately unless cleanup or a request is registered;
128
+ * when it is, wait at most two seconds before exiting. Third signal: always exit
121
129
  * immediately, including while that grace period is active.
122
130
  */
123
131
  export declare function installSignalHandlers(deps?: InterruptDeps): void;
@@ -26,9 +26,14 @@ import { InterruptError, TERMINATION_EXIT_CODES } from './errors.js';
26
26
  export { TERMINATION_EXIT_CODES } from './errors.js';
27
27
  /** Back-compat alias: SIGINT's conventional exit code. */
28
28
  export const SIGINT_EXIT_CODE = TERMINATION_EXIT_CODES.SIGINT;
29
+ export const INTERRUPT_EXIT_BACKSTOP_MS = 3_000;
30
+ export function armInterruptExitBackstop(code, deps = {}) {
31
+ const timer = (deps.setTimer ?? setTimeout)(() => (deps.exit ?? process.exit)(code), INTERRUPT_EXIT_BACKSTOP_MS);
32
+ timer.unref();
33
+ }
29
34
  /**
30
35
  * Process-lifetime coordinator between the signal handler and the `--wait`
31
- * polling paths (DEV-331 piece 1).
36
+ * polling paths.
32
37
  *
33
38
  * Two modes, chosen by whether a graceful-detach scope is armed when the
34
39
  * signal arrives:
@@ -39,12 +44,12 @@ export const SIGINT_EXIT_CODE = TERMINATION_EXIT_CODES.SIGINT;
39
44
  * the cleanup (finalize the ticker, print the honest partial envelope +
40
45
  * re-attach hint, rethrow to `index.ts` → exit 130/143/129).
41
46
  * - **Disarmed** (no wait in progress — prompts, one-shot commands, local
42
- * FS work): the handler prints the generic explanation and exits
43
- * immediately, preserving the pre-DEV-331 behavior. An abort nobody
44
- * observes must never leave the process hanging at e.g. a readline prompt.
47
+ * FS work): the handler prints the generic explanation. An in-flight HTTP
48
+ * request can unwind through the top-level catch; idle work such as a
49
+ * readline prompt exits immediately because it cannot observe the abort.
45
50
  *
46
51
  * A repeated signal still provides a bounded escape hatch: the second waits
47
- * briefly only when critical cleanup is in flight, and the third exits at once.
52
+ * briefly when cleanup or an HTTP request is in flight, and the third exits at once.
48
53
  */
49
54
  export class ShutdownController {
50
55
  controller = new AbortController();
@@ -81,12 +86,12 @@ export class ShutdownController {
81
86
  this.armedCount -= 1;
82
87
  };
83
88
  }
84
- /** Whether teardown currently has work whose abrupt loss is security-sensitive. */
89
+ /** Whether cleanup or an HTTP request is in flight and needs time to settle. */
85
90
  get hasCriticalOperations() {
86
91
  return this.criticalOperations.size > 0;
87
92
  }
88
93
  /**
89
- * Register cleanup before it starts and remove it automatically when it
94
+ * Register an operation before it starts and remove it automatically when it
90
95
  * settles. Rejections retain their original semantics for the caller.
91
96
  */
92
97
  runCriticalOperation(operation) {
@@ -97,7 +102,7 @@ export class ShutdownController {
97
102
  this.criticalOperations.add(tracked);
98
103
  return tracked;
99
104
  }
100
- /** Wait until all current and directly chained critical cleanup settles. */
105
+ /** Wait until all current and directly chained tracked work settles. */
101
106
  async waitForCriticalOperations() {
102
107
  while (this.criticalOperations.size > 0) {
103
108
  await Promise.allSettled([...this.criticalOperations]);
@@ -144,7 +149,7 @@ export function formatInterruptMessage(signal = 'SIGINT') {
144
149
  'check it with `testsprite test list` or `testsprite test wait <runId>`.');
145
150
  }
146
151
  const CRITICAL_OPERATION_GRACE_MS = 2_000;
147
- /** How often the grace period re-checks whether teardown is still running. */
152
+ /** How often the grace period re-checks whether tracked work is still running. */
148
153
  const CRITICAL_OPERATION_POLL_MS = 10;
149
154
  function afterDelay(ms) {
150
155
  return new Promise(resolve => {
@@ -180,10 +185,11 @@ async function waitForCriticalOperationsWithGrace(shutdown) {
180
185
  * single top-level call in `index.ts`; not designed to be installed twice.
181
186
  *
182
187
  * First signal, armed scope: abort-only — the `--wait` catch paths own the
183
- * honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
184
- * First signal, disarmed: print the generic explanation + exit `128+signum`.
185
- * Second signal: exit immediately unless critical cleanup is registered; when
186
- * it is, wait at most two seconds before exiting. Third signal: always exit
188
+ * honest-detach UX and the exit (Ctrl-C detaches; it never cancels the run).
189
+ * First signal, disarmed: print the generic explanation, then drain an in-flight
190
+ * request or exit `128+signum` immediately when idle.
191
+ * Second signal: exit immediately unless cleanup or a request is registered;
192
+ * when it is, wait at most two seconds before exiting. Third signal: always exit
187
193
  * immediately, including while that grace period is active.
188
194
  */
189
195
  export function installSignalHandlers(deps = {}) {
@@ -193,9 +199,8 @@ export function installSignalHandlers(deps = {}) {
193
199
  });
194
200
  const stderr = deps.stderr ??
195
201
  ((line) => {
196
- // A signal handler calls process.exit() right after writing, which can
197
- // truncate an async process.stderr.write() when stderr is a pipe. Write
198
- // synchronously so the interrupt hint is flushed before the process exits.
202
+ // An idle or repeated signal can call process.exit() right after writing,
203
+ // truncating an async stderr write when stderr is a pipe.
199
204
  try {
200
205
  writeSync(process.stderr.fd, `${line}\n`);
201
206
  }
@@ -204,6 +209,10 @@ export function installSignalHandlers(deps = {}) {
204
209
  }
205
210
  });
206
211
  const exit = deps.exit ?? ((code) => process.exit(code));
212
+ const setExitCode = deps.setExitCode ??
213
+ ((code) => {
214
+ process.exitCode = code;
215
+ });
207
216
  const shutdown = deps.shutdown ?? globalShutdown;
208
217
  let signalCount = 0;
209
218
  let graceGeneration = 0;
@@ -222,8 +231,8 @@ export function installSignalHandlers(deps = {}) {
222
231
  // credential delete is registered only after the poll loop unwinds. A
223
232
  // second signal that arrives in between — which is what a reflexive
224
233
  // double Ctrl-C actually does — would otherwise hard-exit and strand a
225
- // live inbound credential until its TTL, the exact outcome the grace
226
- // period exists to prevent.
234
+ // live inbound credential until its TTL. An ordinary in-flight request
235
+ // is registered too, so it gets the same bounded grace period.
227
236
  if (!shutdown.hasCriticalOperations && !shutdown.isArmed) {
228
237
  exit(TERMINATION_EXIT_CODES[signal]);
229
238
  return;
@@ -245,14 +254,16 @@ export function installSignalHandlers(deps = {}) {
245
254
  shutdown.interrupt(signal);
246
255
  return;
247
256
  }
248
- // Disarmed (no --wait in progress): legacy immediate exit. Record the
249
- // signal first so a second one takes the hard-exit branch even when
250
- // `exit` is injected and does not terminate (unit tests).
257
+ // Record the signal first so a second one takes the escalation path.
251
258
  shutdown.interrupt(signal);
252
259
  // Blank line first so the message starts on its own row rather than
253
260
  // trailing the progress ticker's in-place line.
254
261
  stderr('');
255
262
  stderr(formatInterruptMessage(signal));
263
+ if (shutdown.hasCriticalOperations) {
264
+ setExitCode(TERMINATION_EXIT_CODES[signal]);
265
+ return;
266
+ }
256
267
  exit(TERMINATION_EXIT_CODES[signal]);
257
268
  });
258
269
  }
@@ -1,3 +1,4 @@
1
+ import { type CiSummary } from './gh-output.js';
1
2
  export type JUnitReportFormat = 'junit';
2
3
  /** Minimal testcase input shared by batch run and batch rerun poll results. */
3
4
  export interface JUnitTestResult {
@@ -11,6 +12,8 @@ export interface JUnitTestResult {
11
12
  message: string;
12
13
  exitCode?: number;
13
14
  };
15
+ /** Why a member was skipped before dispatch. */
16
+ skipReason?: string;
14
17
  /**
15
18
  * Human-readable test name for the `testcase name` attribute. Falls back to
16
19
  * `testId` when absent (older data / a run whose name could not be resolved).
@@ -65,11 +68,18 @@ export declare function resolveBatchReportProjectId(opts: {
65
68
  */
66
69
  export declare function escapeXml(text: string): string;
67
70
  /**
68
- * Build a JUnit XML document from batch poll results. Per-`testcase` `time` is
71
+ * Build a JUnit XML document from batch results, including skipped members. Per-`testcase` `time` is
69
72
  * the run's wall-clock duration (from `startedAt`/`finishedAt`); the `testsuite`
70
73
  * `time` is their sum. `time` falls back to `0` for a run with no timing.
71
74
  */
72
75
  export declare function buildJUnitReport(opts: JUnitReportBuildOptions): string;
76
+ /**
77
+ * The summary's non-dispatched rows (deferred / conflict / not-found) as
78
+ * skipped JUnit results. Accepted rows carry run statuses and never match
79
+ * `isNonDispatchedStatus`, so the filter alone separates the two without
80
+ * relying on row order.
81
+ */
82
+ export declare function skippedJUnitResultsFromSummary(summary: CiSummary): JUnitTestResult[];
73
83
  /**
74
84
  * Atomically write JUnit XML to `--report-file` (temp sibling + rename).
75
85
  */