@fixsense/cypress-plugin 0.1.0 → 0.2.1

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.
package/README.md CHANGED
@@ -32,8 +32,39 @@ export default defineConfig({
32
32
  });
33
33
  ```
34
34
 
35
- Set `FIXSENSE_API_KEY` in CI. Without it the plugin does nothing, so local
36
- runs are unaffected.
35
+ That is the whole setup. No account, no key.
36
+
37
+ ## What you get, with no account
38
+
39
+ After each run the plugin appends what every test did to
40
+ `.fixsense/history.json` in your project, and once it has seen enough runs it
41
+ says what the history found:
42
+
43
+ ```
44
+ FixSense: 2 tests behave flakily across the last 12 runs
45
+ checkout › pays with a card — failed or retried in 4 of 12 runs
46
+ login › remembers the session — failed or retried in 3 of 12 runs
47
+ ```
48
+
49
+ A test that fails *every* run is reported separately, as a bug rather than
50
+ flakiness — quarantining that one is how a real failure reaches production.
51
+
52
+ Nothing is printed until there are at least five runs and something is
53
+ actually wrong, so a green suite stays quiet.
54
+
55
+ On GitHub Actions the same table is written to the job summary, so it appears
56
+ on the run's own page instead of scrolling past in the log.
57
+
58
+ `.fixsense/` is git-ignored for you: committing it would mean a diff on every
59
+ run and merge conflicts in a file nobody reads.
60
+
61
+ ### Why an account, then
62
+
63
+ The local history lives on one machine and dies with the CI container. The
64
+ hosted service keeps it across machines, branches and runs, says whether the
65
+ test or the application is at fault, and opens the fix as a pull request. Set
66
+ `FIXSENSE_API_KEY` in CI and the same runs are recorded there too; without it
67
+ nothing leaves your machine.
37
68
 
38
69
  ## Options
39
70
 
@@ -44,13 +75,15 @@ registerFixSense(on, {
44
75
  enabled: true,
45
76
  timeoutMs: 10000,
46
77
  repoFullName: 'acme/web', // when CI variables are absent
78
+ local: true, // keep .fixsense/history.json
79
+ cwd: process.cwd(), // where that history lives
47
80
  });
48
81
  ```
49
82
 
50
83
  GitHub Actions, GitLab CI, Bitbucket Pipelines and Azure Pipelines are
51
84
  detected automatically.
52
85
 
53
- ## What it sends
86
+ ## What it sends to FixSense (only with a key)
54
87
 
55
88
  Per test: the describe/it title chain, the spec file, the outcome, the retry
56
89
  count, the duration, and the error message truncated to 2000 characters.
package/dist/index.d.ts CHANGED
@@ -18,6 +18,15 @@ export interface FixSenseCypressOptions {
18
18
  timeoutMs?: number;
19
19
  /** Override repo detection when CI variables are absent or wrong. */
20
20
  repoFullName?: string;
21
+ /**
22
+ * Set false to stop keeping the local run history in `.fixsense/`.
23
+ *
24
+ * The history is what makes the plugin useful without an account, so it is
25
+ * on by default; uploading to FixSense remains opt-in via the API key.
26
+ */
27
+ local?: boolean;
28
+ /** Where the local history lives. Defaults to the process's directory. */
29
+ cwd?: string;
21
30
  }
22
31
  /** The subset of Cypress's plugin event registrar we use. */
23
32
  type On = (event: string, handler: (...args: never[]) => void | Promise<void>) => void;
