@testsprite/testsprite-cli 0.13.0 → 0.15.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 (81) hide show
  1. package/README.md +54 -49
  2. package/dist/commands/ci.d.ts +66 -17
  3. package/dist/commands/ci.js +466 -104
  4. package/dist/commands/doctor.d.ts +3 -0
  5. package/dist/commands/doctor.js +62 -20
  6. package/dist/commands/init.js +17 -3
  7. package/dist/commands/project-env.d.ts +11 -1
  8. package/dist/commands/project-env.js +399 -61
  9. package/dist/commands/project-sign-in.d.ts +60 -0
  10. package/dist/commands/project-sign-in.js +289 -0
  11. package/dist/commands/project.d.ts +9 -0
  12. package/dist/commands/project.js +82 -28
  13. package/dist/commands/schedule.d.ts +12 -0
  14. package/dist/commands/schedule.js +175 -5
  15. package/dist/commands/test.d.ts +126 -30
  16. package/dist/commands/test.js +1928 -447
  17. package/dist/commands/testlist.d.ts +10 -5
  18. package/dist/commands/testlist.js +170 -30
  19. package/dist/commands/tunnel.js +11 -5
  20. package/dist/index.js +17 -38
  21. package/dist/lib/agent-targets.d.ts +8 -3
  22. package/dist/lib/agent-targets.js +15 -4
  23. package/dist/lib/ci-run.d.ts +11 -0
  24. package/dist/lib/ci-run.js +34 -0
  25. package/dist/lib/client-factory.d.ts +35 -1
  26. package/dist/lib/client-factory.js +21 -10
  27. package/dist/lib/config.d.ts +1 -0
  28. package/dist/lib/config.js +1 -1
  29. package/dist/lib/credentials.d.ts +0 -1
  30. package/dist/lib/credentials.js +51 -14
  31. package/dist/lib/dry-run/samples.js +95 -1
  32. package/dist/lib/environment-tunnel.d.ts +109 -0
  33. package/dist/lib/environment-tunnel.js +465 -0
  34. package/dist/lib/errors.js +12 -1
  35. package/dist/lib/first-suite-hint.d.ts +55 -0
  36. package/dist/lib/first-suite-hint.js +101 -0
  37. package/dist/lib/gh-output.d.ts +62 -4
  38. package/dist/lib/gh-output.js +152 -7
  39. package/dist/lib/github-context.d.ts +21 -0
  40. package/dist/lib/github-context.js +153 -0
  41. package/dist/lib/http.d.ts +12 -1
  42. package/dist/lib/http.js +9 -1
  43. package/dist/lib/junit-report.d.ts +11 -7
  44. package/dist/lib/junit-report.js +13 -7
  45. package/dist/lib/local-target.d.ts +13 -3
  46. package/dist/lib/local-target.js +47 -12
  47. package/dist/lib/output.js +15 -1
  48. package/dist/lib/plan-poll.js +3 -4
  49. package/dist/lib/plans.types.d.ts +1 -1
  50. package/dist/lib/redact.d.ts +38 -0
  51. package/dist/lib/redact.js +140 -0
  52. package/dist/lib/render-error.d.ts +19 -5
  53. package/dist/lib/render-error.js +31 -0
  54. package/dist/lib/response-schemas.d.ts +5 -1
  55. package/dist/lib/response-schemas.js +54 -0
  56. package/dist/lib/runs.types.d.ts +115 -1
  57. package/dist/lib/target-url.js +5 -5
  58. package/dist/lib/telemetry.d.ts +31 -8
  59. package/dist/lib/telemetry.js +55 -7
  60. package/dist/lib/testlist.types.d.ts +1 -0
  61. package/dist/lib/ticker.d.ts +9 -0
  62. package/dist/lib/ticker.js +18 -0
  63. package/dist/lib/tunnel-session.d.ts +3 -4
  64. package/dist/lib/tunnel-session.js +3 -4
  65. package/dist/lib/v3-advisory.js +0 -1
  66. package/dist/vendor/tunnel-client/client.d.ts +15 -8
  67. package/dist/vendor/tunnel-client/client.js +477 -407
  68. package/dist/vendor/tunnel-client/config.d.ts +5 -5
  69. package/dist/vendor/tunnel-client/config.js +5 -5
  70. package/dist/vendor/tunnel-client/index.d.ts +4 -4
  71. package/dist/vendor/tunnel-client/index.js +4 -4
  72. package/dist/vendor/tunnel-client/types.d.ts +19 -34
  73. package/dist/vendor/tunnel-client/types.js +1 -0
  74. package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
  75. package/dist/vendor/tunnel-client/ws-compat.js +70 -12
  76. package/dist/version.d.ts +1 -1
  77. package/dist/version.js +1 -1
  78. package/package.json +1 -1
  79. package/schemas/plan.schema.json +2 -2
  80. package/skills/testsprite-ci.skill.md +154 -0
  81. package/skills/testsprite-onboard.skill.md +4 -4
@@ -1,9 +1,16 @@
1
+ import { type EnvironmentTunnelContext } from '../lib/environment-tunnel.js';
2
+ import { type ShutdownHandle } from '../lib/interrupt.js';
3
+ import type { TunnelClientOptions } from '../vendor/tunnel-client/index.js';
4
+ import type { TunnelClientHandle } from '../lib/tunnel-session.js';
1
5
  import { Command } from 'commander';
2
6
  import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
3
7
  import { type FetchImpl } from '../lib/http.js';
4
8
  import { type JUnitReportFormat } from '../lib/junit-report.js';
5
9
  import type { CliDeleteTestListResponse, CliTestList, CliTestListDetail, CliTestListRunResponse } from '../lib/testlist.types.js';
