@fixsense/cypress-plugin 0.0.0-stage → 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CopilotMe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,96 @@
1
- # Temporary Holding Version
1
+ # @fixsense/cypress-plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A Cypress plugin that records what each test did, run after run.
4
+
5
+ Cypress knows a test was retried inside the run it is executing and forgets it
6
+ on exit. This plugin keeps that history, which is what makes a flaky test
7
+ identifiable as flaky rather than as bad luck.
8
+
9
+ Free and MIT licensed. It works on its own; FixSense's paid analysis and
10
+ auto-fix build on the same data.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm install -D @fixsense/cypress-plugin
16
+ ```
17
+
18
+ ```ts
19
+ // cypress.config.ts
20
+ import { defineConfig } from 'cypress';
21
+ import { registerFixSense } from '@fixsense/cypress-plugin';
22
+
23
+ export default defineConfig({
24
+ // Retries are what let Cypress distinguish a flaky test from a failing one.
25
+ retries: { runMode: 2, openMode: 0 },
26
+ e2e: {
27
+ setupNodeEvents(on, config) {
28
+ registerFixSense(on);
29
+ return config;
30
+ },
31
+ },
32
+ });
33
+ ```
34
+
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.
68
+
69
+ ## Options
70
+
71
+ ```ts
72
+ registerFixSense(on, {
73
+ apiKey: process.env.FIXSENSE_API_KEY, // default: FIXSENSE_API_KEY
74
+ apiUrl: 'https://fix-sense.com', // self-hosted installations
75
+ enabled: true,
76
+ timeoutMs: 10000,
77
+ repoFullName: 'acme/web', // when CI variables are absent
78
+ local: true, // keep .fixsense/history.json
79
+ cwd: process.cwd(), // where that history lives
80
+ });
81
+ ```
82
+
83
+ GitHub Actions, GitLab CI, Bitbucket Pipelines and Azure Pipelines are
84
+ detected automatically.
85
+
86
+ ## What it sends to FixSense (only with a key)
87
+
88
+ Per test: the describe/it title chain, the spec file, the outcome, the retry
89
+ count, the duration, and the error message truncated to 2000 characters.
90
+
91
+ It does not send source code, screenshots, videos or environment variables.
92
+
93
+ ## What it will not do
94
+
95
+ It will never fail your run. If the upload fails for any reason, it prints one
96
+ line to stderr and the run's own exit code is untouched.
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @fixsense/cypress-plugin
3
+ *
4
+ * Records what each Cypress test did, run after run, so a flaky test can be
5
+ * recognised as flaky rather than as bad luck.
6
+ *
7
+ * Same two rules as the Playwright reporter, for the same reasons: it never
8
+ * fails a run, and it sends outcomes rather than content.
9
+ */
10
+ import { type TestRecord } from "./payload";
11
+ export interface FixSenseCypressOptions {
12
+ /** Defaults to the FIXSENSE_API_KEY environment variable. */
13
+ apiKey?: string;
14
+ /** Override for self-hosted installations. */
15
+ apiUrl?: string;
16
+ /** Set false to turn the plugin off without editing the config. */
17
+ enabled?: boolean;
18
+ timeoutMs?: number;
19
+ /** Override repo detection when CI variables are absent or wrong. */
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;
30
+ }
31
+ /** The subset of Cypress's plugin event registrar we use. */
32
+ type On = (event: string, handler: (...args: never[]) => void | Promise<void>) => void;
33
+ /**
34
+ * Register the plugin from `setupNodeEvents`.
35
+ *
36
+ * Results are collected per spec and sent once at the end of the run, so one
37
+ * request covers the whole suite rather than one per spec file.
38
+ */
39
+ export declare function registerFixSense(on: On, options?: FixSenseCypressOptions): void;
40
+ export declare function sendRun(tests: TestRecord[], startedAt: Date, options: FixSenseCypressOptions): Promise<void>;
41
+ export default registerFixSense;
42
+ export * from "./payload";
43
+ export { computeFlakiness, readHistory, recordAndReport, renderMarkdown, renderSummary, scoreHistory, HISTORY_DIR, HISTORY_FILE, MAX_RUNS, } from "./local";
package/dist/index.js ADDED
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ /**
3
+ * @fixsense/cypress-plugin
4
+ *
5
+ * Records what each Cypress test did, run after run, so a flaky test can be
6
+ * recognised as flaky rather than as bad luck.
7
+ *
8
+ * Same two rules as the Playwright reporter, for the same reasons: it never
9
+ * fails a run, and it sends outcomes rather than content.
10
+ */
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
23
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
24
+ };
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;
27
+ exports.registerFixSense = registerFixSense;
28
+ exports.sendRun = sendRun;
29
+ const payload_1 = require("./payload");
30
+ const local_1 = require("./local");
31
+ const DEFAULT_API_URL = "https://fix-sense.com";
32
+ const DEFAULT_TIMEOUT_MS = 10_000;
33
+ /**
34
+ * Register the plugin from `setupNodeEvents`.
35
+ *
36
+ * Results are collected per spec and sent once at the end of the run, so one
37
+ * request covers the whole suite rather than one per spec file.
38
+ */
39
+ function registerFixSense(on, options = {}) {
40
+ const tests = [];
41
+ const startedAt = new Date();
42
+ on("after:spec", ((spec, results) => {
43
+ try {
44
+ for (const test of results?.tests ?? []) {
45
+ tests.push((0, payload_1.toTestRecord)(test, spec));
46
+ }
47
+ }
48
+ catch {
49
+ // One unreadable spec is not a reason to lose the rest of the run.
50
+ }
51
+ }));
52
+ on("after:run", (async () => {
53
+ await sendRun(tests, startedAt, options);
54
+ }));
55
+ }
56
+ async function sendRun(tests, startedAt, options) {
57
+ if (options.enabled === false)
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
+ }
72
+ const apiKey = options.apiKey ?? process.env.FIXSENSE_API_KEY;
73
+ // Silent without a key: a developer running Cypress locally has none and
74
+ // does not need telling on every run.
75
+ if (!apiKey)
76
+ return;
77
+ const context = (0, payload_1.detectContext)(process.env);
78
+ const payload = {
79
+ schemaVersion: 1,
80
+ ...context,
81
+ repoFullName: options.repoFullName ?? context.repoFullName,
82
+ startedAt: startedAt.toISOString(),
83
+ durationMs: Date.now() - startedAt.getTime(),
84
+ totals: (0, payload_1.summarise)(tests),
85
+ tests,
86
+ };
87
+ const base = options.apiUrl ?? process.env.FIXSENSE_API_URL ?? DEFAULT_API_URL;
88
+ const controller = new AbortController();
89
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
90
+ try {
91
+ const res = await fetch(`${base.replace(/\/$/, "")}/api/v1/runs`, {
92
+ method: "POST",
93
+ headers: {
94
+ Authorization: `Bearer ${apiKey}`,
95
+ "Content-Type": "application/json",
96
+ },
97
+ body: JSON.stringify(payload),
98
+ signal: controller.signal,
99
+ });
100
+ if (!res.ok) {
101
+ console.error(`[fixsense] Run not recorded: ${res.status} ${res.statusText}`);
102
+ }
103
+ }
104
+ catch (error) {
105
+ const reason = error instanceof Error ? error.message : String(error);
106
+ console.error(`[fixsense] Run not recorded: ${reason}`);
107
+ }
108
+ finally {
109
+ clearTimeout(timer);
110
+ }
111
+ }
112
+ exports.default = registerFixSense;
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,111 @@
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
+ export type Verdict = "stable" | "broken" | "flaky" | "suspect";
47
+ export interface FlakinessReport {
48
+ score: number;
49
+ verdict: Verdict;
50
+ runs: number;
51
+ failureRate: number;
52
+ selfReportedFlakyRate: number;
53
+ transitionRate: number;
54
+ }
55
+ export declare function countTransitions(outcomes: Array<"pass" | "fail">): number;
56
+ /**
57
+ * The same scoring the hosted service applies, so a team sees one answer
58
+ * whether they read it here or in the dashboard.
59
+ */
60
+ export declare function computeFlakiness(history: Array<{
61
+ outcome: Outcome;
62
+ }>): FlakinessReport;
63
+ export declare function historyPath(cwd: string): string;
64
+ /**
65
+ * A history file that cannot be read is treated as no history.
66
+ *
67
+ * It is a cache of past runs, not data anyone would mourn, and refusing to
68
+ * run because of it would break the first rule: never fail someone's build.
69
+ */
70
+ export declare function readHistory(cwd: string): LocalHistory;
71
+ export declare function appendRun(history: LocalHistory, run: StoredRun): LocalHistory;
72
+ /**
73
+ * Keep the directory out of git.
74
+ *
75
+ * Committing it would mean every developer's every run produces a diff, and
76
+ * a merge conflict in a file nobody reads. Only written when absent, so a
77
+ * team that decides otherwise is not overruled on the next run.
78
+ */
79
+ export declare function ensureIgnored(cwd: string): void;
80
+ export declare function writeHistory(cwd: string, history: LocalHistory): void;
81
+ export interface TestVerdict extends FlakinessReport {
82
+ title: string;
83
+ file: string | null;
84
+ /** How many of the stored runs this test failed or needed a retry in. */
85
+ badRuns: number;
86
+ }
87
+ /** Group the stored runs by test and score each one. */
88
+ export declare function scoreHistory(history: LocalHistory): TestVerdict[];
89
+ /**
90
+ * The summary a reader sees, or nothing at all.
91
+ *
92
+ * A line printed after every green run is a line teams learn to scroll past,
93
+ * so this stays empty unless the history actually found something. "suspect"
94
+ * is deliberately not reported: it means the tool is not sure yet.
95
+ */
96
+ export declare function renderSummary(verdicts: TestVerdict[], totalRuns: number): string;
97
+ /** The same summary as GitHub-flavoured Markdown, for the run's own page. */
98
+ export declare function renderMarkdown(verdicts: TestVerdict[], totalRuns: number): string;
99
+ /**
100
+ * Write the Markdown where GitHub Actions renders it on the run's page.
101
+ *
102
+ * In the job log the summary scrolls away under the test output; on the run
103
+ * page it is the first thing a reviewer sees.
104
+ */
105
+ export declare function writeStepSummary(markdown: string): void;
106
+ /**
107
+ * Record this run and report what the history now says.
108
+ *
109
+ * Returns the text that was printed, which is what the tests assert on.
110
+ */
111
+ export declare function recordAndReport(cwd: string, tests: StoredTest[], now?: Date): string;
package/dist/local.js ADDED
@@ -0,0 +1,278 @@
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.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.recordAndReport = recordAndReport;
34
+ const fs_1 = require("fs");
35
+ const path_1 = require("path");
36
+ exports.HISTORY_DIR = ".fixsense";
37
+ exports.HISTORY_FILE = "history.json";
38
+ /**
39
+ * How many runs are kept.
40
+ *
41
+ * Enough that a weekly pattern is visible, few enough that the file stays
42
+ * small in a repository someone did not ask to carry a database.
43
+ */
44
+ exports.MAX_RUNS = 50;
45
+ /** Below this, any verdict is guesswork — the same floor the service uses. */
46
+ exports.MIN_RUNS_FOR_VERDICT = 5;
47
+ /** At or above this score a test is called flaky. */
48
+ exports.FLAKY_SCORE_THRESHOLD = 70;
49
+ function toPassFail(outcome) {
50
+ if (outcome === "skipped")
51
+ return null;
52
+ // A run the runner called flaky ended green, but it is not a pass: it
53
+ // needed a retry to get there, which is the behaviour being measured.
54
+ if (outcome === "flaky")
55
+ return "fail";
56
+ return outcome === "expected" ? "pass" : "fail";
57
+ }
58
+ function countTransitions(outcomes) {
59
+ let transitions = 0;
60
+ for (let i = 1; i < outcomes.length; i++) {
61
+ if (outcomes[i] !== outcomes[i - 1])
62
+ transitions++;
63
+ }
64
+ return transitions;
65
+ }
66
+ /**
67
+ * The same scoring the hosted service applies, so a team sees one answer
68
+ * whether they read it here or in the dashboard.
69
+ */
70
+ function computeFlakiness(history) {
71
+ const sequence = history
72
+ .map((h) => toPassFail(h.outcome))
73
+ .filter((o) => o !== null);
74
+ const runs = sequence.length;
75
+ if (runs === 0) {
76
+ return {
77
+ score: 0,
78
+ verdict: "stable",
79
+ runs: 0,
80
+ failureRate: 0,
81
+ selfReportedFlakyRate: 0,
82
+ transitionRate: 0,
83
+ };
84
+ }
85
+ const failures = sequence.filter((o) => o === "fail").length;
86
+ const failureRate = failures / runs;
87
+ const selfReportedFlaky = history.filter((h) => h.outcome === "flaky").length;
88
+ const selfReportedFlakyRate = selfReportedFlaky / history.length;
89
+ const transitions = countTransitions(sequence);
90
+ const transitionRate = runs > 1 ? transitions / (runs - 1) : 0;
91
+ const score = Math.round(Math.min(100, selfReportedFlakyRate * 100 * 0.75 + transitionRate * 100 * 0.25));
92
+ let verdict;
93
+ if (runs < exports.MIN_RUNS_FOR_VERDICT) {
94
+ verdict = score > 0 ? "suspect" : "stable";
95
+ }
96
+ else if (score >= exports.FLAKY_SCORE_THRESHOLD) {
97
+ verdict = "flaky";
98
+ }
99
+ else if (failureRate >= 0.9 && transitionRate <= 0.1 && selfReportedFlakyRate <= 0.1) {
100
+ // Fails nearly always and almost never changes its mind: a failing test,
101
+ // not a flaky one. Quarantining this is how a real bug reaches production.
102
+ verdict = "broken";
103
+ }
104
+ else if (score > 0) {
105
+ verdict = "suspect";
106
+ }
107
+ else {
108
+ verdict = "stable";
109
+ }
110
+ return {
111
+ score,
112
+ verdict,
113
+ runs,
114
+ failureRate: Number(failureRate.toFixed(3)),
115
+ selfReportedFlakyRate: Number(selfReportedFlakyRate.toFixed(3)),
116
+ transitionRate: Number(transitionRate.toFixed(3)),
117
+ };
118
+ }
119
+ function historyPath(cwd) {
120
+ return (0, path_1.join)(cwd, exports.HISTORY_DIR, exports.HISTORY_FILE);
121
+ }
122
+ /**
123
+ * A history file that cannot be read is treated as no history.
124
+ *
125
+ * It is a cache of past runs, not data anyone would mourn, and refusing to
126
+ * run because of it would break the first rule: never fail someone's build.
127
+ */
128
+ function readHistory(cwd) {
129
+ try {
130
+ const raw = (0, fs_1.readFileSync)(historyPath(cwd), "utf8");
131
+ const parsed = JSON.parse(raw);
132
+ if (!parsed || !Array.isArray(parsed.runs))
133
+ return { version: 1, runs: [] };
134
+ return { version: 1, runs: parsed.runs };
135
+ }
136
+ catch {
137
+ return { version: 1, runs: [] };
138
+ }
139
+ }
140
+ function appendRun(history, run) {
141
+ // Oldest first, so the newest run is the last element and the window drops
142
+ // the oldest runs rather than the ones that matter.
143
+ return { version: 1, runs: [...history.runs, run].slice(-exports.MAX_RUNS) };
144
+ }
145
+ /**
146
+ * Keep the directory out of git.
147
+ *
148
+ * Committing it would mean every developer's every run produces a diff, and
149
+ * a merge conflict in a file nobody reads. Only written when absent, so a
150
+ * team that decides otherwise is not overruled on the next run.
151
+ */
152
+ function ensureIgnored(cwd) {
153
+ try {
154
+ const ignorePath = (0, path_1.join)(cwd, exports.HISTORY_DIR, ".gitignore");
155
+ if ((0, fs_1.existsSync)(ignorePath))
156
+ return;
157
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(ignorePath), { recursive: true });
158
+ (0, fs_1.writeFileSync)(ignorePath, "*\n", "utf8");
159
+ }
160
+ catch {
161
+ // Not being able to write the ignore file is not a reason to stop.
162
+ }
163
+ }
164
+ function writeHistory(cwd, history) {
165
+ try {
166
+ const path = historyPath(cwd);
167
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(path), { recursive: true });
168
+ (0, fs_1.writeFileSync)(path, `${JSON.stringify(history)}\n`, "utf8");
169
+ ensureIgnored(cwd);
170
+ }
171
+ catch (error) {
172
+ const reason = error instanceof Error ? error.message : String(error);
173
+ console.error(`[fixsense] Local history not saved: ${reason}`);
174
+ }
175
+ }
176
+ /** Group the stored runs by test and score each one. */
177
+ function scoreHistory(history) {
178
+ const byTest = new Map();
179
+ for (const run of history.runs) {
180
+ for (const test of run.tests ?? []) {
181
+ const key = `${test.file ?? ""}\u0000${test.title}`;
182
+ const entry = byTest.get(key) ?? { file: test.file ?? null, outcomes: [] };
183
+ entry.outcomes.push(test.outcome);
184
+ byTest.set(key, entry);
185
+ }
186
+ }
187
+ const verdicts = [];
188
+ for (const [key, entry] of byTest) {
189
+ const report = computeFlakiness(entry.outcomes.map((outcome) => ({ outcome })));
190
+ verdicts.push({
191
+ ...report,
192
+ title: key.split("\u0000")[1] ?? "",
193
+ file: entry.file,
194
+ badRuns: entry.outcomes.filter((o) => o === "flaky" || o === "unexpected").length,
195
+ });
196
+ }
197
+ return verdicts.sort((a, b) => b.score - a.score);
198
+ }
199
+ /**
200
+ * The summary a reader sees, or nothing at all.
201
+ *
202
+ * A line printed after every green run is a line teams learn to scroll past,
203
+ * so this stays empty unless the history actually found something. "suspect"
204
+ * is deliberately not reported: it means the tool is not sure yet.
205
+ */
206
+ function renderSummary(verdicts, totalRuns) {
207
+ const flaky = verdicts.filter((v) => v.verdict === "flaky");
208
+ const broken = verdicts.filter((v) => v.verdict === "broken");
209
+ if (flaky.length === 0 && broken.length === 0)
210
+ return "";
211
+ const lines = [];
212
+ if (flaky.length > 0) {
213
+ lines.push(`FixSense: ${flaky.length} ${flaky.length === 1 ? "test behaves" : "tests behave"} flakily across the last ${totalRuns} runs`);
214
+ for (const v of flaky) {
215
+ lines.push(` ${v.title} — failed or retried in ${v.badRuns} of ${v.runs} runs`);
216
+ }
217
+ }
218
+ if (broken.length > 0) {
219
+ lines.push(`FixSense: ${broken.length} ${broken.length === 1 ? "test fails" : "tests fail"} every run — a bug, not flakiness`);
220
+ for (const v of broken) {
221
+ lines.push(` ${v.title} — failed in ${v.badRuns} of ${v.runs} runs`);
222
+ }
223
+ }
224
+ return lines.join("\n");
225
+ }
226
+ /** The same summary as GitHub-flavoured Markdown, for the run's own page. */
227
+ function renderMarkdown(verdicts, totalRuns) {
228
+ const interesting = verdicts.filter((v) => v.verdict === "flaky" || v.verdict === "broken");
229
+ if (interesting.length === 0)
230
+ return "";
231
+ const rows = interesting
232
+ .map((v) => `| \`${v.title}\` | ${v.verdict} | ${v.badRuns} of ${v.runs} | ${v.score} |`)
233
+ .join("\n");
234
+ return [
235
+ `### FixSense — what these tests did over the last ${totalRuns} runs`,
236
+ "",
237
+ "| Test | Verdict | Bad runs | Score |",
238
+ "| --- | --- | --- | --- |",
239
+ rows,
240
+ "",
241
+ ].join("\n");
242
+ }
243
+ /**
244
+ * Write the Markdown where GitHub Actions renders it on the run's page.
245
+ *
246
+ * In the job log the summary scrolls away under the test output; on the run
247
+ * page it is the first thing a reviewer sees.
248
+ */
249
+ function writeStepSummary(markdown) {
250
+ const path = process.env.GITHUB_STEP_SUMMARY;
251
+ if (!path || !markdown)
252
+ return;
253
+ try {
254
+ (0, fs_1.appendFileSync)(path, `${markdown}\n`, "utf8");
255
+ }
256
+ catch {
257
+ // The step summary is a nicety; losing it is not worth a word.
258
+ }
259
+ }
260
+ /**
261
+ * Record this run and report what the history now says.
262
+ *
263
+ * Returns the text that was printed, which is what the tests assert on.
264
+ */
265
+ function recordAndReport(cwd, tests, now = new Date()) {
266
+ const history = appendRun(readHistory(cwd), {
267
+ at: now.toISOString(),
268
+ tests: tests.map((t) => ({ title: t.title, file: t.file, outcome: t.outcome })),
269
+ });
270
+ writeHistory(cwd, history);
271
+ const verdicts = scoreHistory(history);
272
+ const summary = renderSummary(verdicts, history.runs.length);
273
+ if (summary) {
274
+ console.log(`\n${summary}\n`);
275
+ writeStepSummary(renderMarkdown(verdicts, history.runs.length));
276
+ }
277
+ return summary;
278
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Building the run payload from Cypress results.
3
+ *
4
+ * The CI detection and truncation below are deliberately a copy of what
5
+ * @fixsense/playwright-reporter does, not a shared dependency. Each package
6
+ * installs on its own with no FixSense runtime dependency, which is the whole
7
+ * reason a team will add it. `tests/unit/reporter-parity.test.ts` asserts both
8
+ * copies answer identically for the same environment, so the duplication
9
+ * cannot drift silently.
10
+ */
11
+ /** Cypress calls a test's state one of these. */
12
+ export type CypressState = "passed" | "failed" | "pending" | "skipped";
13
+ /** The parts of a Cypress `after:spec` result we read. Structural on purpose. */
14
+ export interface CypressTestLike {
15
+ title: string[];
16
+ state: CypressState;
17
+ duration?: number;
18
+ attempts?: Array<{
19
+ state?: string;
20
+ }>;
21
+ displayError?: string | null;
22
+ }
23
+ export interface CypressSpecLike {
24
+ relative?: string;
25
+ absolute?: string;
26
+ }
27
+ /** The same four words the Playwright reporter sends. */
28
+ export type Outcome = "expected" | "unexpected" | "flaky" | "skipped";
29
+ export interface TestRecord {
30
+ title: string;
31
+ file: string | null;
32
+ outcome: Outcome;
33
+ status: string;
34
+ retries: number;
35
+ durationMs: number;
36
+ errorMessage: string | null;
37
+ }
38
+ export declare const MAX_ERROR_CHARS = 2000;
39
+ export declare function truncateError(message: string | undefined | null): string | null;
40
+ /**
41
+ * Cypress has no "flaky" state, so it has to be derived.
42
+ *
43
+ * With `retries` configured, a test that failed an attempt and passed a later
44
+ * one is exactly what Playwright calls flaky. Without retries configured
45
+ * Cypress cannot produce the signal at all, and such a run contributes only
46
+ * pass/fail — which the cross-run history still scores, just more slowly.
47
+ */
48
+ export declare function deriveOutcome(test: CypressTestLike): Outcome;
49
+ export declare function toTestRecord(test: CypressTestLike, spec: CypressSpecLike): TestRecord;
50
+ export declare function summarise(tests: TestRecord[]): {
51
+ total: number;
52
+ passed: number;
53
+ failed: number;
54
+ flaky: number;
55
+ skipped: number;
56
+ };
57
+ export declare function detectContext(env: Record<string, string | undefined>): {
58
+ provider: string;
59
+ repoFullName: string | null;
60
+ commitSha: string | null;
61
+ branch: string | null;
62
+ ciRunId: string | null;
63
+ ciRunUrl: string | null;
64
+ } | {
65
+ provider: null;
66
+ repoFullName: null;
67
+ commitSha: null;
68
+ branch: null;
69
+ ciRunId: null;
70
+ ciRunUrl: null;
71
+ };
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ /**
3
+ * Building the run payload from Cypress results.
4
+ *
5
+ * The CI detection and truncation below are deliberately a copy of what
6
+ * @fixsense/playwright-reporter does, not a shared dependency. Each package
7
+ * installs on its own with no FixSense runtime dependency, which is the whole
8
+ * reason a team will add it. `tests/unit/reporter-parity.test.ts` asserts both
9
+ * copies answer identically for the same environment, so the duplication
10
+ * cannot drift silently.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.MAX_ERROR_CHARS = void 0;
14
+ exports.truncateError = truncateError;
15
+ exports.deriveOutcome = deriveOutcome;
16
+ exports.toTestRecord = toTestRecord;
17
+ exports.summarise = summarise;
18
+ exports.detectContext = detectContext;
19
+ exports.MAX_ERROR_CHARS = 2000;
20
+ function truncateError(message) {
21
+ if (!message)
22
+ return null;
23
+ const clean = message.replace(/\u001b\[[0-9;]*m/g, "").trim();
24
+ if (!clean)
25
+ return null;
26
+ return clean.length > exports.MAX_ERROR_CHARS
27
+ ? `${clean.slice(0, exports.MAX_ERROR_CHARS)}… [truncated]`
28
+ : clean;
29
+ }
30
+ /**
31
+ * Cypress has no "flaky" state, so it has to be derived.
32
+ *
33
+ * With `retries` configured, a test that failed an attempt and passed a later
34
+ * one is exactly what Playwright calls flaky. Without retries configured
35
+ * Cypress cannot produce the signal at all, and such a run contributes only
36
+ * pass/fail — which the cross-run history still scores, just more slowly.
37
+ */
38
+ function deriveOutcome(test) {
39
+ if (test.state === "pending" || test.state === "skipped")
40
+ return "skipped";
41
+ if (test.state === "failed")
42
+ return "unexpected";
43
+ const attempts = test.attempts ?? [];
44
+ const failedEarlier = attempts
45
+ .slice(0, -1)
46
+ .some((attempt) => attempt.state === "failed");
47
+ return failedEarlier ? "flaky" : "expected";
48
+ }
49
+ function toTestRecord(test, spec) {
50
+ return {
51
+ // Cypress gives the describe/it chain as an array; the separator matches
52
+ // the Playwright reporter so one history reads the same from both.
53
+ title: test.title.filter(Boolean).join(" › "),
54
+ file: spec.relative ?? spec.absolute ?? null,
55
+ outcome: deriveOutcome(test),
56
+ status: test.state,
57
+ retries: Math.max(0, (test.attempts?.length ?? 1) - 1),
58
+ durationMs: test.duration ?? 0,
59
+ errorMessage: truncateError(test.displayError),
60
+ };
61
+ }
62
+ function summarise(tests) {
63
+ return {
64
+ total: tests.length,
65
+ passed: tests.filter((t) => t.outcome === "expected").length,
66
+ failed: tests.filter((t) => t.outcome === "unexpected").length,
67
+ flaky: tests.filter((t) => t.outcome === "flaky").length,
68
+ skipped: tests.filter((t) => t.outcome === "skipped").length,
69
+ };
70
+ }
71
+ function detectContext(env) {
72
+ if (env.GITHUB_ACTIONS === "true" || env.GITHUB_REPOSITORY) {
73
+ const repo = env.GITHUB_REPOSITORY ?? null;
74
+ return {
75
+ provider: "github",
76
+ repoFullName: repo,
77
+ commitSha: env.GITHUB_SHA ?? null,
78
+ branch: env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME || null,
79
+ ciRunId: env.GITHUB_RUN_ID ?? null,
80
+ ciRunUrl: repo && env.GITHUB_RUN_ID
81
+ ? `${env.GITHUB_SERVER_URL ?? "https://github.com"}/${repo}/actions/runs/${env.GITHUB_RUN_ID}`
82
+ : null,
83
+ };
84
+ }
85
+ if (env.GITLAB_CI === "true" || env.CI_PROJECT_PATH) {
86
+ return {
87
+ provider: "gitlab",
88
+ repoFullName: env.CI_PROJECT_PATH ?? null,
89
+ commitSha: env.CI_COMMIT_SHA ?? null,
90
+ branch: env.CI_COMMIT_REF_NAME ?? null,
91
+ ciRunId: env.CI_PIPELINE_ID ?? null,
92
+ ciRunUrl: env.CI_PIPELINE_URL ?? null,
93
+ };
94
+ }
95
+ if (env.BITBUCKET_REPO_FULL_NAME) {
96
+ return {
97
+ provider: "bitbucket",
98
+ repoFullName: env.BITBUCKET_REPO_FULL_NAME,
99
+ commitSha: env.BITBUCKET_COMMIT ?? null,
100
+ branch: env.BITBUCKET_BRANCH ?? null,
101
+ ciRunId: env.BITBUCKET_BUILD_NUMBER ?? null,
102
+ ciRunUrl: null,
103
+ };
104
+ }
105
+ if (env.BUILD_REPOSITORY_NAME || env.TF_BUILD === "True") {
106
+ return {
107
+ provider: "azure",
108
+ repoFullName: env.BUILD_REPOSITORY_NAME ?? null,
109
+ commitSha: env.BUILD_SOURCEVERSION ?? null,
110
+ branch: (env.BUILD_SOURCEBRANCHNAME || env.BUILD_SOURCEBRANCH) ?? null,
111
+ ciRunId: env.BUILD_BUILDID ?? null,
112
+ ciRunUrl: null,
113
+ };
114
+ }
115
+ return {
116
+ provider: null,
117
+ repoFullName: null,
118
+ commitSha: null,
119
+ branch: null,
120
+ ciRunId: null,
121
+ ciRunUrl: null,
122
+ };
123
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@fixsense/cypress-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Cypress plugin that records test outcomes across runs so flaky tests can be identified over time.",
5
+ "license": "MIT",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "README.md",
11
+ "LICENSE"
12
+ ],
13
+ "keywords": [
14
+ "cypress",
15
+ "cypress-plugin",
16
+ "flaky-tests",
17
+ "ci",
18
+ "test-reporting"
19
+ ],
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/CopilotMe/fix-sense.git",
23
+ "directory": "packages/cypress-plugin"
24
+ },
25
+ "homepage": "https://fix-sense.com",
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.json",
28
+ "prepublishOnly": "npm run build"
29
+ },
30
+ "peerDependencies": {
31
+ "cypress": ">=12.0.0"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^20.0.0",
35
+ "typescript": "^5.0.0"
36
+ },
37
+ "engines": {
38
+ "node": ">=18"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ }
43
+ }