@@ -31,3 +40,4 @@ export declare function registerFixSense(on: On, options?: FixSenseCypressOption
31
40
  export declare function sendRun(tests: TestRecord[], startedAt: Date, options: FixSenseCypressOptions): Promise<void>;
32
41
  export default registerFixSense;
33
42
  export * from "./payload";
43
+ export { computeFlakiness, readHistory, recordAndReport, renderMarkdown, renderSummary, scoreHistory, HISTORY_DIR, HISTORY_FILE, MAX_RUNS, } from "./local";
package/dist/index.js CHANGED
@@ -23,9 +23,11 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
23
23
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.MAX_RUNS = exports.HISTORY_FILE = exports.HISTORY_DIR = exports.scoreHistory = exports.renderSummary = exports.renderMarkdown = exports.recordAndReport = exports.readHistory = exports.computeFlakiness = void 0;
26
27
  exports.registerFixSense = registerFixSense;
27
28
  exports.sendRun = sendRun;
28
29
  const payload_1 = require("./payload");
30
+ const local_1 = require("./local");
29
31
  const DEFAULT_API_URL = "https://fix-sense.com";
30
32
  const DEFAULT_TIMEOUT_MS = 10_000;
31
33
  /**
@@ -54,13 +56,24 @@ function registerFixSense(on, options = {}) {
54
56
  async function sendRun(tests, startedAt, options) {
55
57
  if (options.enabled === false)
56
58
  return;
59
+ if (tests.length === 0)
60
+ return;
61
+ // The local history first, because it needs no account and is the only
62
+ // part most first-time users will ever see.
63
+ if (options.local !== false) {
64
+ try {
65
+ (0, local_1.recordAndReport)(options.cwd ?? process.cwd(), tests);
66
+ }
67
+ catch (error) {
68
+ const reason = error instanceof Error ? error.message : String(error);
69
+ console.error(`[fixsense] Local history not updated: ${reason}`);
70
+ }
71
+ }
57
72
  const apiKey = options.apiKey ?? process.env.FIXSENSE_API_KEY;
58
73
  // Silent without a key: a developer running Cypress locally has none and
59
74
  // does not need telling on every run.
60
75
  if (!apiKey)
61
76
  return;
62
- if (tests.length === 0)
63
- return;
64
77
  const context = (0, payload_1.detectContext)(process.env);
65
78
  const payload = {
66
79
  schemaVersion: 1,
@@ -98,3 +111,15 @@ async function sendRun(tests, startedAt, options) {
98
111
  }
99
112
  exports.default = registerFixSense;
100
113
  __exportStar(require("./payload"), exports);
114
+ // Named rather than a star: both modules describe an outcome, and one
115
+ // ambiguous export is worse than nine explicit ones.
116
+ var local_2 = require("./local");
117
+ Object.defineProperty(exports, "computeFlakiness", { enumerable: true, get: function () { return local_2.computeFlakiness; } });
118
+ Object.defineProperty(exports, "readHistory", { enumerable: true, get: function () { return local_2.readHistory; } });
119
+ Object.defineProperty(exports, "recordAndReport", { enumerable: true, get: function () { return local_2.recordAndReport; } });
120
+ Object.defineProperty(exports, "renderMarkdown", { enumerable: true, get: function () { return local_2.renderMarkdown; } });
121
+ Object.defineProperty(exports, "renderSummary", { enumerable: true, get: function () { return local_2.renderSummary; } });
122
+ Object.defineProperty(exports, "scoreHistory", { enumerable: true, get: function () { return local_2.scoreHistory; } });
123
+ Object.defineProperty(exports, "HISTORY_DIR", { enumerable: true, get: function () { return local_2.HISTORY_DIR; } });
124
+ Object.defineProperty(exports, "HISTORY_FILE", { enumerable: true, get: function () { return local_2.HISTORY_FILE; } });
125
+ Object.defineProperty(exports, "MAX_RUNS", { enumerable: true, get: function () { return local_2.MAX_RUNS; } });
@@ -0,0 +1,124 @@
1
+ /**
2
+ * The local run history: what the package does for someone with no account.
3
+ *
4
+ * A test runner is stateless between runs, so "this test has failed three
5
+ * times this week" is a sentence neither Playwright nor Cypress can say. That
6
+ * does not require a server — only a file. This module keeps one in the
7
+ * project being tested, scores it, and prints what it found.
8
+ *
9
+ * The hosted product is what this cannot be: history that survives the CI
10
+ * container, is shared across machines and branches, says whether the test or
11
+ * the application is at fault, and opens the fix. Local mode makes the
12
+ * problem visible; the account solves it.
13
+ *
14
+ * This file is byte-identical in @fixsense/playwright-reporter and
15
+ * @fixsense/cypress-plugin — each package installs standalone with no FixSense
16
+ * dependency, which is the whole reason a team adds one. The parity test
17
+ * asserts the two copies are the same file, so they cannot drift.
18
+ */
19
+ export type Outcome = "expected" | "unexpected" | "flaky" | "skipped";
20
+ export interface StoredTest {
21
+ title: string;
22
+ file: string | null;
23
+ outcome: Outcome;
24
+ }
25
+ export interface StoredRun {
26
+ at: string;
27
+ tests: StoredTest[];
28
+ }
29
+ export interface LocalHistory {
30
+ version: 1;
31
+ runs: StoredRun[];
32
+ }
33
+ export declare const HISTORY_DIR = ".fixsense";
34
+ export declare const HISTORY_FILE = "history.json";
35
+ /**
36
+ * How many runs are kept.
37
+ *
38
+ * Enough that a weekly pattern is visible, few enough that the file stays
39
+ * small in a repository someone did not ask to carry a database.
40
+ */
41
+ export declare const MAX_RUNS = 50;
42
+ /** Below this, any verdict is guesswork — the same floor the service uses. */
43
+ export declare const MIN_RUNS_FOR_VERDICT = 5;
44
+ /** At or above this score a test is called flaky. */
45
+ export declare const FLAKY_SCORE_THRESHOLD = 70;
46
+ /** Runs the runner itself called flaky before that alone is a verdict. */
47
+ export declare const MIN_FLAKY_RUNS = 2;
48
+ /** And how often, so a long-settled test is not judged on old history. */
49
+ export declare const MIN_FLAKY_RATE = 0.2;
50
+ export type Verdict = "stable" | "broken" | "flaky" | "suspect";
51
+ export interface FlakinessReport {
52
+ score: number;
53
+ verdict: Verdict;
54
+ runs: number;
55
+ failureRate: number;
56
+ selfReportedFlakyRate: number;
57
+ transitionRate: number;
58
+ }
59
+ export declare function countTransitions(outcomes: Array<"pass" | "fail">): number;
60
+ /**
61
+ * The same scoring the hosted service applies, so a team sees one answer
62
+ * whether they read it here or in the dashboard.
63
+ */
64
+ export declare function computeFlakiness(history: Array<{
65
+ outcome: Outcome;
66
+ }>): FlakinessReport;
67
+ export declare function historyPath(cwd: string): string;
68
+ /**
69
+ * A history file that cannot be read is treated as no history.
70
+ *
71
+ * It is a cache of past runs, not data anyone would mourn, and refusing to
72
+ * run because of it would break the first rule: never fail someone's build.
73
+ */
74
+ export declare function readHistory(cwd: string): LocalHistory;
75
+ export declare function appendRun(history: LocalHistory, run: StoredRun): LocalHistory;
76
+ /**
77
+ * Keep the directory out of git.
78
+ *
79
+ * Committing it would mean every developer's every run produces a diff, and
80
+ * a merge conflict in a file nobody reads. Only written when absent, so a
81
+ * team that decides otherwise is not overruled on the next run.
82
+ */
83
+ export declare function ensureIgnored(cwd: string): void;
84
+ export declare function writeHistory(cwd: string, history: LocalHistory): void;
85
+ export interface TestVerdict extends FlakinessReport {
86
+ title: string;
87
+ file: string | null;
88
+ /** How many of the stored runs this test failed or needed a retry in. */
89
+ badRuns: number;
90
+ }
91
+ /** Group the stored runs by test and score each one. */
92
+ export declare function scoreHistory(history: LocalHistory): TestVerdict[];
93
+ /**
94
+ * The summary a reader sees, or nothing at all.
95
+ *
96
+ * A line printed after every green run is a line teams learn to scroll past,
97
+ * so this stays empty unless the history actually found something. "suspect"
98
+ * is deliberately not reported: it means the tool is not sure yet.
99
+ */
100
+ export declare function renderSummary(verdicts: TestVerdict[], totalRuns: number): string;
101
+ /** The same summary as GitHub-flavoured Markdown, for the run's own page. */
102
+ export declare function renderMarkdown(verdicts: TestVerdict[], totalRuns: number): string;
103
+ /**
104
+ * Write the Markdown where GitHub Actions renders it on the run's page.
105
+ *
106
+ * In the job log the summary scrolls away under the test output; on the run
107
+ * page it is the first thing a reviewer sees.
108
+ */
109
+ export declare function writeStepSummary(markdown: string): void;
110
+ /**
111
+ * One entry per test per run, whatever the runner reported.
112
+ *
113
+ * A run that listed the same test twice would count as two runs for it, and
114
+ * a retried test would read as several times as flaky as it is. The last
115
+ * entry wins: for a runner that reports each attempt, it is the one that
116
+ * knows how the test finally ended.
117
+ */
118
+ export declare function dedupe(tests: StoredTest[]): StoredTest[];
119
+ /**
120
+ * Record this run and report what the history now says.
121
+ *
122
+ * Returns the text that was printed, which is what the tests assert on.
123
+ */
124
+ export declare function recordAndReport(cwd: string, tests: StoredTest[], now?: Date): string;
package/dist/local.js ADDED
@@ -0,0 +1,309 @@
1
+ "use strict";
2
+ /**
3
+ * The local run history: what the package does for someone with no account.
4
+ *
5
+ * A test runner is stateless between runs, so "this test has failed three
6
+ * times this week" is a sentence neither Playwright nor Cypress can say. That
7
+ * does not require a server — only a file. This module keeps one in the
8
+ * project being tested, scores it, and prints what it found.
9
+ *
10
+ * The hosted product is what this cannot be: history that survives the CI
11
+ * container, is shared across machines and branches, says whether the test or
12
+ * the application is at fault, and opens the fix. Local mode makes the
13
+ * problem visible; the account solves it.
14
+ *
15
+ * This file is byte-identical in @fixsense/playwright-reporter and
16
+ * @fixsense/cypress-plugin — each package installs standalone with no FixSense
17
+ * dependency, which is the whole reason a team adds one. The parity test
18
+ * asserts the two copies are the same file, so they cannot drift.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.MIN_FLAKY_RATE = exports.MIN_FLAKY_RUNS = exports.FLAKY_SCORE_THRESHOLD = exports.MIN_RUNS_FOR_VERDICT = exports.MAX_RUNS = exports.HISTORY_FILE = exports.HISTORY_DIR = void 0;
22
+ exports.countTransitions = countTransitions;
23
+ exports.computeFlakiness = computeFlakiness;
24
+ exports.historyPath = historyPath;
25
+ exports.readHistory = readHistory;
26
+ exports.appendRun = appendRun;
27
+ exports.ensureIgnored = ensureIgnored;
28
+ exports.writeHistory = writeHistory;
29
+ exports.scoreHistory = scoreHistory;
30
+ exports.renderSummary = renderSummary;
31
+ exports.renderMarkdown = renderMarkdown;
32
+ exports.writeStepSummary = writeStepSummary;
33
+ exports.dedupe = dedupe;
34
+ exports.recordAndReport = recordAndReport;
35
+ const fs_1 = require("fs");
36
+ const path_1 = require("path");
37
+ exports.HISTORY_DIR = ".fixsense";
38
+ exports.HISTORY_FILE = "history.json";
39
+ /**
40
+ * How many runs are kept.
41
+ *
42
+ * Enough that a weekly pattern is visible, few enough that the file stays
43
+ * small in a repository someone did not ask to carry a database.
44
+ */
45
+ exports.MAX_RUNS = 50;
46
+ /** Below this, any verdict is guesswork — the same floor the service uses. */
47
+ exports.MIN_RUNS_FOR_VERDICT = 5;
48
+ /** At or above this score a test is called flaky. */
49
+ exports.FLAKY_SCORE_THRESHOLD = 70;
50
+ /** Runs the runner itself called flaky before that alone is a verdict. */
51
+ exports.MIN_FLAKY_RUNS = 2;
52
+ /** And how often, so a long-settled test is not judged on old history. */
53
+ exports.MIN_FLAKY_RATE = 0.2;
54
+ function toPassFail(outcome) {
55
+ if (outcome === "skipped")
56
+ return null;
57
+ // A run the runner called flaky ended green, but it is not a pass: it
58
+ // needed a retry to get there, which is the behaviour being measured.
59
+ if (outcome === "flaky")
60
+ return "fail";
61
+ return outcome === "expected" ? "pass" : "fail";
62
+ }
63
+ function countTransitions(outcomes) {
64
+ let transitions = 0;
65
+ for (let i = 1; i < outcomes.length; i++) {
66
+ if (outcomes[i] !== outcomes[i - 1])
67
+ transitions++;
68
+ }
69
+ return transitions;
70
+ }
71
+ /**
72
+ * The same scoring the hosted service applies, so a team sees one answer
73
+ * whether they read it here or in the dashboard.
74
+ */
75
+ function computeFlakiness(history) {
76
+ const sequence = history
77
+ .map((h) => toPassFail(h.outcome))
78
+ .filter((o) => o !== null);
79
+ const runs = sequence.length;
80
+ if (runs === 0) {
81
+ return {
82
+ score: 0,
83
+ verdict: "stable",
84
+ runs: 0,
85
+ failureRate: 0,
86
+ selfReportedFlakyRate: 0,
87
+ transitionRate: 0,
88
+ };
89
+ }
90
+ const failures = sequence.filter((o) => o === "fail").length;
91
+ const failureRate = failures / runs;
92
+ const selfReportedFlaky = history.filter((h) => h.outcome === "flaky").length;
93
+ const selfReportedFlakyRate = selfReportedFlaky / history.length;
94
+ const transitions = countTransitions(sequence);
95
+ const transitionRate = runs > 1 ? transitions / (runs - 1) : 0;
96
+ // The score says how bad; this says whether we are sure. A run the runner
97
+ // itself called flaky is direct evidence — the test failed and then passed
98
+ // inside one run, which nothing but flakiness explains. A test that did
99
+ // that in a fifth of its runs is flaky even though the score, weighted to
100
+ // rank the worst offenders first, leaves it below the threshold. Two such
101
+ // runs are required so a single retry on a bad afternoon is not a verdict.
102
+ const isDirectlyEvidencedFlaky = selfReportedFlaky >= exports.MIN_FLAKY_RUNS && selfReportedFlakyRate >= exports.MIN_FLAKY_RATE;
103
+ const score = Math.round(Math.min(100, selfReportedFlakyRate * 100 * 0.75 + transitionRate * 100 * 0.25));
104
+ let verdict;
105
+ if (runs < exports.MIN_RUNS_FOR_VERDICT) {
106
+ verdict = score > 0 ? "suspect" : "stable";
107
+ }
108
+ else if (score >= exports.FLAKY_SCORE_THRESHOLD || isDirectlyEvidencedFlaky) {
109
+ verdict = "flaky";
110
+ }
111
+ else if (failureRate >= 0.9 && transitionRate <= 0.1 && selfReportedFlakyRate <= 0.1) {
112
+ // Fails nearly always and almost never changes its mind: a failing test,
113
+ // not a flaky one. Quarantining this is how a real bug reaches production.
114
+ verdict = "broken";
115
+ }
116
+ else if (score > 0) {
117
+ verdict = "suspect";
118
+ }
119
+ else {
120
+ verdict = "stable";
121
+ }
122
+ return {
123
+ score,
124
+ verdict,
125
+ runs,
126
+ failureRate: Number(failureRate.toFixed(3)),
127
+ selfReportedFlakyRate: Number(selfReportedFlakyRate.toFixed(3)),
128
+ transitionRate: Number(transitionRate.toFixed(3)),
129
+ };
130
+ }
131
+ function historyPath(cwd) {
132
+ return (0, path_1.join)(cwd, exports.HISTORY_DIR, exports.HISTORY_FILE);
133
+ }
134
+ /**
135
+ * A history file that cannot be read is treated as no history.
136
+ *
137
+ * It is a cache of past runs, not data anyone would mourn, and refusing to
138
+ * run because of it would break the first rule: never fail someone's build.
139
+ */
140
+ function readHistory(cwd) {
141
+ try {
142
+ const raw = (0, fs_1.readFileSync)(historyPath(cwd), "utf8");
143
+ const parsed = JSON.parse(raw);
144
+ if (!parsed || !Array.isArray(parsed.runs))
145
+ return { version: 1, runs: [] };
146
+ return { version: 1, runs: parsed.runs };
147
+ }
148
+ catch {
149
+ return { version: 1, runs: [] };
150
+ }
151
+ }
152
+ function appendRun(history, run) {
153
+ // Oldest first, so the newest run is the last element and the window drops
154
+ // the oldest runs rather than the ones that matter.
155
+ return { version: 1, runs: [...history.runs, run].slice(-exports.MAX_RUNS) };
156
+ }
157
+ /**
158
+ * Keep the directory out of git.
159
+ *
160
+ * Committing it would mean every developer's every run produces a diff, and
161
+ * a merge conflict in a file nobody reads. Only written when absent, so a
162
+ * team that decides otherwise is not overruled on the next run.
163
+ */
164
+ function ensureIgnored(cwd) {
165
+ try {
166
+ const ignorePath = (0, path_1.join)(cwd, exports.HISTORY_DIR, ".gitignore");
167
+ if ((0, fs_1.existsSync)(ignorePath))
168
+ return;
169
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(ignorePath), { recursive: true });
170
+ (0, fs_1.writeFileSync)(ignorePath, "*\n", "utf8");
171
+ }
172
+ catch {
173
+ // Not being able to write the ignore file is not a reason to stop.
174
+ }
175
+ }
176
+ function writeHistory(cwd, history) {
177
+ try {
178
+ const path = historyPath(cwd);
179
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(path), { recursive: true });
180
+ (0, fs_1.writeFileSync)(path, `${JSON.stringify(history)}\n`, "utf8");
181
+ ensureIgnored(cwd);
182
+ }
183
+ catch (error) {
184
+ const reason = error instanceof Error ? error.message : String(error);
185
+ console.error(`[fixsense] Local history not saved: ${reason}`);
186
+ }
187
+ }
188
+ /** Group the stored runs by test and score each one. */
189
+ function scoreHistory(history) {
190
+ const byTest = new Map();
191
+ for (const run of history.runs) {
192
+ for (const test of run.tests ?? []) {
193
+ const key = `${test.file ?? ""}\u0000${test.title}`;
194
+ const entry = byTest.get(key) ?? { file: test.file ?? null, outcomes: [] };
195
+ entry.outcomes.push(test.outcome);
196
+ byTest.set(key, entry);
197
+ }
198
+ }
199
+ const verdicts = [];
200
+ for (const [key, entry] of byTest) {
201
+ const report = computeFlakiness(entry.outcomes.map((outcome) => ({ outcome })));
202
+ verdicts.push({
203
+ ...report,
204
+ title: key.split("\u0000")[1] ?? "",
205
+ file: entry.file,
206
+ badRuns: entry.outcomes.filter((o) => o === "flaky" || o === "unexpected").length,
207
+ });
208
+ }
209
+ return verdicts.sort((a, b) => b.score - a.score);
210
+ }
211
+ /**
212
+ * The summary a reader sees, or nothing at all.
213
+ *
214
+ * A line printed after every green run is a line teams learn to scroll past,
215
+ * so this stays empty unless the history actually found something. "suspect"
216
+ * is deliberately not reported: it means the tool is not sure yet.
217
+ */
218
+ function renderSummary(verdicts, totalRuns) {
219
+ const flaky = verdicts.filter((v) => v.verdict === "flaky");
220
+ const broken = verdicts.filter((v) => v.verdict === "broken");
221
+ if (flaky.length === 0 && broken.length === 0)
222
+ return "";
223
+ const lines = [];
224
+ if (flaky.length > 0) {
225
+ lines.push(`FixSense: ${flaky.length} ${flaky.length === 1 ? "test behaves" : "tests behave"} flakily across the last ${totalRuns} runs`);
226
+ for (const v of flaky) {
227
+ lines.push(` ${v.title} — failed or retried in ${v.badRuns} of ${v.runs} runs`);
228
+ }
229
+ }
230
+ if (broken.length > 0) {
231
+ lines.push(`FixSense: ${broken.length} ${broken.length === 1 ? "test fails" : "tests fail"} every run — a bug, not flakiness`);
232
+ for (const v of broken) {
233
+ lines.push(` ${v.title} — failed in ${v.badRuns} of ${v.runs} runs`);
234
+ }
235
+ }
236
+ return lines.join("\n");
237
+ }
238
+ /** The same summary as GitHub-flavoured Markdown, for the run's own page. */
239
+ function renderMarkdown(verdicts, totalRuns) {
240
+ const interesting = verdicts.filter((v) => v.verdict === "flaky" || v.verdict === "broken");
241
+ if (interesting.length === 0)
242
+ return "";
243
+ const rows = interesting
244
+ .map((v) => `| \`${v.title}\` | ${v.verdict} | ${v.badRuns} of ${v.runs} | ${v.score} |`)
245
+ .join("\n");
246
+ return [
247
+ `### FixSense — what these tests did over the last ${totalRuns} runs`,
248
+ "",
249
+ "| Test | Verdict | Bad runs | Score |",
250
+ "| --- | --- | --- | --- |",
251
+ rows,
252
+ "",
253
+ ].join("\n");
254
+ }
255
+ /**
256
+ * Write the Markdown where GitHub Actions renders it on the run's page.
257
+ *
258
+ * In the job log the summary scrolls away under the test output; on the run
259
+ * page it is the first thing a reviewer sees.
260
+ */
261
+ function writeStepSummary(markdown) {
262
+ const path = process.env.GITHUB_STEP_SUMMARY;
263
+ if (!path || !markdown)
264
+ return;
265
+ try {
266
+ (0, fs_1.appendFileSync)(path, `${markdown}\n`, "utf8");
267
+ }
268
+ catch {
269
+ // The step summary is a nicety; losing it is not worth a word.
270
+ }
271
+ }
272
+ /**
273
+ * One entry per test per run, whatever the runner reported.
274
+ *
275
+ * A run that listed the same test twice would count as two runs for it, and
276
+ * a retried test would read as several times as flaky as it is. The last
277
+ * entry wins: for a runner that reports each attempt, it is the one that
278
+ * knows how the test finally ended.
279
+ */
280
+ function dedupe(tests) {
281
+ const byKey = new Map();
282
+ for (const t of tests) {
283
+ byKey.set(`${t.file ?? ""}\u0000${t.title}`, {
284
+ title: t.title,
285
+ file: t.file,
286
+ outcome: t.outcome,
287
+ });
288
+ }
289
+ return [...byKey.values()];
290
+ }
291
+ /**
292
+ * Record this run and report what the history now says.
293
+ *
294
+ * Returns the text that was printed, which is what the tests assert on.
295
+ */
296
+ function recordAndReport(cwd, tests, now = new Date()) {
297
+ const history = appendRun(readHistory(cwd), {
298
+ at: now.toISOString(),
299
+ tests: dedupe(tests),
300
+ });
301
+ writeHistory(cwd, history);
302
+ const verdicts = scoreHistory(history);
303
+ const summary = renderSummary(verdicts, history.runs.length);
304
+ if (summary) {
305
+ console.log(`\n${summary}\n`);
306
+ writeStepSummary(renderMarkdown(verdicts, history.runs.length));
307
+ }
308
+ return summary;
309
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fixsense/cypress-plugin",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Cypress plugin that records test outcomes across runs so flaky tests can be identified over time.",
5
5
  "license": "MIT",
6
6
  "main": "./dist/index.js",