6
10
  export interface TestListDeps {
11
+ shutdown?: ShutdownHandle;
12
+ createTunnelClient?: (options: TunnelClientOptions) => TunnelClientHandle;
13
+ environmentTunnel?: EnvironmentTunnelContext;
7
14
  env?: NodeJS.ProcessEnv;
8
15
  credentialsPath?: string;
9
16
  fetchImpl?: FetchImpl;
@@ -60,6 +67,9 @@ export declare function waitRequestTimeoutMs(opts: {
60
67
  requestTimeoutMs?: number;
61
68
  }): number | undefined;
62
69
  export interface RunTestlistRunOptions extends CommonOptions {
70
+ noWait?: boolean;
71
+ skipPreflight?: boolean;
72
+ concurrencyIsDefault?: boolean;
63
73
  listId: string;
64
74
  /** --case (repeatable): run only this subset of the list's cases (== test ids). */
65
75
  cases?: string[];
@@ -78,11 +88,6 @@ export interface RunTestlistRunOptions extends CommonOptions {
78
88
  /** --summary-file: also write the reduced machine summary JSON to this path. */
79
89
  summaryFile?: string;
80
90
  }
81
- /**
82
- * `testlist run` — dispatch the list's cases (optionally a `--case` subset) and,
83
- * with `--wait`, poll every returned runId to a verdict, optionally writing a
84
- * JUnit XML report (`--report junit`). testlist run is V3-only.
85
- */
86
91
  export declare function runTestlistRun(opts: RunTestlistRunOptions, deps?: TestListDeps): Promise<CliTestListRunResponse>;
87
92
  export declare function createTestListCommand(deps?: TestListDeps): Command;
88
93
  export {};
@@ -1,3 +1,6 @@
1
+ import { TunnelLostError } from '../lib/tunnel-session.js';
2
+ import { resolveEnvironmentRunTarget, readEnvironmentPreflight, groupEnvironmentTargets, emitEnvironmentDispatchPartial, withEnvironmentTunnel, } from '../lib/environment-tunnel.js';
3
+ import { globalShutdown } from '../lib/interrupt.js';
1
4
  import { randomUUID } from 'node:crypto';
2
5
  import { Command } from 'commander';
3
6
  import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
@@ -11,7 +14,7 @@ import { billingConflictLink, describeConflict, insufficientCreditsConflictError
11
14
  import { recordBatchOutcome } from '../lib/telemetry.js';
12
15
  import { formatRunProgressLine } from '../lib/run-progress.js';
13
16
  import { createTicker } from '../lib/ticker.js';
14
- import { buildJUnitReport, parseJUnitReportFormat, skippedJUnitResultsFromSummary, writeJUnitReportFile, } from '../lib/junit-report.js';
17
+ import { buildJUnitReport, durationSecondsBetween, parseJUnitReportFormat, skippedJUnitResultsFromSummary, writeJUnitReportFile, } from '../lib/junit-report.js';
15
18
  import { renderTextTable, resolveTextColumns } from '../lib/text-table.js';
16
19
  import { assertIdempotencyKey } from '../lib/validate.js';
17
20
  import { resolveWaitFailure, waitMemberError } from '../lib/wait-exit.js';
@@ -289,9 +292,7 @@ function assertNoNotFound(resp) {
289
292
  * with `--wait`, poll every returned runId to a verdict, optionally writing a
290
293
  * JUnit XML report (`--report junit`). testlist run is V3-only.
291
294
  */
292
- export async function runTestlistRun(opts, deps = {}) {
293
- const out = makeOutput(opts.output, deps);
294
- const stderrFn = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
295
+ function validateTestlistRunOptions(opts) {
295
296
  if (opts.idempotencyKey !== undefined)
296
297
  assertIdempotencyKey(opts.idempotencyKey);
297
298
  if (!Number.isInteger(opts.maxConcurrency) ||
@@ -316,6 +317,74 @@ export async function runTestlistRun(opts, deps = {}) {
316
317
  if (opts.summaryFile !== undefined && !opts.wait) {
317
318
  throw localValidationError('summary-file', '--summary-file requires --wait (it reduces the terminal run result). Add --wait.');
318
319
  }
320
+ }
321
+ export async function runTestlistRun(opts, deps = {}) {
322
+ validateTestlistRunOptions({ ...opts, wait: opts.wait || (!opts.dryRun && !opts.noWait) });
323
+ if (opts.dryRun || deps.environmentTunnel)
324
+ return runTestlistRunCore(opts, deps);
325
+ let client;
326
+ try {
327
+ client = makeClient(opts, deps);
328
+ }
329
+ catch (err) {
330
+ validateTestlistRunOptions(opts);
331
+ throw err;
332
+ }
333
+ const stderr = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
334
+ let list;
335
+ try {
336
+ list = await readEnvironmentPreflight(client, `/testlist/${encodeURIComponent(opts.listId)}`);
337
+ }
338
+ catch (err) {
339
+ if (err instanceof InterruptError)
340
+ throw err;
341
+ return runTestlistRunCore(opts, deps);
342
+ }
343
+ const targets = new Map();
344
+ const backend = [];
345
+ const cache = new Map();
346
+ for (const test of list.cases ?? []) {
347
+ if (opts.cases?.length && !opts.cases.includes(test.testId))
348
+ continue;
349
+ const environment = list.projectEnvironments?.find(row => row.projectId === test.projectId)?.environmentName;
350
+ const target = await resolveEnvironmentRunTarget({
351
+ client,
352
+ testId: test.testId,
353
+ knownTest: test,
354
+ includeBackend: true,
355
+ environment,
356
+ noWait: opts.noWait,
357
+ verbose: opts.verbose || opts.debug,
358
+ stderr,
359
+ cache,
360
+ });
361
+ if (target && test.type === 'backend')
362
+ backend.push({ testId: test.testId, reason: 'backend-test' });
363
+ else if (target)
364
+ targets.set(test.testId, target);
365
+ }
366
+ if (!targets.size)
367
+ return runTestlistRunCore(opts, deps);
368
+ const maxConcurrency = opts.concurrencyIsDefault ? 5 : opts.maxConcurrency;
369
+ if (maxConcurrency > 10)
370
+ throw localValidationError('max-concurrency', 'tunnel runs support at most 10 concurrent runs (default 5)');
371
+ if (backend.length)
372
+ stderr(`[advisory] ${backend.length} backend test(s) skipped — tunnel runs frontend tests only.`);
373
+ const cases = (list.cases ?? [])
374
+ .filter(test => !backend.some(row => row.testId === test.testId) &&
375
+ (!opts.cases?.length || opts.cases.includes(test.testId)))
376
+ .map(test => test.testId);
377
+ cases.push(...(opts.cases ?? []).filter(id => !list.cases?.some(test => test.testId === id)));
378
+ return withEnvironmentTunnel({ ...opts, maxConcurrency, requestTimeoutMs: waitRequestTimeoutMs({ ...opts, wait: true }) }, deps, [...targets.values()], 'testlist run', context => {
379
+ context.targets = targets;
380
+ context.skipped = backend;
381
+ return runTestlistRunCore({ ...opts, cases, wait: true, maxConcurrency }, { ...deps, environmentTunnel: context });
382
+ });
383
+ }
384
+ async function runTestlistRunCore(opts, deps = {}) {
385
+ validateTestlistRunOptions(opts);
386
+ const out = makeOutput(opts.output, deps);
387
+ const stderrFn = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
319
388
  const idempotencyKey = opts.idempotencyKey ?? `cli-testlist-run-${randomUUID()}`;
320
389
  emitIdempotencyKey(opts, deps, idempotencyKey, opts.idempotencyKey);
321
390
  if (opts.dryRun) {
@@ -325,8 +394,51 @@ export async function runTestlistRun(opts, deps = {}) {
325
394
  return sample;
326
395
  }
327
396
  // Under --wait, raise the per-request timeout to cover --timeout (see helper).
328
- const client = makeClient({ ...opts, requestTimeoutMs: waitRequestTimeoutMs(opts) }, deps);
329
- const resp = await client.triggerTestListRun(opts.listId, opts.cases && opts.cases.length > 0 ? { testIds: opts.cases } : {}, { idempotencyKey });
397
+ const client = deps.environmentTunnel?.client ??
398
+ makeClient({ ...opts, requestTimeoutMs: waitRequestTimeoutMs(opts) }, deps);
399
+ let resp;
400
+ if (deps.environmentTunnel) {
401
+ const targets = deps.environmentTunnel.targets;
402
+ const groups = groupEnvironmentTargets(opts.cases ?? [...targets.keys()], targets, deps.environmentTunnel.maxConcurrency);
403
+ const responses = [];
404
+ try {
405
+ for (const [index, testIds] of groups.entries()) {
406
+ const target = targets.get(testIds[0]);
407
+ const suffix = groups.length > 1 ? `:group${index}` : '';
408
+ if (target)
409
+ await deps.environmentTunnel.waitForCapacity(testIds.length);
410
+ const response = await client.triggerTestListRun(opts.listId, {
411
+ testIds,
412
+ ...(target
413
+ ? { targetUrl: target.targetUrl, tunnelClientId: deps.environmentTunnel.clientId }
414
+ : {}),
415
+ }, { idempotencyKey: `${idempotencyKey.slice(0, 256 - suffix.length)}${suffix}` });
416
+ responses.push(response);
417
+ if (target)
418
+ await deps.environmentTunnel.confirm(response, response.accepted.map(row => row.runId));
419
+ }
420
+ }
421
+ catch (err) {
422
+ if (responses.length)
423
+ await emitEnvironmentDispatchPartial(responses, groups.flat(), opts, deps, 'testlist', err, deps.environmentTunnel);
424
+ throw err;
425
+ }
426
+ resp = {
427
+ ...responses[0],
428
+ ...(deps.environmentTunnel.skipped?.length
429
+ ? { skipped: deps.environmentTunnel.skipped }
430
+ : {}),
431
+ accepted: responses.flatMap(row => row.accepted),
432
+ conflicts: responses.flatMap(row => row.conflicts),
433
+ deferred: responses.flatMap(row => row.deferred),
434
+ ...(responses.some(row => row.notFound)
435
+ ? { notFound: responses.flatMap(row => row.notFound ?? []) }
436
+ : {}),
437
+ };
438
+ }
439
+ else {
440
+ resp = await client.triggerTestListRun(opts.listId, opts.cases && opts.cases.length > 0 ? { testIds: opts.cases } : {}, { idempotencyKey });
441
+ }
330
442
  // Partial `--case` miss: some ids were not members of this list. The matched
331
443
  // subset still dispatched; a FULL miss is a 404 upstream and never reaches
332
444
  // here. Warn on stderr so JSON stdout stays the machine payload (the ids are
@@ -428,8 +540,9 @@ export async function runTestlistRun(opts, deps = {}) {
428
540
  // empty-suite report rather than nothing.
429
541
  // --- --wait fan-out ---
430
542
  const ticker = createTicker(stderrFn, opts.output === 'json' ? false : undefined);
431
- const batchDeadlineMs = Date.now() + opts.timeoutSeconds * 1000;
543
+ const batchDeadlineMs = deps.environmentTunnel?.deadlineMs ?? Date.now() + opts.timeoutSeconds * 1000;
432
544
  const results = [];
545
+ const reportDurations = new Map();
433
546
  async function pollOne(entry) {
434
547
  const remainingMs = batchDeadlineMs - Date.now();
435
548
  if (remainingMs <= 0) {
@@ -452,8 +565,13 @@ export async function runTestlistRun(opts, deps = {}) {
452
565
  timeoutSeconds: Math.ceil(remainingMs / 1000),
453
566
  sleep: deps.sleep,
454
567
  onTransition: opts.verbose ? (msg) => stderrFn(`[verbose] ${msg}`) : undefined,
455
- onTick: (run, elapsedMs) => ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`)),
568
+ shutdown: deps.shutdown ?? globalShutdown,
569
+ onTick: (run, elapsedMs) => {
570
+ deps.environmentTunnel?.onPoll(run);
571
+ ticker.update(formatRunProgressLine(run, elapsedMs, `(${entry.testId})`));
572
+ },
456
573
  });
574
+ reportDurations.set(entry.runId, durationSecondsBetween(finalRun.startedAt, finalRun.finishedAt, finalRun.createdAt));
457
575
  return {
458
576
  testId: entry.testId,
459
577
  testTitle: finalRun.testTitle ?? null,
@@ -478,6 +596,8 @@ export async function runTestlistRun(opts, deps = {}) {
478
596
  };
479
597
  }
480
598
  catch (err) {
599
+ if (deps.environmentTunnel && err instanceof TunnelLostError)
600
+ throw err;
481
601
  if (err instanceof TimeoutError) {
482
602
  return {
483
603
  testId: entry.testId,
@@ -519,32 +639,41 @@ export async function runTestlistRun(opts, deps = {}) {
519
639
  // `runTestRunAll`'s inline driver rather than extracting a shared helper).
520
640
  let pollIdx = 0;
521
641
  let inFlight = 0;
522
- await new Promise((resolve, reject) => {
523
- function startNext() {
524
- while (inFlight < opts.maxConcurrency && pollIdx < resp.accepted.length) {
525
- const entry = resp.accepted[pollIdx++];
526
- inFlight++;
527
- pollOne(entry)
528
- .then(r => {
529
- results.push(r);
530
- inFlight--;
531
- startNext();
532
- if (inFlight === 0 && pollIdx >= resp.accepted.length)
533
- resolve();
534
- })
535
- .catch(reject);
642
+ try {
643
+ await new Promise((resolve, reject) => {
644
+ function startNext() {
645
+ while (inFlight < opts.maxConcurrency && pollIdx < resp.accepted.length) {
646
+ const entry = resp.accepted[pollIdx++];
647
+ inFlight++;
648
+ pollOne(entry)
649
+ .then(r => {
650
+ results.push(r);
651
+ inFlight--;
652
+ startNext();
653
+ if (inFlight === 0 && pollIdx >= resp.accepted.length)
654
+ resolve();
655
+ })
656
+ .catch(reject);
657
+ }
536
658
  }
537
- }
538
- startNext();
539
- if (resp.accepted.length === 0)
540
- resolve();
541
- });
659
+ startNext();
660
+ if (resp.accepted.length === 0)
661
+ resolve();
662
+ });
663
+ }
664
+ catch (err) {
665
+ ticker.finalize();
666
+ if (deps.environmentTunnel)
667
+ await emitEnvironmentDispatchPartial([resp], resp.accepted.map(row => row.testId), opts, deps, 'testlist', err, deps.environmentTunnel);
668
+ throw err;
669
+ }
542
670
  ticker.finalize();
543
671
  const passed = results.filter(r => r.status === 'passed').length;
544
672
  const failed = results.filter(r => r.status !== 'passed' && r.status !== 'timeout').length;
545
673
  const timedOut = results.filter(r => r.status === 'timeout').length;
546
674
  stderrFn(`Test-list run complete: ${passed}/${resp.accepted.length} passed, ${failed} failed/blocked, ${timedOut} timed out`);
547
675
  const jsonPayload = {
676
+ ...(deps.environmentTunnel?.skipped?.length ? { skipped: deps.environmentTunnel.skipped } : {}),
548
677
  accepted: results,
549
678
  conflicts: resp.conflicts,
550
679
  deferred: resp.deferred,
@@ -575,7 +704,13 @@ export async function runTestlistRun(opts, deps = {}) {
575
704
  const xml = buildJUnitReport({
576
705
  suiteName,
577
706
  classname: `testlist:${opts.listId}`,
578
- results: [...results, ...skippedJUnitResultsFromSummary(summary)],
707
+ results: [
708
+ ...results.map(r => ({
709
+ ...r,
710
+ durationSeconds: r.runId ? reportDurations.get(r.runId) : undefined,
711
+ })),
712
+ ...skippedJUnitResultsFromSummary(summary, results),
713
+ ],
579
714
  });
580
715
  await writeJUnitReportFile(opts.reportFile, xml);
581
716
  }
@@ -775,11 +910,13 @@ export function createTestListCommand(deps = {}) {
775
910
  });
776
911
  testlist
777
912
  .command('run <list-id>')
778
- .description('Run a test list (dispatch its cases and return pollable run ids)')
913
+ .description('Run a test list (dispatch its cases and return pollable run ids). Loopback environments open a tunnel automatically and wait.')
779
914
  .option('--case <test-id>', 'run only this case (repeatable; default: every case in the list)', collectRepeatable, [])
780
915
  .option('--wait', 'poll every dispatched run until terminal or --timeout', false)
916
+ .option('--no-wait', 'detach without opening an automatic environment tunnel')
917
+ .option('--skip-preflight', 'skip the loopback port probe before opening a tunnel')
781
918
  .option('--timeout <s>', 'with --wait, max seconds to wait (1–3600, default 600)')
782
- .option('--max-concurrency <n>', `with --wait, max in-flight polls at once (1-${MAX_TESTLIST_RUN_CONCURRENCY}, default ${DEFAULT_TESTLIST_RUN_CONCURRENCY})`)
919
+ .option('--max-concurrency <n>', `with a tunnel, max runs in flight (1-10, default 5); otherwise with --wait, max polls (1-${MAX_TESTLIST_RUN_CONCURRENCY}, default ${DEFAULT_TESTLIST_RUN_CONCURRENCY})`)
783
920
  .option('--idempotency-key <key>', 'caller-supplied idempotency key (1-256 chars)')
784
921
  .option('--report <format>', 'with --wait: write a JUnit XML sidecar after polling (accepted: junit)')
785
922
  .option('--report-file <path>', 'output path for --report (atomic write)')
@@ -794,6 +931,9 @@ export function createTestListCommand(deps = {}) {
794
931
  listId,
795
932
  cases: cmdOpts.case,
796
933
  wait,
934
+ noWait: command.getOptionValueSource('wait') === 'cli' && cmdOpts.wait === false,
935
+ skipPreflight: cmdOpts.skipPreflight === true,
936
+ concurrencyIsDefault: cmdOpts.maxConcurrency === undefined,
797
937
  timeoutSeconds: parseTestlistTimeoutFlag(cmdOpts.timeout),
798
938
  maxConcurrency: parseTestlistConcurrencyFlag(cmdOpts.maxConcurrency),
799
939
  idempotencyKey: cmdOpts.idempotencyKey,
@@ -264,7 +264,7 @@ export async function runTunnelStart(opts, deps = {}) {
264
264
  `expiresAt ${d.expiresAt}`,
265
265
  `status online`,
266
266
  `transport ${d.transport}`,
267
- `hint Attach a run: testsprite test run <test-id> --local <port> --tunnel-client ${d.clientId}`,
267
+ `hint Attach a run: testsprite test run <test-id> --env <name> --tunnel-client ${d.clientId}`,
268
268
  `hint Stop it: press Ctrl-C here, or run 'testsprite tunnel stop ${d.clientId}' from another terminal`,
269
269
  ].join('\n');
270
270
  });
@@ -551,15 +551,15 @@ export async function runTunnelStop(opts, deps = {}) {
551
551
  export function createTunnelCommand(deps = {}) {
552
552
  const tunnel = new Command('tunnel')
553
553
  .description('Open a tunnel so TestSprite can reach an app on this machine')
554
- .addHelpText('after', '\n`testsprite test run <id> --local <port>` opens and closes a tunnel for you for a single\n' +
555
- 'run. Use these commands when you want one tunnel to serve several runs, or to check on\n' +
554
+ .addHelpText('after', '\nFrontend runs automatically open and close a tunnel when the selected environment URL\n' +
555
+ 'is on this machine. Use these commands when you want one tunnel to serve several runs, or to check on\n' +
556
556
  'one that a run reported as down.\n' +
557
557
  '\nA tunnel lives only as long as `tunnel start` is running — there is no background\n' +
558
558
  'daemon, because the credential that authorises an inbound network path into this machine\n' +
559
559
  'is never written to disk.\n' +
560
560
  '\nExamples:\n' +
561
561
  ' testsprite tunnel start # hold a tunnel open (Ctrl-C to stop)\n' +
562
- ' testsprite test run <id> --local 5173 --tunnel-client <id>\n' +
562
+ ' testsprite test run <id> --env <name> --tunnel-client <id>\n' +
563
563
  ' testsprite tunnel list\n' +
564
564
  ' testsprite tunnel status <id>\n' +
565
565
  ' testsprite tunnel stop <id>\n' +
@@ -574,7 +574,10 @@ export function createTunnelCommand(deps = {}) {
574
574
  'credential is deleted when the command exits regardless — the lifetime only matters if ' +
575
575
  'this process is killed without cleaning up.')
576
576
  .addHelpText('after', '\nPrints the client id to stderr as soon as it is minted, before connecting; pass it\n' +
577
- 'to `test run --local <port> --tunnel-client <id>`.\n' +
577
+ 'to `test run <id> --env <name> --tunnel-client <id>` for an environment on this machine.\n' +
578
+ 'Frontend runs normally open their own tunnel automatically for a loopback environment URL.\n' +
579
+ '\nDev servers can take a minute per page through the tunnel. For a heavy dev server,\n' +
580
+ "test a built server: `npm run build`, then your framework's preview/start command.\n" +
578
581
  '\nExit codes:\n' +
579
582
  ' 0 you stopped it (Ctrl-C is the normal way to end this command)\n' +
580
583
  ' 3 auth error — the key needs the `run:tunnel` scope; mint a new key\n' +
@@ -592,6 +595,7 @@ export function createTunnelCommand(deps = {}) {
592
595
  .command('list')
593
596
  .description('List live tunnel bindings for this account')
594
597
  .addHelpText('after', '\nShows each tunnel client id, connection status, creation time and expiry.\n' +
598
+ 'Includes tunnels automatically opened for environments on this machine.\n' +
595
599
  '\nExit codes:\n' +
596
600
  ' 0 listed (possibly empty)\n' +
597
601
  ' 3 auth error — the key needs the `run:tunnel` scope\n' +
@@ -606,6 +610,7 @@ export function createTunnelCommand(deps = {}) {
606
610
  .description('Report whether a tunnel client of yours is connected')
607
611
  .addHelpText('after', '\n`offline` means the API answered and said nothing is connected with that id. A failure\n' +
608
612
  'to reach TestSprite is reported as its own error, never as `offline`.\n' +
613
+ 'Use the client id printed by a run that automatically opened a tunnel.\n' +
609
614
  '\nExit codes:\n' +
610
615
  ' 0 answered (the answer may be `offline`)\n' +
611
616
  ' 4 no such tunnel for this account\n' +
@@ -621,6 +626,7 @@ export function createTunnelCommand(deps = {}) {
621
626
  .option('--confirm', 'required with --all for this destructive operation', false)
622
627
  .addHelpText('after', '\nStopping one that is already gone succeeds. Revoking the credential\n' +
623
628
  'also makes a running `tunnel start` exit within ~15 s.\n' +
629
+ 'A run that automatically opened this tunnel loses access to its environment when you stop it.\n' +
624
630
  'Stopping all requires --confirm; --dry-run previews sample ids without it.\n' +
625
631
  '\nExit codes:\n' +
626
632
  ' 0 stopped (or already absent), including an empty --all result\n' +
package/dist/index.js CHANGED
@@ -19,9 +19,10 @@ import { ApiError, CLIError, InterruptError, RequestTimeoutError, extractNodeErr
19
19
  import { armInterruptExitBackstop, installBrokenPipeGuard, installSignalHandlers, } from './lib/interrupt.js';
20
20
  import { Output, isOutputMode } from './lib/output.js';
21
21
  import { maybeInstallProxyAgent } from './lib/proxy.js';
22
- import { renderAmbiguousOrgCandidates, renderTunnelBindingLimitIds, renderCommanderError, rephraseUnknownOption, } from './lib/render-error.js';
22
+ import { redactDeep } from './lib/redact.js';
23
+ import { buildInterruptEnvelope, renderAmbiguousOrgCandidates, renderTunnelBindingLimitIds, renderCommanderError, rephraseUnknownOption, } from './lib/render-error.js';
23
24
  import { isPlanTemplateInvocation, maybeEmitSkillNudge } from './lib/skill-nudge.js';
24
- import { classifyCliError, isTelemetryOptedOut, recordOutcome, resolveTelemetryAuth, } from './lib/telemetry.js';
25
+ import { classifyCliError, isTelemetryOptedOut, recordOutcome, recordTelemetryExtras, resolveTelemetryAuth, } from './lib/telemetry.js';
25
26
  import { maybeNotifyUpdate } from './lib/update-check.js';
26
27
  import { VERSION } from './version.js';
27
28
  import { rejectUnsupportedNodeVersion } from './version-guard.js';
@@ -74,7 +75,11 @@ program.addCommand(createTestCommand({
74
75
  },
75
76
  }));
76
77
  program.addCommand(createTestListCommand());
77
- program.addCommand(createCiCommand({}));
78
+ program.addCommand(createCiCommand({
79
+ onWaitTimeout: context => {
80
+ waitTimeoutTelemetry = context;
81
+ },
82
+ }));
78
83
  program.addCommand(createScheduleCommand({}));
79
84
  program.addCommand(createTunnelCommand({}));
80
85
  program.addCommand(createAgentCommand({}));
@@ -119,12 +124,6 @@ let telemetryEmit = false;
119
124
  // Auth resolved in the preAction hook, before the command's action runs, so
120
125
  // `auth remove` (which deletes the profile) is still reported on the key it used.
121
126
  let telemetryAuth;
122
- // True when the leaf command that is about to run carries a `--local` option
123
- // value — `test run --local <port>` or `project create --local <port>`.
124
- // Set before validation so test-run refusals still report attempts that a
125
- // backend-side mint/attach event never observes. Local project admission
126
- // failures have a separate zero-HTTP exception below.
127
- let telemetryLocal = false;
128
127
  // Local project admission failures must exit without any TestSprite HTTP,
129
128
  // including telemetry. Track companion flags even when --local is missing.
130
129
  let telemetryLocalProject = false;
@@ -205,9 +204,10 @@ program.hook('preAction', (_thisCommand, actionCommand) => {
205
204
  const commandPath = commandPathOf(actionCommand);
206
205
  // Record which leaf command ran, for the telemetry emit around parseAsync.
207
206
  ranCommandPath = commandPath;
208
- // The raw --local opt is a port string; only its presence is
209
- // recorded (see `telemetryLocal`'s own comment — never the value).
210
- telemetryLocal = globals.local !== undefined;
207
+ // Preserve explicit --local attempts, including refusals and borrowed tunnels;
208
+ // only flag presence is recorded. Automatic tunnel paths record the same fact.
209
+ if (globals.local !== undefined)
210
+ recordTelemetryExtras({ local: true });
211
211
  telemetryLocalProject =
212
212
  commandPath === 'project create' &&
213
213
  (globals.local !== undefined || globals.localHost !== undefined);
@@ -277,7 +277,6 @@ try {
277
277
  exitCode: 0,
278
278
  durationMs: Date.now() - telemetryStartedAt,
279
279
  ...telemetryGlobals(),
280
- local: telemetryLocal,
281
280
  }, { resolvedAuth: telemetryAuth });
282
281
  }
283
282
  }
@@ -312,7 +311,6 @@ catch (err) {
312
311
  ...waitTimeoutTelemetry,
313
312
  durationMs: Date.now() - telemetryStartedAt,
314
313
  ...telemetryGlobals(),
315
- local: telemetryLocal,
316
314
  }, { resolvedAuth: telemetryAuth });
317
315
  }
318
316
  process.exitCode = code;
@@ -333,7 +331,10 @@ catch (err) {
333
331
  message,
334
332
  nextAction: err.nextAction,
335
333
  requestId: err.requestId,
336
- details: err.details,
334
+ // `err.details` is already redacted at ApiError construction (see
335
+ // `errors.ts`); redacting again here is defence in depth for this
336
+ // hand-built envelope specifically, independent of that.
337
+ details: redactDeep(err.details),
337
338
  ...(billingRefusal ? { links: billingRefusal.links } : {}),
338
339
  },
339
340
  };
@@ -391,29 +392,7 @@ catch (err) {
391
392
  // A disarmed request has no run ID, so its JSON hint describes checking
392
393
  // current state before retrying. Both use the conventional 128+signum code.
393
394
  if (mode === 'json') {
394
- const tunnelDetach = err
395
- .tunnelDetach;
396
- const envelope = {
397
- error: {
398
- code: 'INTERRUPTED',
399
- message: err.message,
400
- nextAction: tunnelDetach?.nextAction ??
401
- (err.runWaitContext
402
- ? 'The server-side run (if any) keeps executing and billing. ' +
403
- 'Re-attach with: testsprite test wait <runId>, or stop it with: testsprite test cancel <runId> ' +
404
- '(runId is in the partial JSON on stdout).'
405
- : 'The request was interrupted. Check the current state before retrying; ' +
406
- 'a multi-item command may have processed some items.'),
407
- requestId: 'local',
408
- details: {
409
- signal: err.signal,
410
- ...(tunnelDetach
411
- ? { runId: tunnelDetach.runId, cancelOutcome: tunnelDetach.cancel }
412
- : {}),
413
- },
414
- },
415
- };
416
- process.stderr.write(`${JSON.stringify(envelope, null, 2)}\n`);
395
+ process.stderr.write(`${JSON.stringify(buildInterruptEnvelope(err), null, 2)}\n`);
417
396
  }
418
397
  else {
419
398
  process.stderr.write(`Error: ${err.message}\n`);
@@ -65,7 +65,12 @@ export interface SkillSpec {
65
65
  * `testsprite-onboard` codex contribution — a single always-on line. Kept here
66
66
  * (not in a `*.codex.md` asset) because it is one line; see {@link CodexContribution}.
67
67
  */
68
- export declare const ONBOARD_CODEX_LINE = "**First-time setup:** if this repo has no TestSprite tests yet, seed a *broad* first suite across its main user flows \u2014 not just one test \u2014 each with a concrete, observable assertion, before reporting setup as done.";
68
+ export declare const ONBOARD_CODEX_LINE = "**First-time setup:** if this repo has no TestSprite tests yet, seed a *broad* first suite across its main user flows \u2014 not just one test \u2014 each with a concrete, observable assertion, before reporting setup as done. Try `testsprite test plan generate --project <id>` then `test plan accept` first; author plans by hand only if generation is unavailable.";
69
+ /**
70
+ * `testsprite-ci` codex contribution — one always-on line; the full onboarding
71
+ * flow lives in the own-file body and the docs.
72
+ */
73
+ export declare const CI_CODEX_LINE = "**CI gate:** to run TestSprite on every pull request, use `testsprite ci init github --project <id> --env <name>`, finish the `REPLACE ME` step for how PRs deploy (platform-deployed previews \u2192 `on: deployment_status`; the workflow deploys \u2192 keep `pull_request`), set the `TESTSPRITE_API_KEY` secret, then prove it on one real, non-draft pull request. If the GitHub App already gates the project, ask before adding a second gate.";
69
74
  /**
70
75
  * The skill registry. Each entry owns its name, description (drift-guarded by a
71
76
  * byte-identity unit test against a template doc), own-file body asset, and codex
@@ -77,9 +82,9 @@ export declare const SKILLS: Record<string, SkillSpec>;
77
82
  /**
78
83
  * Skills installed by `setup` and by `agent install` when no `--skill` subset is
79
84
  * given. Order is significant for the codex aggregate (verify first, then the
80
- * onboard line as a short addendum).
85
+ * onboard and ci lines as short addenda).
81
86
  */
82
- export declare const DEFAULT_SKILLS: readonly ["testsprite-verify", "testsprite-onboard"];
87
+ export declare const DEFAULT_SKILLS: readonly ["testsprite-verify", "testsprite-onboard", "testsprite-ci"];
83
88
  /** @deprecated The canonical skill name. New code: iterate {@link SKILLS}. */
84
89
  export declare const SKILL_NAME = "testsprite-verify";
85
90
  /**
@@ -5,7 +5,12 @@ import { VERSION } from '../version.js';
5
5
  * `testsprite-onboard` codex contribution — a single always-on line. Kept here
6
6
  * (not in a `*.codex.md` asset) because it is one line; see {@link CodexContribution}.
7
7
  */
8
- export const ONBOARD_CODEX_LINE = '**First-time setup:** if this repo has no TestSprite tests yet, seed a *broad* first suite across its main user flows — not just one test — each with a concrete, observable assertion, before reporting setup as done.';
8
+ export const ONBOARD_CODEX_LINE = '**First-time setup:** if this repo has no TestSprite tests yet, seed a *broad* first suite across its main user flows — not just one test — each with a concrete, observable assertion, before reporting setup as done. Try `testsprite test plan generate --project <id>` then `test plan accept` first; author plans by hand only if generation is unavailable.';
9
+ /**
10
+ * `testsprite-ci` codex contribution — one always-on line; the full onboarding
11
+ * flow lives in the own-file body and the docs.
12
+ */
13
+ export const CI_CODEX_LINE = '**CI gate:** to run TestSprite on every pull request, use `testsprite ci init github --project <id> --env <name>`, finish the `REPLACE ME` step for how PRs deploy (platform-deployed previews → `on: deployment_status`; the workflow deploys → keep `pull_request`), set the `TESTSPRITE_API_KEY` secret, then prove it on one real, non-draft pull request. If the GitHub App already gates the project, ask before adding a second gate.';
9
14
  /**
10
15
  * The skill registry. Each entry owns its name, description (drift-guarded by a
11
16
  * byte-identity unit test against a template doc), own-file body asset, and codex
@@ -22,17 +27,23 @@ export const SKILLS = {
22
27
  },
23
28
  'testsprite-onboard': {
24
29
  name: 'testsprite-onboard',
25
- description: 'Stand up a complete, runnable TestSprite test suite for the current repo at first use — create a project (with a target URL and auth), derive a coherent set of tests from the codebase, batch-create them, and smoke-run a few to a green verdict so the user immediately has something worth running. Use ONLY when a repo has no TestSprite tests yet (a fresh project), right after `testsprite setup`, or when the user asks to "set up / bootstrap / seed tests". This is first-run setup, NOT change verification — once a project already has tests, use the testsprite-verify skill instead.',
30
+ description: 'Stand up a complete, runnable TestSprite test suite for the current repo at first use — create a project (with a target URL and auth), generate a coherent set of tests (or derive and batch-create them from the codebase), and smoke-run a few to a green verdict so the user has something worth running. Use ONLY when a repo has no TestSprite tests yet (a fresh project), right after `testsprite setup`, or when the user asks to "set up / bootstrap / seed tests". This is first-run setup, NOT change verification — once a project already has tests, use the testsprite-verify skill instead.',
26
31
  bodyFile: 'testsprite-onboard.skill.md',
27
32
  codex: { kind: 'line', text: ONBOARD_CODEX_LINE },
28
33
  },
34
+ 'testsprite-ci': {
35
+ name: 'testsprite-ci',
36
+ description: 'Gate pull requests with TestSprite in CI — work out how the repo deploys pull-request previews (platform-deployed → `on: deployment_status`; deployed in the workflow → `on: pull_request`), pick the environment the gate signs in with, generate the workflow with `testsprite ci init github`, finish its placeholder step, set the `TESTSPRITE_API_KEY` secret, and prove the gate on one real pull request. Use when the user asks to add TestSprite to CI or GitHub Actions, run the tests on every PR, or block merges on them. NOT for seeding a first suite (testsprite-onboard) or checking one change (testsprite-verify).',
37
+ bodyFile: 'testsprite-ci.skill.md',
38
+ codex: { kind: 'line', text: CI_CODEX_LINE },
39
+ },
29
40
  };
30
41
  /**
31
42
  * Skills installed by `setup` and by `agent install` when no `--skill` subset is
32
43
  * given. Order is significant for the codex aggregate (verify first, then the
33
- * onboard line as a short addendum).
44
+ * onboard and ci lines as short addenda).
34
45
  */
35
- export const DEFAULT_SKILLS = ['testsprite-verify', 'testsprite-onboard'];
46
+ export const DEFAULT_SKILLS = ['testsprite-verify', 'testsprite-onboard', 'testsprite-ci'];
36
47
  // ---------------------------------------------------------------------------
37
48
  // Back-compat single-skill exports (= the canonical `testsprite-verify` skill)
38
49
  // ---------------------------------------------------------------------------
@@ -0,0 +1,11 @@
1
+ import type { CiSummary } from './gh-output.js';
2
+ import type { RunConflict } from './conflict-reason.js';
3
+ import { type WaitMemberResult } from './wait-exit.js';
4
+ /** CI owns non-dispatch policy; operational poll failures retain their typed exit. */
5
+ export declare function resolveCiRunFailure(summary: CiSummary, accepted: readonly WaitMemberResult[], opts: {
6
+ timeoutSeconds: number;
7
+ allowEmpty?: boolean;
8
+ failOnSkipped?: boolean;
9
+ },
10
+ /** The batch's `conflicts[]`, with their reasons, when the caller has them. */
11
+ conflicts?: readonly RunConflict[]): Error | null;
@@ -0,0 +1,34 @@
1
+ import { CLIError } from './errors.js';
2
+ import { resolveWaitFailure } from './wait-exit.js';
3
+ /** CI owns non-dispatch policy; operational poll failures retain their typed exit. */
4
+ export function resolveCiRunFailure(summary, accepted, opts,
5
+ /** The batch's `conflicts[]`, with their reasons, when the caller has them. */
6
+ conflicts = []) {
7
+ const missing = summary.runs.filter(row => row.status === 'not_found');
8
+ if (missing.length > 0) {
9
+ return new CLIError(`Tests not found: ${missing.map(row => row.testId).join(', ')}`, 4);
10
+ }
11
+ const failure = resolveWaitFailure(accepted, opts);
12
+ if (failure)
13
+ return failure;
14
+ if (accepted.length === 0) {
15
+ // `--allow-empty` covers an empty selection: no tests, a filter that
16
+ // matched nothing, or runs already in flight elsewhere. A batch the
17
+ // backend REFUSED — an unknown environment, an un-runnable one, a
18
+ // view-only mirror, a billing hold — is not empty, and reading it as
19
+ // green is the false-green shape a gate exists to prevent.
20
+ const refused = conflicts.filter(c => c.reason !== undefined && c.reason !== 'in_flight' && c.reason !== 'not_found');
21
+ if (refused.length > 0) {
22
+ const first = refused[0];
23
+ return new CLIError(`No tests were dispatched: ${refused.length} refused (${first.reason}${first.message ? `: ${first.message}` : ''}).`, 5);
24
+ }
25
+ if (!opts.allowEmpty) {
26
+ return new CLIError('No tests were dispatched. Pass --allow-empty to allow an empty CI run.', 5);
27
+ }
28
+ }
29
+ if (summary.skipped > 0 && opts.failOnSkipped) {
30
+ return new CLIError(`${summary.skipped} tests were skipped (--fail-on-skipped).`, 1);
31
+ }
32
+ return null;
33
+ }
34
+ //# sourceMappingURL=ci-run.js.map