@testsprite/testsprite-cli 0.6.0 → 0.8.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 (96) hide show
  1. package/README.md +52 -31
  2. package/dist/commands/agent.js +91 -45
  3. package/dist/commands/ci.d.ts +88 -0
  4. package/dist/commands/ci.js +429 -0
  5. package/dist/commands/doctor.d.ts +1 -1
  6. package/dist/commands/doctor.js +104 -8
  7. package/dist/commands/init.js +8 -0
  8. package/dist/commands/project.d.ts +78 -0
  9. package/dist/commands/project.js +429 -5
  10. package/dist/commands/schedule.d.ts +120 -0
  11. package/dist/commands/schedule.js +487 -0
  12. package/dist/commands/test.d.ts +176 -2
  13. package/dist/commands/test.js +2235 -609
  14. package/dist/commands/testlist.d.ts +88 -0
  15. package/dist/commands/testlist.js +753 -0
  16. package/dist/commands/tunnel.d.ts +72 -0
  17. package/dist/commands/tunnel.js +367 -0
  18. package/dist/index.js +113 -40
  19. package/dist/lib/agent-targets.d.ts +13 -4
  20. package/dist/lib/agent-targets.js +11 -2
  21. package/dist/lib/conflict-reason.d.ts +30 -0
  22. package/dist/lib/conflict-reason.js +45 -0
  23. package/dist/lib/credentials.js +42 -1
  24. package/dist/lib/cron.d.ts +40 -0
  25. package/dist/lib/cron.js +190 -0
  26. package/dist/lib/dry-run/samples.d.ts +9 -0
  27. package/dist/lib/dry-run/samples.js +293 -55
  28. package/dist/lib/errors.d.ts +9 -0
  29. package/dist/lib/errors.js +11 -0
  30. package/dist/lib/gh-output.d.ts +33 -1
  31. package/dist/lib/gh-output.js +97 -27
  32. package/dist/lib/http.d.ts +119 -0
  33. package/dist/lib/http.js +243 -2
  34. package/dist/lib/interrupt.d.ts +38 -13
  35. package/dist/lib/interrupt.js +130 -15
  36. package/dist/lib/junit-report.d.ts +20 -2
  37. package/dist/lib/junit-report.js +38 -5
  38. package/dist/lib/local-target.d.ts +95 -0
  39. package/dist/lib/local-target.js +184 -0
  40. package/dist/lib/plan-poll.d.ts +171 -0
  41. package/dist/lib/plan-poll.js +442 -0
  42. package/dist/lib/plans.types.d.ts +130 -0
  43. package/dist/lib/plans.types.js +31 -0
  44. package/dist/lib/poll-support.d.ts +26 -0
  45. package/dist/lib/poll-support.js +65 -0
  46. package/dist/lib/poll.d.ts +1 -0
  47. package/dist/lib/poll.js +2 -40
  48. package/dist/lib/proxy.d.ts +16 -0
  49. package/dist/lib/proxy.js +19 -1
  50. package/dist/lib/response-schemas.d.ts +20 -0
  51. package/dist/lib/response-schemas.js +55 -1
  52. package/dist/lib/run-progress.d.ts +41 -0
  53. package/dist/lib/run-progress.js +56 -0
  54. package/dist/lib/runs.types.d.ts +32 -3
  55. package/dist/lib/secret-file.d.ts +15 -0
  56. package/dist/lib/secret-file.js +82 -0
  57. package/dist/lib/target-url-preflight.d.ts +91 -0
  58. package/dist/lib/target-url-preflight.js +259 -0
  59. package/dist/lib/target-url.d.ts +63 -9
  60. package/dist/lib/target-url.js +283 -62
  61. package/dist/lib/telemetry.d.ts +11 -0
  62. package/dist/lib/telemetry.js +1 -0
  63. package/dist/lib/testlist.types.d.ts +77 -0
  64. package/dist/lib/testlist.types.js +9 -0
  65. package/dist/lib/ticker.d.ts +8 -0
  66. package/dist/lib/ticker.js +3 -0
  67. package/dist/lib/tunnel-session.d.ts +129 -0
  68. package/dist/lib/tunnel-session.js +232 -0
  69. package/dist/lib/tunnel.types.d.ts +54 -0
  70. package/dist/lib/tunnel.types.js +8 -0
  71. package/dist/lib/v3-advisory.d.ts +35 -22
  72. package/dist/lib/v3-advisory.js +44 -24
  73. package/dist/lib/wait-exit.d.ts +29 -0
  74. package/dist/lib/wait-exit.js +103 -0
  75. package/dist/vendor/tunnel-client/client.d.ts +83 -0
  76. package/dist/vendor/tunnel-client/client.js +871 -0
  77. package/dist/vendor/tunnel-client/config.d.ts +41 -0
  78. package/dist/vendor/tunnel-client/config.js +42 -0
  79. package/dist/vendor/tunnel-client/index.d.ts +9 -0
  80. package/dist/vendor/tunnel-client/index.js +9 -0
  81. package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
  82. package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
  83. package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
  84. package/dist/vendor/tunnel-client/protocol.js +143 -0
  85. package/dist/vendor/tunnel-client/types.d.ts +96 -0
  86. package/dist/vendor/tunnel-client/types.js +10 -0
  87. package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
  88. package/dist/vendor/tunnel-client/ws-compat.js +316 -0
  89. package/dist/version-guard.d.ts +10 -7
  90. package/dist/version-guard.js +37 -9
  91. package/dist/version.d.ts +1 -1
  92. package/dist/version.js +1 -1
  93. package/package.json +2 -1
  94. package/skills/testsprite-onboard.skill.md +60 -4
  95. package/skills/testsprite-verify.codex.md +22 -16
  96. package/skills/testsprite-verify.skill.md +27 -18
