@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,3 +1,4 @@
1
+ import type { ExecutionReport } from './runs.types.js';
1
2
  /**
2
3
  * CI-native output layer for the run path (issue #99, reshaped from
3
4
  * the withdrawn top-level `ci` command per the #264 review). Covers both a
@@ -42,6 +43,12 @@ export interface CiSummary {
42
43
  skipped: number;
43
44
  timedOut: number;
44
45
  runs: CiRunRow[];
46
+ /**
47
+ * The server's execution report (the GitHub App comment content) when the
48
+ * backend could provide one for this batch. Absent otherwise — never null —
49
+ * so a summary from an older backend is byte-identical to before.
50
+ */
51
+ executionReport?: ExecutionReport;
45
52
  }
46
53
  export declare function isNonDispatchedStatus(status: string): boolean;
47
54
  /**
@@ -55,12 +62,17 @@ export declare function isNonDispatchedStatus(status: string): boolean;
55
62
  * cannot read as "1/1 passed" with no annotation — but it counts as `skipped`,
56
63
  * never `failed`: whether non-dispatch fails the job is the exit-code
57
64
  * gates' call, and a `failed` count the gates disagree with is exactly the
58
- * artifacts-contradict-the-exit bug. (`skippedFrontend` / `skippedIntegration`
59
- * are NOT folded in — they exit 0 and are the Action layer's allow-partial
60
- * concern.)
65
+ * artifacts-contradict-the-exit bug.
66
+ *
67
+ * `skippedFrontend` / `skippedIntegration` are folded in only under
68
+ * `foldSkippedBuckets` (the `ci run` contract: ONE skipped number covering
69
+ * everything requested but not run). Default off — for `test run --all` they
70
+ * exit 0 and are the Action layer's allow-partial concern, and changing that
71
+ * default would silently change its artifacts.
61
72
  */
62
73
  export declare function summarizeAcceptedPayload(capturedJson: string, opts?: {
63
74
  notFoundNote?: string;
75
+ foldSkippedBuckets?: boolean;
64
76
  }): CiSummary;
65
77
  /**
66
78
  * Reduce a single `test run <test-id> --wait` result into the same CI summary
@@ -106,6 +118,11 @@ export declare function emitGithubOutputs(summary: CiSummary, env: NodeJS.Proces
106
118
  }, opts?: {
107
119
  force?: boolean;
108
120
  label?: string;
121
+ /**
122
+ * Pre-rendered job-summary Markdown (the execution report) that replaces
123
+ * the local results table when the backend provided one.
124
+ */
125
+ markdown?: string;
109
126
  }): void;
110
127
  /**
111
128
  * Emit the CI artifacts for a `--wait` run: the machine summary file (when
@@ -128,4 +145,45 @@ export declare function emitCiArtifacts(summary: CiSummary, opts: {
128
145
  env: NodeJS.ProcessEnv;
129
146
  stdout: (line: string) => void;
130
147
  stderr: (line: string) => void;
131
- }, label: string): void;
148
+ }, label: string, extra?: {
149
+ markdown?: string;
150
+ }): void;
151
+ /**
152
+ * Hand the execution report to later steps: its JSON and Markdown are written
153
+ * under `$RUNNER_TEMP` (else the OS temp dir) and their paths appended to
154
+ * `$GITHUB_OUTPUT` as `execution-report-file` / `execution-report-markdown-file`.
155
+ * Paths, not bodies — a step output is capped at 1 MiB and multi-line values
156
+ * need heredoc escaping. No-op without `GITHUB_OUTPUT` (nothing can consume
157
+ * them). Best-effort: a write failure is reported and never masks the gate.
158
+ */
159
+ export declare function emitExecutionReportOutputs(ready: {
160
+ report: ExecutionReport;
161
+ markdown: string;
162
+ }, io: {
163
+ env: NodeJS.ProcessEnv;
164
+ stderr: (line: string) => void;
165
+ }): {
166
+ jsonPath: string;
167
+ markdownPath: string;
168
+ } | undefined;
169
+ /**
170
+ * The job-summary Markdown for a batch that has a server execution report.
171
+ *
172
+ * The exit code comes from the CLI's own poll of every run plus whatever did
173
+ * not dispatch; the report describes only the execution. Usually they agree
174
+ * and the summary is the report, byte for byte the App's comment. When they
175
+ * do not — a run the CLI could not read or that timed out, a test refused
176
+ * before dispatch, a retry error — the report alone would read "all passed"
177
+ * under a red check, so the local verdict is stated first and the rows the
178
+ * report cannot contain are appended. A red run whose failures the report
179
+ * also shows agrees — the counts match — and keeps the App's comment as is.
180
+ */
181
+ export declare function reconcileExecutionReportMarkdown(summary: CiSummary, ready: {
182
+ report: ExecutionReport;
183
+ markdown: string;
184
+ }): string;
185
+ /** Numeric step outputs share the exact counters used by every other CI sink. */
186
+ export declare function emitCiStepOutputs(summary: CiSummary, io: {
187
+ env: NodeJS.ProcessEnv;
188
+ stderr: (line: string) => void;
189
+ }): void;
@@ -1,4 +1,6 @@
1
1
  import { appendFileSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
2
4
  import { describeConflict } from './conflict-reason.js';
3
5
  /**
4
6
  * Row statuses that mean "this test never ran" as opposed to "this run did not
@@ -48,9 +50,13 @@ function bucketRows(bucket, status, note) {
48
50
  * cannot read as "1/1 passed" with no annotation — but it counts as `skipped`,
49
51
  * never `failed`: whether non-dispatch fails the job is the exit-code
50
52
  * gates' call, and a `failed` count the gates disagree with is exactly the
51
- * artifacts-contradict-the-exit bug. (`skippedFrontend` / `skippedIntegration`
52
- * are NOT folded in — they exit 0 and are the Action layer's allow-partial
53
- * concern.)
53
+ * artifacts-contradict-the-exit bug.
54
+ *
55
+ * `skippedFrontend` / `skippedIntegration` are folded in only under
56
+ * `foldSkippedBuckets` (the `ci run` contract: ONE skipped number covering
57
+ * everything requested but not run). Default off — for `test run --all` they
58
+ * exit 0 and are the Action layer's allow-partial concern, and changing that
59
+ * default would silently change its artifacts.
54
60
  */
55
61
  export function summarizeAcceptedPayload(capturedJson, opts = {}) {
56
62
  let parsed;
@@ -82,20 +88,41 @@ export function summarizeAcceptedPayload(capturedJson, opts = {}) {
82
88
  };
83
89
  })
84
90
  : [];
91
+ const notFoundConflicts = new Set(Array.isArray(payload.conflicts)
92
+ ? payload.conflicts
93
+ .filter(c => c?.reason === 'not_found')
94
+ .map(c => String(c.testId))
95
+ : []);
85
96
  const rows = [
86
97
  ...acceptedRows,
98
+ ...bucketRows(payload.skipped, 'skipped', item => typeof item?.reason === 'string'
99
+ ? item.reason
100
+ : 'not dispatched'),
87
101
  ...bucketRows(payload.deferred, 'deferred', 'rate-deferred (not dispatched)'),
102
+ // One note per conflict, from its reason (HEAD); under `foldSkippedBuckets`
103
+ // a `not_found` conflict keeps its own status so the `ci run` gate can
104
+ // exit 4 for it instead of reading it as a transient conflict.
88
105
  ...bucketRows(payload.conflicts, 'conflict', item => {
89
106
  const conflict = item;
90
107
  return conflict && typeof conflict.testId === 'string' && conflict.reason
91
108
  ? `${describeConflict(conflict)} (not dispatched)`
92
109
  : 'already in flight (not dispatched)';
93
- }),
110
+ }).map(row => opts.foldSkippedBuckets === true && notFoundConflicts.has(row.testId)
111
+ ? { ...row, status: 'not_found' }
112
+ : row),
94
113
  // Default note is `test rerun`'s cause (a not-found id has no replayable
95
114
  // run). `testlist run` passes its own — a not-found `--case` id is one that
96
115
  // is not a member of the list — so the annotation/artifact don't state the
97
116
  // wrong reason on the surface this whole layer exists to serve.
98
117
  ...bucketRows(payload.notFound, 'not_found', opts.notFoundNote ?? 'no replayable run (not dispatched)'),
118
+ ...(opts.foldSkippedBuckets === true
119
+ ? [
120
+ // `bucketRows` handles both bucket shapes: `skippedFrontend` is bare
121
+ // testId strings, `skippedIntegration` is `{ testId }` objects.
122
+ ...bucketRows(payload.skippedFrontend, 'skipped', 'frontend test — not run by the batch engine'),
123
+ ...bucketRows(payload.skippedIntegration, 'skipped', 'assembled integration test — run it from the portal'),
124
+ ]
125
+ : []),
99
126
  ];