package/dist/lib/http.js CHANGED
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
2
2
  import * as v from 'valibot';
3
3
  import { ApiError, InterruptError, RequestTimeoutError, TransportError } from './errors.js';
4
4
  import { VERSION } from '../version.js';
5
- import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_RESPONSE_SCHEMA, LIST_RUNS_RESPONSE_SCHEMA, RERUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, } from './response-schemas.js';
5
+ import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_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';
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,6 +41,14 @@ const MAX_ATTEMPTS_INTERNAL = 2;
41
41
  const MAX_RATE_LIMITED_DELAY_MS = 60_000;
42
42
  const CONFLICT_DELAY_MS = 1000;
43
43
  const INTERNAL_DELAY_MS = 500;
44
+ // Upper bound on the size of a successful JSON response body the client will
45
+ // buffer into memory. `response.json()` reads the ENTIRE body before parsing,
46
+ // with no limit, so a large `test result --history` page or a run with a long
47
+ // `steps[]` array (getRun `includeSteps`) would grow the heap in proportion to
48
+ // the payload. 64 MiB sits far above any legitimate metadata/history/steps
49
+ // response yet still bounds a pathological — or hostile — one. Override per
50
+ // client via `HttpClientOptions.maxResponseBytes`.
51
+ const MAX_RESPONSE_BYTES_DEFAULT = 64 * 1024 * 1024;
44
52
  // Cap on how many valibot issues a shape-mismatch INTERNAL envelope carries in
45
53
  // `details.issues` (path + message each). Keeps the envelope readable and
46
54
  // guarantees the response body itself is never echoed back to the operator.
@@ -56,6 +64,7 @@ export class HttpClient {
56
64
  onServerVersion;
57
65
  requestTimeoutMs;
58
66
  shutdownSignal;
67
+ maxResponseBytes;
59
68
  constructor(options) {
60
69
  this.baseUrl = trimTrailingSlash(options.baseUrl);
61
70
  this.apiKey = options.apiKey;
@@ -67,6 +76,14 @@ export class HttpClient {
67
76
  this.onTransition = options.onTransition;
68
77
  this.onServerVersion = options.onServerVersion;
69
78
  this.requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_DEFAULT_MS;
79
+ this.maxResponseBytes = options.maxResponseBytes ?? MAX_RESPONSE_BYTES_DEFAULT;
80
+ }
81
+ /** The resolved facade base URL (trailing slash trimmed). Read-only —
82
+ * callers that bypass the client for a side-channel request (e.g. the
83
+ * presigned S3 PUT) use it to reason about the facade's locality
84
+ * (DEV-384 review F3). */
85
+ get resolvedBaseUrl() {
86
+ return this.baseUrl;
70
87
  }
71
88
  /**
72
89
  * Read the backend's supported-floor header off a response and forward it to
@@ -216,6 +233,24 @@ export class HttpClient {
216
233
  retryOnConflict: false,
217
234
  }).then(r => r.body);
218
235
  }
236
+ /**
237
+ * POST /api/cli/v1/testlist/{listId}/run
238
+ * Dispatch a test list's cases (optionally a `testIds` subset) per project
239
+ * with their configured environments; returns pollable runIds. `--wait` polls
240
+ * each `accepted[].runId`.
241
+ *
242
+ * `retryOnConflict: false` — a 409 here (every dispatched project is an
243
+ * MCP-mirrored view-only mirror) is a permanent condition, not a transient one.
244
+ */
245
+ async triggerTestListRun(listId, body, options) {
246
+ return this.postWithMeta(`/testlist/${encodeURIComponent(listId)}/run`, {
247
+ body,
248
+ headers: { 'idempotency-key': options.idempotencyKey },
249
+ signal: options.signal,
250
+ schema: TESTLIST_RUN_RESPONSE_SCHEMA,
251
+ retryOnConflict: false,
252
+ }).then(r => r.body);
253
+ }
219
254
  /**
220
255
  * GET /api/cli/v1/tests/{testId}/runs
221
256
  * List a test's prior run history, newest-first.
@@ -266,6 +301,56 @@ export class HttpClient {
266
301
  schema: RUN_RESPONSE_SCHEMA,
267
302
  });
268
303
  }
304
+ /**
305
+ * POST /api/cli/v1/tunnel — mint a tunnel client for `test run --local`.
306
+ *
307
+ * The ONLY response on this surface that carries a secret. Deliberately NOT
308
+ * sent with an `Idempotency-Key`: the interceptor persists the response body
309
+ * for the whole replay window, so an idempotent mint would put a live
310
+ * credential in the idempotency store — the exact copy the server-side
311
+ * binding exists to avoid. The server rate-limits this route instead.
312
+ *
313
+ * `retryOnConflict: false` for the same reason `triggerRun` opts out: a 409
314
+ * here means the per-principal live-binding cap is reached, which is a
315
+ * standing condition, not a transient snapshot conflict.
316
+ */
317
+ async mintTunnel(body, options = {}) {
318
+ return this.postWithMeta('/tunnel', {
319
+ body,
320
+ signal: options.signal,
321
+ schema: TUNNEL_MINT_RESPONSE_SCHEMA,
322
+ retryOnConflict: false,
323
+ }).then(r => r.body);
324
+ }
325
+ /**
326
+ * GET /api/cli/v1/tunnel/{clientId} — is this binding's client connected?
327
+ *
328
+ * A 404 covers unknown, another tenant's, and expired alike; the surface is
329
+ * deliberately not an existence oracle for client ids. Callers must not
330
+ * translate a transport failure or a non-200 into `offline` — "the tunnel is
331
+ * down" and "we could not reach TestSprite to ask" are different answers,
332
+ * and collapsing them is what DEV-1005 was.
333
+ */
334
+ async getTunnelStatus(clientId, options = {}) {
335
+ return this.get(`/tunnel/${encodeURIComponent(clientId)}`, {
336
+ signal: options.signal,
337
+ schema: TUNNEL_STATUS_RESPONSE_SCHEMA,
338
+ });
339
+ }
340
+ /**
341
+ * DELETE /api/cli/v1/tunnel/{clientId} — destroy a binding. 204, idempotent.
342
+ *
343
+ * No body, no `Idempotency-Key`: the operation is idempotent by definition
344
+ * and this is the call made from a `finally` block, including after a
345
+ * signal, where there is least room for extra ceremony.
346
+ */
347
+ async deleteTunnel(clientId, options = {}) {
348
+ await this.deleteWithMeta(`/tunnel/${encodeURIComponent(clientId)}`, {
349
+ signal: options.signal,
350
+ allowNoContent: true,
351
+ retryOnConflict: false,
352
+ });
353
+ }
269
354
  /**
270
355
  * POST /api/cli/v1/runs/{runId}/cancel
271
356
  * User-initiated cancel of a queued/running run (DEV-331 piece 3). No
@@ -283,6 +368,56 @@ export class HttpClient {
283
368
  retryOnConflict: false,
284
369
  });
285
370
  }
371
+ /**
372
+ * POST /api/cli/v1/projects/{projectId}/plans/generate (DEV-384 V3-B)
373
+ * Start whichever generation stage the project is missing next. The body
374
+ * is empty by contract — the server decides which rung fires. 202 both
375
+ * for `accepted` (a stage started) and `nothing_to_start` (proposals are
376
+ * already staged; the facade's no-restart guard refuses a duplicate
377
+ * append because it would wipe the batch and re-bill 2 credits).
378
+ *
379
+ * `retryOnConflict: false` — a 409 here is `stage_in_flight`, a flow
380
+ * signal the ladder answers by attaching and polling, never a transient
381
+ * snapshot conflict to paper over with a retry.
382
+ */
383
+ async generatePlans(projectId, options) {
384
+ return this.post(`/projects/${encodeURIComponent(projectId)}/plans/generate`, {
385
+ body: {},
386
+ headers: { 'idempotency-key': options.idempotencyKey },
387
+ signal: options.signal,
388
+ retryOnConflict: false,
389
+ });
390
+ }
391
+ /**
392
+ * GET /api/cli/v1/projects/{projectId}/plans (DEV-384 V3-B)
393
+ * Pure read: the facade-synthesized generation status, the staged
394
+ * proposal list (stable proposalIds — what `accept --only` consumes),
395
+ * and a best-effort credits block. When `waitSeconds` (1–25) is
396
+ * provided the server long-polls: one request per window, answered
397
+ * early on any change.
398
+ */
399
+ async getPlans(projectId, options) {
400
+ return this.get(`/projects/${encodeURIComponent(projectId)}/plans`, {
401
+ query: options?.waitSeconds !== undefined ? { waitSeconds: options.waitSeconds } : undefined,
402
+ signal: options?.signal,
403
+ });
404
+ }
405
+ /**
406
+ * POST /api/cli/v1/projects/{projectId}/plans/accept (DEV-384 V3-B)
407
+ * Convert staged proposals into real test cases. `only` is ALWAYS an
408
+ * explicit, non-empty id list — the caller enforces the two §3.3 safety
409
+ * rules (full list when the user didn't subset; an empty selection is a
410
+ * client-side validation error because `[]` is server-destructive:
411
+ * it means "reject everything" and clears the staged batch).
412
+ */
413
+ async acceptPlans(projectId, only, options) {
414
+ return this.post(`/projects/${encodeURIComponent(projectId)}/plans/accept`, {
415
+ body: { only },
416
+ headers: { 'idempotency-key': options.idempotencyKey },
417
+ signal: options.signal,
418
+ retryOnConflict: false,
419
+ });
420
+ }
286
421
  /**
287
422
  * Classify an error thrown while issuing OR reading a request. When it is an
288
423
  * abort/timeout and our per-request timeout signal fired (and the caller had
@@ -435,12 +570,28 @@ export class HttpClient {
435
570
  });
436
571
  let raw;
437
572
  try {
438
- raw = await response.json();
573
+ if (response.status === 204 && options.allowNoContent === true) {
574
+ // Only explicitly bodyless endpoints may bypass the historical
575
+ // JSON-envelope contract. Every other 204 still falls through
576
+ // to JSON.parse('') and becomes a typed malformed-response error.
577
+ raw = undefined;
578
+ }
579
+ else {
580
+ // Bounded read, then parse — assigning to `raw` rather than returning
581
+ // here keeps the schema validation below on the success path.
582
+ const text = await readBoundedText(response, this.maxResponseBytes, requestId);
583
+ raw = JSON.parse(text);
584
+ }
439
585
  }
440
586
  catch (err) {
441
587
  // Interrupt passthrough (see the fetch catch above).
442
588
  if (err instanceof InterruptError)
443
589
  throw err;
590
+ // A bounded-read rejection (PAYLOAD_TOO_LARGE) — or any typed ApiError —
591
+ // is a real, actionable outcome; surface it unchanged rather than
592
+ // masking it as a malformed-body error below.
593
+ if (err instanceof ApiError)
594
+ throw err;
444
595
  // A timeout/abort can fire mid-body-read (headers received, stream stalls).
445
596
  this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
446
597
  // Otherwise the successful response body was not valid JSON — a
@@ -805,6 +956,96 @@ export function malformedResponseError(response, requestId, cause) {
805
956
  },
806
957
  }, response.status);
807
958
  }
959
+ /**
960
+ * Read a successful response body as text, bounded to `maxBytes`.
961
+ *
962
+ * `response.json()` buffers the ENTIRE body into memory before parsing, with no
963
+ * upper limit — a large `test result --history` page, or a run with a long
964
+ * `steps[]` array (getRun `includeSteps`), grows the heap in proportion to the
965
+ * payload. This reads the body incrementally and stops once the accumulated
966
+ * size crosses `maxBytes`, so a pathological (or hostile) response fails fast
967
+ * with a typed PAYLOAD_TOO_LARGE error instead of exhausting memory.
968
+ *
969
+ * A declared `Content-Length` over the cap is rejected before any body is read.
970
+ * Chunked bodies (no `Content-Length`) are bounded by counting bytes as they
971
+ * stream. Decoding happens once, at the end, so multi-byte UTF-8 sequences that
972
+ * straddle a chunk boundary still decode correctly.
973
+ */
974
+ async function readBoundedText(response, maxBytes, requestId) {
975
+ const declared = Number(response.headers.get('content-length'));
976
+ if (Number.isFinite(declared) && declared > maxBytes) {
977
+ throw responseTooLargeError(requestId, maxBytes, declared);
978
+ }
979
+ const stream = response.body;
980
+ if (stream === null) {
981
+ // No readable stream exposed (some runtimes / test doubles): fall back to a
982
+ // buffered read, then enforce the cap on the materialized text.
983
+ const text = await response.text();
984
+ if (new TextEncoder().encode(text).length > maxBytes) {
985
+ throw responseTooLargeError(requestId, maxBytes);
986
+ }
987
+ return text;
988
+ }
989
+ const reader = stream.getReader();
990
+ const chunks = [];
991
+ let total = 0;
992
+ try {
993
+ for (;;) {
994
+ const { done, value } = await reader.read();
995
+ if (done)
996
+ break;
997
+ if (value === undefined)
998
+ continue;
999
+ total += value.byteLength;
1000
+ if (total > maxBytes) {
1001
+ await reader.cancel();
1002
+ throw responseTooLargeError(requestId, maxBytes, total);
1003
+ }
1004
+ chunks.push(value);
1005
+ }
1006
+ }
1007
+ finally {
1008
+ try {
1009
+ reader.releaseLock();
1010
+ }
1011
+ catch {
1012
+ // The reader may already be released after cancel(); releasing twice is a
1013
+ // no-op we don't want surfacing over the original error.
1014
+ }
1015
+ }
1016
+ return new TextDecoder('utf-8').decode(concatChunks(chunks, total));
1017
+ }
1018
+ /** Concatenate byte chunks into a single `Uint8Array` of known total length. */
1019
+ function concatChunks(chunks, total) {
1020
+ const out = new Uint8Array(total);
1021
+ let offset = 0;
1022
+ for (const chunk of chunks) {
1023
+ out.set(chunk, offset);
1024
+ offset += chunk.byteLength;
1025
+ }
1026
+ return out;
1027
+ }
1028
+ /**
1029
+ * Typed error for a response body that exceeds the client-side buffering cap.
1030
+ * Reuses PAYLOAD_TOO_LARGE (exit 5, validation family) — the same code the
1031
+ * backend returns for oversized request bodies — so machine consumers route on
1032
+ * it uniformly. `nextAction` names the knobs that shrink the result set.
1033
+ */
1034
+ function responseTooLargeError(requestId, maxBytes, observedBytes) {
1035
+ const limitMiB = Math.round(maxBytes / (1024 * 1024));
1036
+ return new ApiError({
1037
+ code: 'PAYLOAD_TOO_LARGE',
1038
+ message: `The server response exceeded the client-side ${limitMiB} MiB limit and was not ` +
1039
+ `buffered, to avoid unbounded memory use.`,
1040
+ nextAction: 'Narrow the result set and retry — e.g. a smaller --page-size, a tighter --since ' +
1041
+ 'window, or scope --history to a single run.',
1042
+ requestId,
1043
+ details: {
1044
+ maxBytes,
1045
+ ...(observedBytes !== undefined ? { observedBytes } : {}),
1046
+ },
1047
+ });
1048
+ }
808
1049
  export function parseRetryAfter(headerValue) {
809
1050
  if (!headerValue)
810
1051
  return undefined;
@@ -12,8 +12,10 @@
12
12
  * Broken pipe: when output is piped to a reader that closes early
13
13
  * (`testsprite ... | head`), the kernel raises `EPIPE` on the next stdout write.
14
14
  * Node turns an `'error'` with no listener into an uncaughtException and dumps a
15
- * raw `write EPIPE` stack (exit 1). The guard swallows it and exits 0, the
16
- * conventional SIGPIPE-equivalent result for "the reader went away".
15
+ * raw `write EPIPE` stack (exit 1). Outside an armed lifetime the guard exits
16
+ * 0 immediately, the conventional SIGPIPE-equivalent result. While armed it
17
+ * first requests coordinated shutdown so tunnel cleanup can finish, then the
18
+ * same synthetic interrupt reason preserves exit 0.
17
19
  *
18
20
  * `process` and the streams are injectable so the wiring is unit-testable
19
21
  * without spawning a subprocess or sending a real signal.
@@ -28,10 +30,12 @@ export declare const SIGINT_EXIT_CODE: 130;
28
30
  * only these members, and tests can supply a lightweight fake.
29
31
  */
30
32
  export interface ShutdownHandle {
31
- /** Aborts (reason: `InterruptError`) when a termination signal arrives while armed. */
33
+ /** Aborts with the graceful-stop reason when a signal/EPIPE arrives while armed. */
32
34
  readonly signal: AbortSignal;
33
35
  /** Enter a graceful-detach scope. Returns the disposer that leaves it. */
34
36
  arm(): () => void;
37
+ /** Run and track cleanup that a repeated signal may briefly wait for. */
38
+ runCriticalOperation<T>(operation: () => Promise<T>): Promise<T>;
35
39
  }
36
40
  /**
37
41
  * Process-lifetime coordinator between the signal handler and the `--wait`
@@ -40,7 +44,7 @@ export interface ShutdownHandle {
40
44
  * Two modes, chosen by whether a graceful-detach scope is armed when the
41
45
  * signal arrives:
42
46
  *
43
- * - **Armed** (inside `pollRunUntilTerminal`): the handler only aborts
47
+ * - **Armed** (inside `pollRunUntilTerminal` or a tunnel lifetime): the handler only aborts
44
48
  * `signal` with an `InterruptError` — no I/O, no exit. The in-flight fetch
45
49
  * and every backoff sleep bail immediately; the `--wait` catch blocks own
46
50
  * the cleanup (finalize the ticker, print the honest partial envelope +
@@ -50,25 +54,42 @@ export interface ShutdownHandle {
50
54
  * immediately, preserving the pre-DEV-331 behavior. An abort nobody
51
55
  * observes must never leave the process hanging at e.g. a readline prompt.
52
56
  *
53
- * A second signal while the armed cleanup is in flight is the documented
54
- * escape hatch: immediate hard exit.
57
+ * 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.
55
59
  */
56
60
  export declare class ShutdownController {
57
61
  private readonly controller;
62
+ private readonly criticalOperations;
58
63
  private armedCount;
59
- private receivedSignal;
64
+ private receivedCause;
60
65
  constructor();
61
66
  get signal(): AbortSignal;
62
- /** The first termination signal received, or null if none yet. */
63
- get received(): TerminationSignal | null;
67
+ /** The first graceful-shutdown cause received, or null if none yet. */
68
+ get received(): TerminationSignal | 'EPIPE' | null;
64
69
  get isArmed(): boolean;
65
70
  /**
66
71
  * Enter a graceful-detach scope (re-entrant: fan-out members overlap).
67
72
  * Returns an idempotent disposer.
68
73
  */
69
74
  arm(): () => void;
75
+ /** Whether teardown currently has work whose abrupt loss is security-sensitive. */
76
+ get hasCriticalOperations(): boolean;
77
+ /**
78
+ * Register cleanup before it starts and remove it automatically when it
79
+ * settles. Rejections retain their original semantics for the caller.
80
+ */
81
+ runCriticalOperation<T>(operation: () => Promise<T>): Promise<T>;
82
+ /** Wait until all current and directly chained critical cleanup settles. */
83
+ waitForCriticalOperations(): Promise<void>;
70
84
  /** Record the signal and abort with an `InterruptError` carrying it. */
71
85
  interrupt(signal: TerminationSignal): void;
86
+ /**
87
+ * Abort an armed lifetime after stdout's reader closes. The InterruptError
88
+ * subtype deliberately keeps the existing graceful-detach catch paths in
89
+ * play (including tunnel cancellation), while its exit code stays the
90
+ * SIGPIPE-equivalent success code 0.
91
+ */
92
+ brokenPipe(): void;
72
93
  }
73
94
  /**
74
95
  * The process-wide instance: `index.ts` hands it to `installSignalHandlers`,
@@ -95,8 +116,9 @@ export interface InterruptDeps {
95
116
  * First signal, armed scope: abort-only — the `--wait` catch paths own the
96
117
  * honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
97
118
  * First signal, disarmed: print the generic explanation + exit `128+signum`.
98
- * Second signal (any mode): immediate hard exit — the escape hatch when the
99
- * graceful cleanup itself wedges.
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
121
+ * immediately, including while that grace period is active.
100
122
  */
101
123
  export declare function installSignalHandlers(deps?: InterruptDeps): void;
102
124
  export interface BrokenPipeDeps {
@@ -106,11 +128,14 @@ export interface BrokenPipeDeps {
106
128
  stderr?: NodeJS.EventEmitter;
107
129
  /** Process exit. Defaults to `process.exit`. */
108
130
  exit?: (code: number) => void;
131
+ /** Shutdown coordinator. Defaults to {@link globalShutdown}. */
132
+ shutdown?: ShutdownController;
109
133
  }
110
134
  /**
111
135
  * Guard against `EPIPE` on stdout/stderr so piping to a reader that closes
112
136
  * early (`testsprite ... | head`) exits cleanly instead of crashing with an
113
- * unhandled `write EPIPE` stack. Only `EPIPE` is swallowed; any other stream
114
- * error is left to surface normally.
137
+ * unhandled `write EPIPE` stack. An armed stdout path requests graceful
138
+ * shutdown before exiting 0; a disarmed one exits 0 immediately. Only `EPIPE`
139
+ * is swallowed; any other stream error is left to surface normally.
115
140
  */
116
141
  export declare function installBrokenPipeGuard(deps?: BrokenPipeDeps): void;
@@ -12,8 +12,10 @@
12
12
  * Broken pipe: when output is piped to a reader that closes early
13
13
  * (`testsprite ... | head`), the kernel raises `EPIPE` on the next stdout write.
14
14
  * Node turns an `'error'` with no listener into an uncaughtException and dumps a
15
- * raw `write EPIPE` stack (exit 1). The guard swallows it and exits 0, the
16
- * conventional SIGPIPE-equivalent result for "the reader went away".
15
+ * raw `write EPIPE` stack (exit 1). Outside an armed lifetime the guard exits
16
+ * 0 immediately, the conventional SIGPIPE-equivalent result. While armed it
17
+ * first requests coordinated shutdown so tunnel cleanup can finish, then the
18
+ * same synthetic interrupt reason preserves exit 0.
17
19
  *
18
20
  * `process` and the streams are injectable so the wiring is unit-testable
19
21
  * without spawning a subprocess or sending a real signal.
@@ -31,7 +33,7 @@ export const SIGINT_EXIT_CODE = TERMINATION_EXIT_CODES.SIGINT;
31
33
  * Two modes, chosen by whether a graceful-detach scope is armed when the
32
34
  * signal arrives:
33
35
  *
34
- * - **Armed** (inside `pollRunUntilTerminal`): the handler only aborts
36
+ * - **Armed** (inside `pollRunUntilTerminal` or a tunnel lifetime): the handler only aborts
35
37
  * `signal` with an `InterruptError` — no I/O, no exit. The in-flight fetch
36
38
  * and every backoff sleep bail immediately; the `--wait` catch blocks own
37
39
  * the cleanup (finalize the ticker, print the honest partial envelope +
@@ -41,13 +43,14 @@ export const SIGINT_EXIT_CODE = TERMINATION_EXIT_CODES.SIGINT;
41
43
  * immediately, preserving the pre-DEV-331 behavior. An abort nobody
42
44
  * observes must never leave the process hanging at e.g. a readline prompt.
43
45
  *
44
- * A second signal while the armed cleanup is in flight is the documented
45
- * escape hatch: immediate hard exit.
46
+ * 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.
46
48
  */
47
49
  export class ShutdownController {
48
50
  controller = new AbortController();
51
+ criticalOperations = new Set();
49
52
  armedCount = 0;
50
- receivedSignal = null;
53
+ receivedCause = null;
51
54
  constructor() {
52
55
  // Every fetch and every poll iteration composes this signal via
53
56
  // AbortSignal.any — a 50-run batch fan-out legitimately holds >10
@@ -57,9 +60,9 @@ export class ShutdownController {
57
60
  get signal() {
58
61
  return this.controller.signal;
59
62
  }
60
- /** The first termination signal received, or null if none yet. */
63
+ /** The first graceful-shutdown cause received, or null if none yet. */
61
64
  get received() {
62
- return this.receivedSignal;
65
+ return this.receivedCause;
63
66
  }
64
67
  get isArmed() {
65
68
  return this.armedCount > 0;
@@ -78,11 +81,56 @@ export class ShutdownController {
78
81
  this.armedCount -= 1;
79
82
  };
80
83
  }
84
+ /** Whether teardown currently has work whose abrupt loss is security-sensitive. */
85
+ get hasCriticalOperations() {
86
+ return this.criticalOperations.size > 0;
87
+ }
88
+ /**
89
+ * Register cleanup before it starts and remove it automatically when it
90
+ * settles. Rejections retain their original semantics for the caller.
91
+ */
92
+ runCriticalOperation(operation) {
93
+ const started = Promise.resolve().then(operation);
94
+ const tracked = started.finally(() => {
95
+ this.criticalOperations.delete(tracked);
96
+ });
97
+ this.criticalOperations.add(tracked);
98
+ return tracked;
99
+ }
100
+ /** Wait until all current and directly chained critical cleanup settles. */
101
+ async waitForCriticalOperations() {
102
+ while (this.criticalOperations.size > 0) {
103
+ await Promise.allSettled([...this.criticalOperations]);
104
+ }
105
+ }
81
106
  /** Record the signal and abort with an `InterruptError` carrying it. */
82
107
  interrupt(signal) {
83
- this.receivedSignal = signal;
108
+ this.receivedCause = signal;
84
109
  this.controller.abort(new InterruptError(signal));
85
110
  }
111
+ /**
112
+ * Abort an armed lifetime after stdout's reader closes. The InterruptError
113
+ * subtype deliberately keeps the existing graceful-detach catch paths in
114
+ * play (including tunnel cancellation), while its exit code stays the
115
+ * SIGPIPE-equivalent success code 0.
116
+ */
117
+ brokenPipe() {
118
+ if (this.receivedCause !== null)
119
+ return;
120
+ this.receivedCause = 'EPIPE';
121
+ this.controller.abort(new BrokenPipeInterruptError());
122
+ }
123
+ }
124
+ class BrokenPipeInterruptError extends InterruptError {
125
+ exitCode = 0;
126
+ constructor() {
127
+ // Existing graceful-detach consumers read `.signal` to render their
128
+ // partial status. The distinct name/message and exitCode carry the real
129
+ // cause without widening the OS-signal contract in errors.ts.
130
+ super('SIGINT');
131
+ this.name = 'BrokenPipeInterruptError';
132
+ this.message = 'Output pipe closed.';
133
+ }
86
134
  }
87
135
  /**
88
136
  * The process-wide instance: `index.ts` hands it to `installSignalHandlers`,
@@ -95,6 +143,38 @@ export function formatInterruptMessage(signal = 'SIGINT') {
95
143
  return (`Interrupted (${signal}). Any run already started keeps executing on the server; ` +
96
144
  'check it with `testsprite test list` or `testsprite test wait <runId>`.');
97
145
  }
146
+ const CRITICAL_OPERATION_GRACE_MS = 2_000;
147
+ /** How often the grace period re-checks whether teardown is still running. */
148
+ const CRITICAL_OPERATION_POLL_MS = 10;
149
+ function afterDelay(ms) {
150
+ return new Promise(resolve => {
151
+ const timer = setTimeout(resolve, ms);
152
+ timer.unref?.();
153
+ });
154
+ }
155
+ async function waitForCriticalOperationsWithGrace(shutdown) {
156
+ const graceExpired = afterDelay(CRITICAL_OPERATION_GRACE_MS);
157
+ const teardownFinished = (async () => {
158
+ // An armed scope is the honest signal that teardown has not finished. On a
159
+ // tunnel run it spans the whole unwind — cancel, then close, then the
160
+ // credential delete — and those register one at a time with gaps between
161
+ // them, so "no critical operation right now" does not mean "done". A fixed
162
+ // settle window is the wrong shape: measured against the real command, the
163
+ // first registration lands well after any window short enough to keep the
164
+ // escape hatch snappy. Waiting for the scope to close instead tracks the
165
+ // actual work, and the caller's overall cap keeps it bounded.
166
+ while (shutdown.isArmed) {
167
+ if (shutdown.hasCriticalOperations) {
168
+ await shutdown.waitForCriticalOperations();
169
+ }
170
+ else {
171
+ await afterDelay(CRITICAL_OPERATION_POLL_MS);
172
+ }
173
+ }
174
+ await shutdown.waitForCriticalOperations();
175
+ })();
176
+ await Promise.race([graceExpired, teardownFinished]);
177
+ }
98
178
  /**
99
179
  * Register handlers for SIGINT, SIGTERM and SIGHUP. Idempotent enough for a
100
180
  * single top-level call in `index.ts`; not designed to be installed twice.
@@ -102,8 +182,9 @@ export function formatInterruptMessage(signal = 'SIGINT') {
102
182
  * First signal, armed scope: abort-only — the `--wait` catch paths own the
103
183
  * honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
104
184
  * First signal, disarmed: print the generic explanation + exit `128+signum`.
105
- * Second signal (any mode): immediate hard exit — the escape hatch when the
106
- * graceful cleanup itself wedges.
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
187
+ * immediately, including while that grace period is active.
107
188
  */
108
189
  export function installSignalHandlers(deps = {}) {
109
190
  const on = deps.on ??
@@ -124,13 +205,38 @@ export function installSignalHandlers(deps = {}) {
124
205
  });
125
206
  const exit = deps.exit ?? ((code) => process.exit(code));
126
207
  const shutdown = deps.shutdown ?? globalShutdown;
208
+ let signalCount = 0;
209
+ let graceGeneration = 0;
127
210
  for (const signal of Object.keys(TERMINATION_EXIT_CODES)) {
128
211
  on(signal, () => {
129
- if (shutdown.received !== null) {
130
- // Second signal while graceful cleanup is in flight: hard exit now.
212
+ signalCount += 1;
213
+ if (signalCount >= 3) {
214
+ // Invalidate any second-signal grace continuation before hard exit.
215
+ graceGeneration += 1;
131
216
  exit(TERMINATION_EXIT_CODES[signal]);
132
217
  return;
133
218
  }
219
+ if (signalCount === 2) {
220
+ // `isArmed` matters as much as an already-registered operation: on a
221
+ // tunnel run the lifecycle scope stays armed across teardown, and the
222
+ // credential delete is registered only after the poll loop unwinds. A
223
+ // second signal that arrives in between — which is what a reflexive
224
+ // 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.
227
+ if (!shutdown.hasCriticalOperations && !shutdown.isArmed) {
228
+ exit(TERMINATION_EXIT_CODES[signal]);
229
+ return;
230
+ }
231
+ const generation = ++graceGeneration;
232
+ void waitForCriticalOperationsWithGrace(shutdown).then(() => {
233
+ // A third signal already took the immediate path.
234
+ if (graceGeneration !== generation)
235
+ return;
236
+ exit(TERMINATION_EXIT_CODES[signal]);
237
+ });
238
+ return;
239
+ }
134
240
  if (shutdown.isArmed) {
135
241
  // Graceful detach: abort only (sync, signal-safe — no I/O here so a
136
242
  // pending stdout `drain` wait can settle); the armed catch paths
@@ -154,18 +260,27 @@ export function installSignalHandlers(deps = {}) {
154
260
  /**
155
261
  * Guard against `EPIPE` on stdout/stderr so piping to a reader that closes
156
262
  * early (`testsprite ... | head`) exits cleanly instead of crashing with an
157
- * unhandled `write EPIPE` stack. Only `EPIPE` is swallowed; any other stream
158
- * error is left to surface normally.
263
+ * unhandled `write EPIPE` stack. An armed stdout path requests graceful
264
+ * shutdown before exiting 0; a disarmed one exits 0 immediately. Only `EPIPE`
265
+ * is swallowed; any other stream error is left to surface normally.
159
266
  */
160
267
  export function installBrokenPipeGuard(deps = {}) {
161
268
  const stdout = deps.stdout ?? process.stdout;
162
269
  const stderr = deps.stderr ?? process.stderr;
163
270
  const exit = deps.exit ?? ((code) => process.exit(code));
271
+ const shutdown = deps.shutdown ?? globalShutdown;
164
272
  stdout.on('error', (error) => {
165
273
  // Reader went away (`| head`, `| less` then q): exit cleanly like SIGPIPE
166
274
  // rather than dumping an unhandled `write EPIPE` stack. Any other stdout
167
275
  // error is a genuine, actionable failure, so re-throw it (Node's default).
168
276
  if (error.code === 'EPIPE') {
277
+ if (shutdown.isArmed) {
278
+ // A tunnel lifetime owns credential teardown in its `finally`. Abort
279
+ // through the same coordinator as the first signal and let that
280
+ // cleanup finish; the synthetic reason exits 0 once it propagates.
281
+ shutdown.brokenPipe();
282
+ return;
283
+ }
169
284
  exit(0);
170
285
  return;
171
286
  }