100
127
  const passed = rows.filter(row => row.status === 'passed').length;
101
128
  const timedOut = rows.filter(row => row.status === 'timeout').length;
@@ -235,7 +262,7 @@ export function emitGithubOutputs(summary, env, sinks, opts = {}) {
235
262
  const summaryPath = env.GITHUB_STEP_SUMMARY;
236
263
  if (typeof summaryPath === 'string' && summaryPath.length > 0) {
237
264
  try {
238
- sinks.appendFile(summaryPath, renderJobSummaryMarkdown(summary));
265
+ sinks.appendFile(summaryPath, opts.markdown ?? renderJobSummaryMarkdown(summary));
239
266
  }
240
267
  catch {
241
268
  sinks.stderr(`[${label}] could not append to GITHUB_STEP_SUMMARY; continuing`);
@@ -276,7 +303,7 @@ export function emitGithubOutputs(summary, env, sinks, opts = {}) {
276
303
  * command in the failure messages (`[run]` / `[rerun]` / `[testlist run]`).
277
304
  * Both writes are best-effort — a sink throwing must never change the exit code.
278
305
  */
279
- export function emitCiArtifacts(summary, opts, io, label) {
306
+ export function emitCiArtifacts(summary, opts, io, label, extra = {}) {
280
307
  const ghEnabled = opts.ghOutput === true || io.env.GITHUB_ACTIONS === 'true';
281
308
  if (!ghEnabled && opts.summaryFile === undefined)
282
309
  return;
@@ -298,7 +325,125 @@ export function emitCiArtifacts(summary, opts, io, label) {
298
325
  // Under --output json the run envelope owns stdout; workflow commands go
299
326
  // to stderr instead (the Actions runner parses both streams).
300
327
  annotations: opts.output === 'json' ? io.stderr : io.stdout,
301
- }, { force: opts.ghOutput === true, label });
328
+ }, { force: opts.ghOutput === true, label, markdown: extra.markdown });
329
+ }
330
+ }
331
+ /**
332
+ * Hand the execution report to later steps: its JSON and Markdown are written
333
+ * under `$RUNNER_TEMP` (else the OS temp dir) and their paths appended to
334
+ * `$GITHUB_OUTPUT` as `execution-report-file` / `execution-report-markdown-file`.
335
+ * Paths, not bodies — a step output is capped at 1 MiB and multi-line values
336
+ * need heredoc escaping. No-op without `GITHUB_OUTPUT` (nothing can consume
337
+ * them). Best-effort: a write failure is reported and never masks the gate.
338
+ */
339
+ export function emitExecutionReportOutputs(ready, io) {
340
+ const outputPath = io.env.GITHUB_OUTPUT;
341
+ if (!outputPath)
342
+ return undefined;
343
+ const dir = io.env.RUNNER_TEMP || tmpdir();
344
+ const safeId = ready.report.executionId.replace(/[^A-Za-z0-9_-]/g, '_');
345
+ const jsonPath = join(dir, `testsprite-execution-report-${safeId}.json`);
346
+ const markdownPath = join(dir, `testsprite-execution-report-${safeId}.md`);
347
+ // A `key=value` output line ends at a newline, so a path carrying one would
348
+ // smuggle a second output; such a path is skipped rather than escaped.
349
+ if (/[\r\n]/.test(jsonPath) || /[\r\n]/.test(markdownPath)) {
350
+ io.stderr('[ci run] execution report outputs skipped: the temp directory path contains a newline');
351
+ return undefined;
352
+ }
353
+ try {
354
+ // Owner-only: the report carries the run's narrative, error text, fix
355
+ // prompts and screenshot links, and the runner's temp dir is shared.
356
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- Runner temp directory (`$RUNNER_TEMP` or the OS temp dir) plus a sanitised execution id; never caller input.
357
+ writeFileSync(jsonPath, `${JSON.stringify(ready.report, null, 2)}\n`, {
358
+ encoding: 'utf8',
359
+ mode: 0o600,
360
+ });
361
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- Same runner temp directory and sanitised id as above.
362
+ writeFileSync(markdownPath, ready.markdown, { encoding: 'utf8', mode: 0o600 });
363
+ }
364
+ catch (err) {
365
+ io.stderr(`[ci run] execution report files not written (${err instanceof Error ? err.message : String(err)}); continuing`);
366
+ return undefined;
367
+ }
368
+ try {
369
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- GITHUB_OUTPUT is the runner-provided output path; only the two temp-file paths above are appended.
370
+ appendFileSync(outputPath, `execution-report-file=${jsonPath}\nexecution-report-markdown-file=${markdownPath}\n`, 'utf8');
371
+ }
372
+ catch {
373
+ io.stderr('[ci run] execution report outputs not appended to GITHUB_OUTPUT; continuing');
374
+ }
375
+ return { jsonPath, markdownPath };
376
+ }
377
+ /**
378
+ * The job-summary Markdown for a batch that has a server execution report.
379
+ *
380
+ * The exit code comes from the CLI's own poll of every run plus whatever did
381
+ * not dispatch; the report describes only the execution. Usually they agree
382
+ * and the summary is the report, byte for byte the App's comment. When they
383
+ * do not — a run the CLI could not read or that timed out, a test refused
384
+ * before dispatch, a retry error — the report alone would read "all passed"
385
+ * under a red check, so the local verdict is stated first and the rows the
386
+ * report cannot contain are appended. A red run whose failures the report
387
+ * also shows agrees — the counts match — and keeps the App's comment as is.
388
+ */
389
+ export function reconcileExecutionReportMarkdown(summary, ready) {
390
+ const localNonPassed = summary.runs.filter(row => row.status !== 'passed');
391
+ const { stats } = ready.report;
392
+ const agrees = summary.skipped === 0 &&
393
+ summary.timedOut === 0 &&
394
+ summary.passed === stats.passed &&
395
+ summary.failed === stats.failed + stats.blocked &&
396
+ summary.total === stats.total;
397
+ if (agrees)
398
+ return ready.markdown;
399
+ const reported = new Set(ready.report.tests.map(t => t.id));
400
+ const missing = localNonPassed.filter(row => !row.runId || !reported.has(row.runId));
401
+ const banner = [
402
+ '> [!WARNING]',
403
+ `> **CI gate: ${summary.passed} of ${summary.total} passed, ${summary.failed} failed, ${summary.skipped} skipped, ${summary.timedOut} timed out.**`,
404
+ "> The check's result comes from the CLI's own poll of each run. The report below is the server's view of execution " +
405
+ `\`${ready.report.executionId}\`` +
406
+ (missing.length > 0 ? ' and does not cover the rows listed at the end.' : '.'),
407
+ '',
408
+ ];
409
+ const appendix = missing.length > 0
410
+ ? [
411
+ '',
412
+ '### Not reflected in the execution report',
413
+ '',
414
+ '| Test | Status | Detail | Run |',
415
+ '| --- | --- | --- | --- |',
416
+ ...missing.map(row => {
417
+ const label = row.title?.trim() || row.testId;
418
+ const test = row.dashboardUrl
419
+ ? `[${escapeMarkdownLinkText(label)}](${escapeMarkdownUrl(row.dashboardUrl)})`
420
+ : escapeTableCell(label);
421
+ const runId = row.runId ?? '';
422
+ const run = row.executionUrl && runId
423
+ ? `[${escapeMarkdownLinkText(runId)}](${escapeMarkdownUrl(row.executionUrl)})`
424
+ : escapeTableCell(runId);
425
+ return `| ${test} | ${escapeTableCell(row.status)} | ${escapeTableCell(row.error ?? '')} | ${run} |`;
426
+ }),
427
+ '',
428
+ ]
429
+ : [];
430
+ return [...banner, ready.markdown.replace(/\s+$/, ''), ...appendix, ''].join('\n');
431
+ }
432
+ /** Numeric step outputs share the exact counters used by every other CI sink. */
433
+ export function emitCiStepOutputs(summary, io) {
434
+ const outputPath = io.env.GITHUB_OUTPUT;
435
+ if (!outputPath)
436
+ return;
437
+ const content = ['total', 'passed', 'failed', 'skipped', 'timedOut']
438
+ .map(key => `${key}=${summary[key]}\n`)
439
+ .join('');
440
+ try {
441
+ // Runner-provided output file; only numeric counter values are appended.
442
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- GITHUB_OUTPUT is an explicit runner/operator-provided output path, not API/test content; only computed numeric counters are appended.
443
+ appendFileSync(outputPath, content, 'utf8');
444
+ }
445
+ catch {
446
+ io.stderr('[ci run] could not append to GITHUB_OUTPUT; continuing');
302
447
  }
303
448
  }
304
449
  //# sourceMappingURL=gh-output.js.map
@@ -0,0 +1,21 @@
1
+ import type { FetchImpl } from './http.js';
2
+ import type { CiGithubTrigger } from './runs.types.js';
3
+ export type GithubRunContext = {
4
+ kind: 'pull_request';
5
+ trigger: CiGithubTrigger;
6
+ draft: boolean;
7
+ } | {
8
+ kind: 'no_pull_request';
9
+ event: string;
10
+ reason: string;
11
+ } | {
12
+ kind: 'outside_actions';
13
+ };
14
+ export interface GithubContextDeps {
15
+ /** Reads `$GITHUB_EVENT_PATH`; injectable so tests never touch the runner. */
16
+ readFile?: (path: string) => string;
17
+ fetchImpl?: FetchImpl;
18
+ }
19
+ /** The temporary environment a pull request's runs live in — shared with the GitHub App. */
20
+ export declare function previewEnvironmentName(prNumber: number): string;
21
+ export declare function readGithubRunContext(env: NodeJS.ProcessEnv, deps?: GithubContextDeps): Promise<GithubRunContext>;
@@ -0,0 +1,153 @@
1
+ /**
2
+ * What `ci run` can learn about the pull request it is gating, from the
3
+ * GitHub Actions runner alone — no secrets of ours, no flags in the yml.
4
+ *
5
+ * A `pull_request` event names the PR in its payload. A `deployment_status`
6
+ * event (the platform-deploys-every-PR shape) only names the commit, so the
7
+ * PR is looked up with the job's own `GITHUB_TOKEN` through the same call the
8
+ * GitHub App makes (`GET /repos/{owner}/{repo}/commits/{sha}/pulls`). A run
9
+ * that cannot be tied to a pull request is reported as such, never guessed:
10
+ * the caller decides whether that means "skip" or "run without a preview".
11
+ */
12
+ import { readFileSync } from 'node:fs';
13
+ import { CLIError, localValidationError } from './errors.js';
14
+ /** The temporary environment a pull request's runs live in — shared with the GitHub App. */
15
+ export function previewEnvironmentName(prNumber) {
16
+ return `github-pr-${prNumber}`;
17
+ }
18
+ const SHA_RE = /^[0-9a-f]{40}$/;
19
+ export async function readGithubRunContext(env, deps = {}) {
20
+ if (env.GITHUB_ACTIONS !== 'true')
21
+ return { kind: 'outside_actions' };
22
+ const event = env.GITHUB_EVENT_NAME ?? '';
23
+ const slug = env.GITHUB_REPOSITORY ?? '';
24
+ const [repoOwner, repoName, ...rest] = slug.split('/');
25
+ if (!repoOwner || !repoName || rest.length > 0) {
26
+ return { kind: 'no_pull_request', event, reason: 'GITHUB_REPOSITORY is not owner/name' };
27
+ }
28
+ const payload = readEvent(env, deps);
29
+ if (event === 'pull_request' || event === 'pull_request_target') {
30
+ const pr = asRecord(payload.pull_request);
31
+ const prNumber = pr?.number;
32
+ if (typeof prNumber !== 'number' || !Number.isInteger(prNumber) || prNumber < 1) {
33
+ throw localValidationError('github-event-path', `the ${event} event at $GITHUB_EVENT_PATH carries no pull_request.number`, undefined, 'field');
34
+ }
35
+ const head = asRecord(pr?.head);
36
+ return {
37
+ kind: 'pull_request',
38
+ draft: pr?.draft === true,
39
+ trigger: {
40
+ repoOwner,
41
+ repoName,
42
+ prNumber,
43
+ ...(typeof head?.ref === 'string' && head.ref !== '' ? { branchName: head.ref } : {}),
44
+ ...(typeof head?.sha === 'string' && SHA_RE.test(head.sha) ? { commitSha: head.sha } : {}),
45
+ },
46
+ };
47
+ }
48
+ if (event === 'deployment_status') {
49
+ const deployment = asRecord(payload.deployment);
50
+ const sha = typeof deployment?.sha === 'string' ? deployment.sha : '';
51
+ if (!SHA_RE.test(sha)) {
52
+ return { kind: 'no_pull_request', event, reason: 'the deployment names no commit' };
53
+ }
54
+ const token = env.GITHUB_TOKEN;
55
+ if (!token) {
56
+ throw localValidationError('GITHUB_TOKEN', 'a deployment_status event names only a commit; ci run looks up its pull request with the job token — add `GITHUB_TOKEN: ${{ github.token }}` to the step env', undefined, 'field');
57
+ }
58
+ const pulls = await listPullsForCommit({ env, repoOwner, repoName, sha, token }, deps.fetchImpl ?? globalThis.fetch);
59
+ // The PR whose head IS this commit is the one this deployment belongs to.
60
+ // Anything looser (several open PRs, a merged one) is not a gate target.
61
+ const exact = pulls.filter(p => p.headSha === sha);
62
+ const open = pulls.filter(p => p.state === 'open');
63
+ const chosen = exact[0] ?? (open.length === 1 ? open[0] : undefined);
64
+ if (!chosen) {
65
+ return {
66
+ kind: 'no_pull_request',
67
+ event,
68
+ reason: pulls.length === 0
69
+ ? `commit ${sha.slice(0, 7)} belongs to no pull request`
70
+ : `commit ${sha.slice(0, 7)} is not the head of an open pull request`,
71
+ };
72
+ }
73
+ const branch = typeof deployment?.ref === 'string' ? deployment.ref : chosen.headRef;
74
+ return {
75
+ kind: 'pull_request',
76
+ draft: chosen.draft,
77
+ trigger: {
78
+ repoOwner,
79
+ repoName,
80
+ prNumber: chosen.number,
81
+ commitSha: sha,
82
+ ...(branch ? { branchName: branch } : {}),
83
+ },
84
+ };
85
+ }
86
+ return {
87
+ kind: 'no_pull_request',
88
+ event,
89
+ reason: `a ${event || 'non-PR'} event has no pull request`,
90
+ };
91
+ }
92
+ function readEvent(env, deps) {
93
+ const path = env.GITHUB_EVENT_PATH;
94
+ if (!path)
95
+ return {};
96
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- `path` is the runner-provided `$GITHUB_EVENT_PATH` env path (read-only), never API/test content.
97
+ const read = deps.readFile ?? (p => readFileSync(p, 'utf8'));
98
+ try {
99
+ const parsed = JSON.parse(read(path));
100
+ return asRecord(parsed) ?? {};
101
+ }
102
+ catch (err) {
103
+ throw localValidationError('github-event-path', `cannot read the GitHub event at $GITHUB_EVENT_PATH: ${err instanceof Error ? err.message : String(err)}`, undefined, 'field');
104
+ }
105
+ }
106
+ async function listPullsForCommit(args, fetchImpl) {
107
+ const base = (args.env.GITHUB_API_URL ?? 'https://api.github.com').replace(/\/+$/, '');
108
+ const url = `${base}/repos/${encodeURIComponent(args.repoOwner)}/${encodeURIComponent(args.repoName)}/commits/${args.sha}/pulls`;
109
+ let response;
110
+ try {
111
+ response = await fetchImpl(url, {
112
+ method: 'GET',
113
+ headers: {
114
+ accept: 'application/vnd.github+json',
115
+ authorization: `Bearer ${args.token}`,
116
+ 'x-github-api-version': '2022-11-28',
117
+ },
118
+ });
119
+ }
120
+ catch (err) {
121
+ throw new CLIError(`Could not look up the pull request for commit ${args.sha.slice(0, 7)}: ${err instanceof Error ? err.message : String(err)}`, 10);
122
+ }
123
+ if (!response.ok) {
124
+ throw new CLIError(`Could not look up the pull request for commit ${args.sha.slice(0, 7)}: GitHub answered ${response.status}` +
125
+ (response.status === 403 || response.status === 401
126
+ ? ' — the job token needs `pull-requests: read`'
127
+ : ''), response.status === 401 || response.status === 403 ? 5 : 10);
128
+ }
129
+ const body = await response.json();
130
+ if (!Array.isArray(body))
131
+ return [];
132
+ return body.flatMap((item) => {
133
+ const pr = asRecord(item);
134
+ const head = asRecord(pr?.head);
135
+ if (typeof pr?.number !== 'number' || typeof head?.sha !== 'string')
136
+ return [];
137
+ return [
138
+ {
139
+ number: pr.number,
140
+ state: typeof pr.state === 'string' ? pr.state : '',
141
+ draft: pr.draft === true,
142
+ headSha: head.sha,
143
+ ...(typeof head.ref === 'string' ? { headRef: head.ref } : {}),
144
+ },
145
+ ];
146
+ });
147
+ }
148
+ function asRecord(value) {
149
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
150
+ ? value
151
+ : undefined;
152
+ }
153
+ //# sourceMappingURL=github-context.js.map
@@ -2,7 +2,7 @@ import * as v from 'valibot';
2
2
  import type { ErrorCode } from './errors.js';
3
3
  import { ApiError } from './errors.js';
4
4
  import type { CliTestListRunResponse } from './testlist.types.js';
5
- import type { TriggerRunBody, TriggerRunResponse, RunResponse, RerunRequest, RerunResponse, BatchRerunRequest, BatchRerunResponse, BatchRunFreshRequest, BatchRunFreshResponse, ListRunsQuery, ListRunsResponse, CancelRunResponse } from './runs.types.js';
5
+ import type { TriggerRunBody, TriggerRunResponse, RunResponse, RerunRequest, RerunResponse, BatchRerunRequest, BatchRerunResponse, BatchRunFreshRequest, BatchRunFreshResponse, ListRunsQuery, ListRunsResponse, CancelRunResponse, ExecutionReportResponse } from './runs.types.js';
6
6
  import type { CliAcceptPlansResponse, CliGeneratePlansResponse, CliGetPlansResponse } from './plans.types.js';
7
7
  import type { MintTunnelBody, TunnelListResponse, TunnelMintResponse, TunnelStatusResponse } from './tunnel.types.js';
8
8
  import type { ShutdownHandle } from './interrupt.js';
@@ -325,6 +325,8 @@ export declare class HttpClient {
325
325
  */
326
326
  triggerTestListRun(listId: string, body: {
327
327
  testIds?: string[];
328
+ tunnelClientId?: string;
329
+ targetUrl?: string;
328
330
  }, options: {
329
331
  idempotencyKey: string;
330
332
  signal?: AbortSignal;
@@ -396,6 +398,15 @@ export declare class HttpClient {
396
398
  signal?: AbortSignal;
397
399
  retry?: boolean;
398
400
  }): Promise<TunnelStatusResponse>;
401
+ /**
402
+ * The execution report — the GitHub App's PR-comment content — for one
403
+ * execution. `ready: false` asks the caller to poll again; the server keeps
404
+ * building the report meanwhile.
405
+ */
406
+ getExecutionReport(executionId: string, options?: {
407
+ signal?: AbortSignal;
408
+ retry?: boolean;
409
+ }): Promise<ExecutionReportResponse>;
399
410
  /**
400
411
  * DELETE /api/cli/v1/tunnel/{clientId} — destroy a binding. 204, idempotent.
401
412
  *
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 { 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';
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, EXECUTION_REPORT_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
@@ -376,6 +376,14 @@ export class HttpClient {
376
376
  schema: TUNNEL_STATUS_RESPONSE_SCHEMA,
377
377
  });
378
378
  }
379
+ /**
380
+ * The execution report — the GitHub App's PR-comment content — for one
381
+ * execution. `ready: false` asks the caller to poll again; the server keeps
382
+ * building the report meanwhile.
383
+ */
384
+ async getExecutionReport(executionId, options = {}) {
385
+ return this.get(`/tests/executions/${encodeURIComponent(executionId)}/report`, { signal: options.signal, retry: options.retry, schema: EXECUTION_REPORT_RESPONSE_SCHEMA });
386
+ }
379
387
  /**
380
388
  * DELETE /api/cli/v1/tunnel/{clientId} — destroy a binding. 204, idempotent.
381
389
  *
@@ -22,16 +22,17 @@ export interface JUnitTestResult {
22
22
  name?: string;
23
23
  /**
24
24
  * Wall-clock duration of the run in seconds, for `testcase time`. Derived from
25
- * the poll result's `startedAt`/`finishedAt`; omitted when timing is absent
25
+ * the poll result's `startedAt` (or `createdAt`) and `finishedAt`; omitted when timing is absent
26
26
  * (rendered as `0`, the pre-fix behaviour).
27
27
  */
28
28
  durationSeconds?: number;
29
29
  }
30
30
  /**
31
31
  * Duration in seconds between two ISO timestamps, or `undefined` when either is
32
- * missing / unparseable / negative (clock skew). Kept ≥ 0.
32
+ * missing / unparseable / negative (clock skew). Prefer startedAt, falling back
33
+ * to createdAt on servers that do not record a start. Kept ≥ 0.
33
34
  */
34
- export declare function durationSecondsBetween(startedAt: string | null | undefined, finishedAt: string | null | undefined): number | undefined;
35
+ export declare function durationSecondsBetween(startedAt: string | null | undefined, finishedAt: string | null | undefined, createdAt?: string | null): number | undefined;
35
36
  export interface JUnitReportBuildOptions {
36
37
  suiteName: string;
37
38
  classname: string;
@@ -75,11 +76,14 @@ export declare function escapeXml(text: string): string;
75
76
  export declare function buildJUnitReport(opts: JUnitReportBuildOptions): string;
76
77
  /**
77
78
  * 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.
79
+ * skipped JUnit results. Accepted rows carry run statuses and today never
80
+ * match `isNonDispatchedStatus`, but the two vocabularies are only disjoint
81
+ * by convention: `skipped` is a word both could use. So a member already in
82
+ * `dispatched` (the polled results the caller is writing) is left out here
83
+ * rather than trusted to stay apart, which keeps `tests` from counting one
84
+ * member twice if the server ever reports such a status for an admitted run.
81
85
  */
82
- export declare function skippedJUnitResultsFromSummary(summary: CiSummary): JUnitTestResult[];
86
+ export declare function skippedJUnitResultsFromSummary(summary: CiSummary, dispatched?: ReadonlyArray<Pick<JUnitTestResult, 'testId'>>): JUnitTestResult[];
83
87
  /**
84
88
  * Atomically write JUnit XML to `--report-file` (temp sibling + rename).
85
89
  */
@@ -6,9 +6,11 @@ import { localValidationError, TransportError } from './errors.js';
6
6
  import { isNonDispatchedStatus } from './gh-output.js';
7
7
  /**
8
8
  * Duration in seconds between two ISO timestamps, or `undefined` when either is
9
- * missing / unparseable / negative (clock skew). Kept ≥ 0.
9
+ * missing / unparseable / negative (clock skew). Prefer startedAt, falling back
10
+ * to createdAt on servers that do not record a start. Kept ≥ 0.
10
11
  */
11
- export function durationSecondsBetween(startedAt, finishedAt) {
12
+ export function durationSecondsBetween(startedAt, finishedAt, createdAt) {
13
+ startedAt = startedAt ?? createdAt;
12
14
  if (!startedAt || !finishedAt)
13
15
  return undefined;
14
16
  const start = Date.parse(startedAt);
@@ -179,13 +181,17 @@ export function buildJUnitReport(opts) {
179
181
  }
180
182
  /**
181
183
  * The summary's non-dispatched rows (deferred / conflict / not-found) as
182
- * skipped JUnit results. Accepted rows carry run statuses and never match
183
- * `isNonDispatchedStatus`, so the filter alone separates the two without
184
- * relying on row order.
184
+ * skipped JUnit results. Accepted rows carry run statuses and today never
185
+ * match `isNonDispatchedStatus`, but the two vocabularies are only disjoint
186
+ * by convention: `skipped` is a word both could use. So a member already in
187
+ * `dispatched` (the polled results the caller is writing) is left out here
188
+ * rather than trusted to stay apart, which keeps `tests` from counting one
189
+ * member twice if the server ever reports such a status for an admitted run.
185
190
  */
186
- export function skippedJUnitResultsFromSummary(summary) {
191
+ export function skippedJUnitResultsFromSummary(summary, dispatched = []) {
192
+ const alreadyIncluded = new Set(dispatched.map(row => row.testId));
187
193
  return summary.runs
188
- .filter(row => isNonDispatchedStatus(row.status))
194
+ .filter(row => isNonDispatchedStatus(row.status) && !alreadyIncluded.has(row.testId))
189
195
  .map(row => ({ testId: row.testId, status: 'skipped', skipReason: row.error ?? row.status }));
190
196
  }
191
197
  async function assertReportFileParent(rawPath) {