pw-cucumber-triage-agent 0.1.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,147 @@
1
+ # PW Cucumber Triage Agent
2
+
3
+ AI-assisted, rule-based CLI for triaging Playwright + Cucumber failures.
4
+
5
+ ## Quick Start
6
+
7
+ Requirements: Node 18+
8
+
9
+ ```bash
10
+ npm install
11
+ npm run start -- --cucumberJson path/to/cucumber.json --html triage-report.html --out triage-eval.json
12
+ ```
13
+
14
+ ## Typical Usage
15
+
16
+ Basic run:
17
+
18
+ ```bash
19
+ npm run start -- --cucumberJson path/to/cucumber.json
20
+ ```
21
+
22
+ Full run with optional context:
23
+
24
+ ```bash
25
+ npm run start -- \
26
+ --cucumberJson artifacts/cucumber-report.json \
27
+ --console artifacts/console.log \
28
+ --artifacts artifacts/ \
29
+ --repo my-repo \
30
+ --branch main \
31
+ --commit abc123 \
32
+ --workflowUrl "https://github.com/org/repo/actions/runs/123" \
33
+ --env staging \
34
+ --html artifacts/triage-report.html \
35
+ --out artifacts/triage-eval.json
36
+ ```
37
+
38
+ ## Output
39
+
40
+ - category and confidence per failed scenario
41
+ - suggested fixes
42
+ - terminal summary/detail tables
43
+ - Jira drafts (draft-only)
44
+ - HTML report (`--html`)
45
+ - eval JSON (`--out`)
46
+
47
+ ## Use In Other Projects
48
+
49
+ Recommended:
50
+
51
+ ```bash
52
+ npm install --save-dev pw-cucumber-triage-agent
53
+ ```
54
+
55
+ Add script in consumer `package.json`:
56
+
57
+ ```json
58
+ {
59
+ "scripts": {
60
+ "triage:e2e": "pw-triage --cucumberJson artifacts/cucumber-report.json --html artifacts/triage-report.html --out artifacts/triage-eval.json"
61
+ }
62
+ }
63
+ ```
64
+
65
+ Alternatives:
66
+
67
+ - `npx pw-cucumber-triage-agent --cucumberJson path/to/cucumber.json --html triage-report.html`
68
+ - `npx pw-triage --cucumberJson path/to/cucumber.json --html triage-report.html`
69
+ - global install: `npm install -g pw-cucumber-triage-agent`
70
+
71
+ ## CI Snippets
72
+
73
+ GitHub Actions:
74
+
75
+ ```yaml
76
+ - name: Run failure triage
77
+ if: always()
78
+ run: |
79
+ npx pw-triage \
80
+ --cucumberJson artifacts/cucumber-report.json \
81
+ --console artifacts/console.log \
82
+ --artifacts artifacts/ \
83
+ --repo "${{ github.repository }}" \
84
+ --branch "${{ github.ref_name }}" \
85
+ --commit "${{ github.sha }}" \
86
+ --workflowUrl "https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" \
87
+ --html artifacts/triage-report.html \
88
+ --out artifacts/triage-eval.json
89
+ ```
90
+
91
+ Jenkins:
92
+
93
+ ```groovy
94
+ sh '''
95
+ npx pw-triage \
96
+ --cucumberJson artifacts/cucumber-report.json \
97
+ --console artifacts/console.log \
98
+ --artifacts artifacts/ \
99
+ --repo "$JOB_NAME" \
100
+ --branch "$BRANCH_NAME" \
101
+ --commit "$GIT_COMMIT" \
102
+ --workflowUrl "$BUILD_URL" \
103
+ --html artifacts/triage-report.html \
104
+ --out artifacts/triage-eval.json
105
+ '''
106
+ ```
107
+
108
+ ## CLI Options
109
+
110
+ | Option | Description |
111
+ |---|---|
112
+ | `--cucumberJson <path>` | Path to Cucumber JSON report (required) |
113
+ | `--console <path>` | Console log text file |
114
+ | `--artifacts <dir>` | Artifacts folder (screenshots/traces/videos) |
115
+ | `--maxFailures <n>` | Stop after N failures (default `500`) |
116
+ | `--repo <name>` | Repository name |
117
+ | `--workflowUrl <url>` | CI run URL |
118
+ | `--commit <sha>` | Commit SHA |
119
+ | `--branch <name>` | Branch name |
120
+ | `--pr <num>` | Pull request number |
121
+ | `--env <name>` | Environment name |
122
+ | `--baseUrl <url>` | Base URL |
123
+ | `--jiraProject <key>` | Jira project key (default `E2E`) |
124
+ | `--jiraType <type>` | Jira issue type (default `Bug`) |
125
+ | `--approve` | Approval intent flag (still draft-only) |
126
+ | `--out <path>` | Write eval JSON |
127
+ | `--html <path>` | Write HTML report |
128
+
129
+ ## Troubleshooting
130
+
131
+ - `required option '--cucumberJson <path>' not specified`
132
+ Use: `--cucumberJson artifacts/cucumber-report.json`
133
+ - `Cucumber JSON not found`
134
+ Verify path and quote paths with spaces.
135
+ - `pw-triage: command not found`
136
+ Run with `npx pw-triage ...` or install as dev dependency first.
137
+ - `No failed scenarios found in cucumber JSON`
138
+ Confirm you passed the correct cucumber JSON output file.
139
+
140
+ ## Notes
141
+
142
+ - CLI-first package (no programmatic import API yet)
143
+ - Jira submission is draft-only in this version
144
+
145
+ ## License
146
+
147
+ Apache-2.0
@@ -0,0 +1,73 @@
1
+ const PATTERNS = [
2
+ // Env / dependency
3
+ { category: "ENV_DEPENDENCY", weight: 0.35, regex: /\b(503|502|504)\b|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|DNS/i, evidenceKind: "CONSOLE", note: "Network/dependency error pattern" },
4
+ { category: "ENV_DEPENDENCY", weight: 0.25, regex: /\b(timeout|timed out)\b.*\b(connect|request|response)\b/i, evidenceKind: "CONSOLE", note: "Request/connect timeout pattern" },
5
+ // Infra
6
+ { category: "INFRA", weight: 0.35, regex: /browser has disconnected|Target closed|Protocol error|crash|Out of memory|ENOMEM/i, evidenceKind: "STACK", note: "Runner/browser instability pattern" },
7
+ // Timeouts/perf
8
+ { category: "PERFORMANCE_TIMEOUT", weight: 0.40, regex: /Timeout\s*\d*ms exceeded|Test timeout of \d+ms exceeded|waiting for .* timed out/i, evidenceKind: "STACK", note: "Timeout signature" },
9
+ // Test bug (selectors / visibility / brittle assertions)
10
+ { category: "TEST_BUG", weight: 0.40, regex: /strict mode violation|locator\(.+\) resolved to \d+ elements|Element is not attached|not visible|toBeVisible/i, evidenceKind: "STACK", note: "Locator/visibility/assertion brittleness signature" },
11
+ // Product regression candidates (assertion mismatch without locator brittleness signatures)
12
+ { category: "PRODUCT_REGRESSION", weight: 0.30, regex: /expected.+(to equal|to be|to contain)|received:.+expected:|assertionerror|expect\(received\)\./i, evidenceKind: "STACK", note: "Assertion mismatch pattern" },
13
+ // Flake hints (transient/retry wording across runners and logs)
14
+ { category: "FLAKE", weight: 0.30, regex: /\b(flaky|intermittent|transient)\b|retry(?:ing| #?\d+)/i, evidenceKind: "CONSOLE", note: "Flake/retry signature" },
15
+ // Data / auth / state
16
+ { category: "DATA_STATE", weight: 0.35, regex: /already exists|duplicate key|conflict|invalid state|not authorized|401|403/i, evidenceKind: "CONSOLE", note: "Auth/data/state pattern" },
17
+ // Cucumber undefined / ambiguous steps
18
+ { category: "TEST_BUG", weight: 0.35, regex: /Undefined\. Implement with the following snippet|Ambiguous match found/i, evidenceKind: "REPORT", note: "Undefined/ambiguous Cucumber step definition" },
19
+ ];
20
+ function clamp01(n) {
21
+ return Math.max(0, Math.min(1, n));
22
+ }
23
+ export function classifyFailure(textBlob, runFailureCount) {
24
+ const scores = {
25
+ PRODUCT_REGRESSION: 0,
26
+ TEST_BUG: 0,
27
+ FLAKE: 0,
28
+ ENV_DEPENDENCY: 0,
29
+ INFRA: 0,
30
+ PERFORMANCE_TIMEOUT: 0,
31
+ DATA_STATE: 0,
32
+ UNKNOWN: 0
33
+ };
34
+ const evidence = [];
35
+ for (const p of PATTERNS) {
36
+ if (p.regex.test(textBlob)) {
37
+ scores[p.category] += p.weight;
38
+ evidence.push({ kind: p.evidenceKind, message: `${p.note} (${p.regex})` });
39
+ }
40
+ }
41
+ // Many failures at once suggests env/infra issues
42
+ if (runFailureCount >= 8) {
43
+ scores.ENV_DEPENDENCY += 0.15;
44
+ scores.INFRA += 0.15;
45
+ evidence.push({ kind: "HEURISTIC", message: `Many failing scenarios in run (${runFailureCount}) suggests env/infra over isolated failures.` });
46
+ }
47
+ // If this is a pure expectation mismatch (without selector brittleness), bias toward regression.
48
+ if (/expected.+(to equal|to be|to contain)|received:.+expected:|assertionerror|expect\(received\)\./i.test(textBlob) &&
49
+ !/strict mode violation|locator\(.+\) resolved to \d+ elements|Element is not attached|not visible|toBeVisible/i.test(textBlob)) {
50
+ scores.PRODUCT_REGRESSION += 0.2;
51
+ evidence.push({ kind: "HEURISTIC", message: "Expectation mismatch without locator instability is often product behavior drift." });
52
+ }
53
+ const sorted = Object.entries(scores).sort((a, b) => b[1] - a[1]);
54
+ const [topCat, topScore] = sorted[0];
55
+ const secondScore = sorted[1]?.[1] ?? 0;
56
+ // Confidence: combine absolute score + separation gap
57
+ const gap = topScore - secondScore;
58
+ let confidence = clamp01(0.45 * topScore + 0.55 * clamp01(gap + 0.25));
59
+ if (topScore < 0.15) {
60
+ return {
61
+ category: "UNKNOWN",
62
+ confidence: 0.3,
63
+ evidence: [{ kind: "HEURISTIC", message: "No strong pattern matched; needs human triage." }]
64
+ };
65
+ }
66
+ // Assertion mismatch could be a regression; lower confidence slightly and add hint
67
+ if (topCat === "TEST_BUG" && /Expected.*to equal|toContainText|toHaveText/i.test(textBlob) &&
68
+ !/strict mode violation|locator\(.+\) resolved to \d+ elements/i.test(textBlob)) {
69
+ evidence.push({ kind: "HEURISTIC", message: "Assertion mismatch could indicate a product regression; verify expected behavior vs recent changes." });
70
+ confidence = clamp01(confidence - 0.1);
71
+ }
72
+ return { category: topCat, confidence, evidence };
73
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { extractFailuresStreaming } from "./cucumber_stream.js";
6
+ import { indexArtifacts } from "./load_artifacts.js";
7
+ import { triageFailuresPerScenario } from "./triage_per_scenario.js";
8
+ import { renderTable } from "./table.js";
9
+ import { writeEvalRunRecord } from "./eval.js";
10
+ import { parseMaxFailuresOption } from "./cli_options.js";
11
+ import { writeHtmlReport } from "./html_report.js";
12
+ function readTextIfExists(p) {
13
+ if (!p)
14
+ return undefined;
15
+ if (!fs.existsSync(p))
16
+ return undefined;
17
+ return fs.readFileSync(p, "utf-8");
18
+ }
19
+ function categorySummary(records) {
20
+ const total = records.length || 1;
21
+ const counts = new Map();
22
+ for (const r of records)
23
+ counts.set(r.category, (counts.get(r.category) ?? 0) + 1);
24
+ const rows = Array.from(counts.entries())
25
+ .sort((a, b) => b[1] - a[1])
26
+ .map(([cat, n]) => ({ category: cat, count: String(n), pct: `${Math.round((n / total) * 100)}%` }));
27
+ return rows;
28
+ }
29
+ async function main() {
30
+ const program = new Command();
31
+ program
32
+ .name("pw-triage")
33
+ .description("Cucumber JSON + Playwright artifacts failure triage agent (per-scenario categories + tables + Jira draft)")
34
+ .requiredOption("--cucumberJson <path>", "Path to cucumber.json")
35
+ .option("--console <path>", "Path to console log text")
36
+ .option("--artifacts <dir>", "Artifacts directory (screenshots/videos/traces)")
37
+ .option("--maxFailures <n>", "Stop after N failures (default 500)", "500")
38
+ .option("--repo <name>", "Repo name")
39
+ .option("--workflowUrl <url>", "CI run URL")
40
+ .option("--commit <sha>", "Commit SHA")
41
+ .option("--branch <name>", "Branch")
42
+ .option("--pr <num>", "PR number")
43
+ .option("--env <name>", "Environment name")
44
+ .option("--baseUrl <url>", "Base URL")
45
+ .option("--jiraProject <key>", "Jira project key", "E2E")
46
+ .option("--jiraType <type>", "Jira issue type", "Bug")
47
+ .option("--approve", "Human approval gate to allow ticket submission (this project outputs drafts only)", false)
48
+ .option("--out <path>", "Write eval run record JSON to this file")
49
+ .option("--html <path>", "Write business-friendly HTML report to this file")
50
+ .parse(process.argv);
51
+ const opts = program.opts();
52
+ const inputs = {
53
+ cucumberJsonPath: opts.cucumberJson,
54
+ consoleLogPath: opts.console,
55
+ artifactsDir: opts.artifacts,
56
+ runContext: {
57
+ repo: opts.repo,
58
+ workflowUrl: opts.workflowUrl,
59
+ commitSha: opts.commit,
60
+ branch: opts.branch,
61
+ prNumber: opts.pr,
62
+ environment: opts.env,
63
+ baseUrl: opts.baseUrl
64
+ },
65
+ jiraProjectKey: opts.jiraProject,
66
+ jiraIssueType: opts.jiraType,
67
+ approve: Boolean(opts.approve),
68
+ outJsonPath: opts.out,
69
+ htmlOutPath: opts.html
70
+ };
71
+ if (!fs.existsSync(inputs.cucumberJsonPath)) {
72
+ throw new Error(`Cucumber JSON not found: ${inputs.cucumberJsonPath}`);
73
+ }
74
+ const maxFailures = parseMaxFailuresOption(opts.maxFailures, 500);
75
+ const consoleLog = readTextIfExists(inputs.consoleLogPath);
76
+ const artifacts = indexArtifacts(inputs.artifactsDir);
77
+ const failures = await extractFailuresStreaming(inputs.cucumberJsonPath, maxFailures);
78
+ if (!failures.length) {
79
+ console.log("No failed scenarios found in cucumber JSON.");
80
+ process.exit(0);
81
+ }
82
+ const records = triageFailuresPerScenario({
83
+ failures,
84
+ runFailureCount: failures.length,
85
+ consoleLog,
86
+ context: inputs.runContext,
87
+ jiraProjectKey: inputs.jiraProjectKey,
88
+ jiraIssueType: inputs.jiraIssueType,
89
+ artifacts
90
+ });
91
+ console.log("\n=== Failure Categories (Summary) ===");
92
+ console.log(renderTable(categorySummary(records), [
93
+ { key: "category", label: "Category", width: 22 },
94
+ { key: "count", label: "Count", width: 7 },
95
+ { key: "pct", label: "%", width: 6 },
96
+ ]));
97
+ console.log("\n=== Failed Scenarios (Details) ===");
98
+ const detailRows = records.map((r, idx) => ({
99
+ "#": String(idx + 1),
100
+ "Feature": r.feature,
101
+ "Scenario": r.scenario,
102
+ "Step": r.step,
103
+ "Location": r.location,
104
+ "Category": r.category,
105
+ "Conf": `${Math.round(r.confidence * 100)}%`,
106
+ "FP": r.fingerprint,
107
+ "Top error": r.topError
108
+ }));
109
+ console.log(renderTable(detailRows, [
110
+ { key: "#", label: "#", width: 3 },
111
+ { key: "Feature", label: "Feature", width: 18 },
112
+ { key: "Scenario", label: "Scenario", width: 30 },
113
+ { key: "Step", label: "Step", width: 24 },
114
+ { key: "Location", label: "Location", width: 22 },
115
+ { key: "Category", label: "Category", width: 18 },
116
+ { key: "Conf", label: "Conf", width: 6 },
117
+ { key: "FP", label: "FP", width: 10 },
118
+ { key: "Top error", label: "Top error", width: 40 },
119
+ ]));
120
+ console.log("\n=== Suggested Fixes (Top 1 per scenario) ===");
121
+ for (const r of records.slice(0, 15)) {
122
+ console.log(`- [${r.category} ${Math.round(r.confidence * 100)}%] ${r.feature} › ${r.scenario}: ${r.suggestedFix[0] ?? ""}`);
123
+ }
124
+ console.log("\n=== Jira Drafts (JSON) ===");
125
+ const drafts = records.map(r => ({ fingerprint: r.fingerprint, category: r.category, confidence: r.confidence, jiraDraft: r.jiraDraft }));
126
+ console.log(JSON.stringify(drafts, null, 2));
127
+ if (inputs.outJsonPath) {
128
+ writeEvalRunRecord(inputs.outJsonPath, inputs.runContext, records);
129
+ console.log(`\nWrote eval run record: ${path.resolve(inputs.outJsonPath)}`);
130
+ }
131
+ if (inputs.htmlOutPath) {
132
+ writeHtmlReport(inputs.htmlOutPath, records, inputs.runContext);
133
+ console.log(`Wrote HTML report: ${path.resolve(inputs.htmlOutPath)}`);
134
+ }
135
+ if (!inputs.approve) {
136
+ console.log("\nApproval gate: NOT approved. No tickets submitted (drafts only). Re-run with --approve to indicate approval intent.");
137
+ }
138
+ else {
139
+ console.log("\nApproved: submission requested, but this project intentionally outputs drafts only. Wire Jira REST client to create issues.");
140
+ }
141
+ }
142
+ main().catch(err => {
143
+ console.error(err);
144
+ process.exit(1);
145
+ });
@@ -0,0 +1,8 @@
1
+ export function parseMaxFailuresOption(value, fallback = 500) {
2
+ const raw = value ?? fallback;
3
+ const n = typeof raw === "number" ? raw : Number(raw);
4
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1) {
5
+ throw new Error(`Invalid --maxFailures value "${String(value)}". Provide a positive integer.`);
6
+ }
7
+ return n;
8
+ }
@@ -0,0 +1,88 @@
1
+ import fs from "node:fs";
2
+ import streamChain from "stream-chain";
3
+ import streamJson from "stream-json";
4
+ import StreamArray from "stream-json/streamers/StreamArray.js";
5
+ function s(v) {
6
+ return typeof v === "string" ? v : undefined;
7
+ }
8
+ /**
9
+ * Streaming extraction of failed steps from a Cucumber JSON report.
10
+ * Designed for large reports (e.g., 35MB+) without JSON.parse of entire file.
11
+ *
12
+ * Assumes top-level JSON is an array of "feature" objects (common cucumber-json format).
13
+ */
14
+ export async function extractFailuresStreaming(filePath, maxFailures = 500) {
15
+ const failures = [];
16
+ const pipeline = streamChain.chain([
17
+ fs.createReadStream(filePath),
18
+ streamJson.parser(),
19
+ StreamArray.streamArray()
20
+ ]);
21
+ pipeline.on("data", ({ value }) => {
22
+ if (failures.length >= maxFailures) {
23
+ // stop early; likely meltdown
24
+ pipeline.destroy();
25
+ return;
26
+ }
27
+ const featureName = s(value?.name);
28
+ const uri = s(value?.uri) ?? s(value?.path);
29
+ const elements = Array.isArray(value?.elements) ? value.elements : (Array.isArray(value?.scenarios) ? value.scenarios : []);
30
+ for (const el of elements) {
31
+ const scenarioName = s(el?.name) ?? "Unknown scenario";
32
+ const line = typeof el?.line === "number" ? el.line : undefined;
33
+ const steps = Array.isArray(el?.steps) ? el.steps : [];
34
+ for (const st of steps) {
35
+ const result = st?.result ?? st?.match?.result ?? {};
36
+ const status = s(result?.status) ?? s(st?.status) ?? "unknown";
37
+ if (status === "failed" || status === "ambiguous" || status === "undefined") {
38
+ const errorMessage = s(result?.error_message) ?? s(st?.error_message) ?? s(result?.message);
39
+ failures.push({
40
+ featureName,
41
+ scenarioName,
42
+ uri,
43
+ line,
44
+ stepName: s(st?.name),
45
+ stepKeyword: s(st?.keyword),
46
+ status,
47
+ durationNs: typeof result?.duration === "number" ? result.duration : undefined,
48
+ errorMessage
49
+ });
50
+ if (failures.length >= maxFailures) {
51
+ pipeline.destroy();
52
+ return;
53
+ }
54
+ }
55
+ }
56
+ }
57
+ });
58
+ return await new Promise((resolve, reject) => {
59
+ let settled = false;
60
+ const resolveOnce = () => {
61
+ if (settled)
62
+ return;
63
+ settled = true;
64
+ resolve(dedupe(failures));
65
+ };
66
+ const rejectOnce = (err) => {
67
+ if (settled)
68
+ return;
69
+ settled = true;
70
+ reject(err);
71
+ };
72
+ pipeline.on("end", resolveOnce);
73
+ pipeline.on("error", rejectOnce);
74
+ pipeline.on("close", resolveOnce); // in case we destroy early
75
+ });
76
+ }
77
+ function dedupe(items) {
78
+ const seen = new Set();
79
+ const out = [];
80
+ for (const f of items) {
81
+ const key = `${f.uri ?? ""}:${f.line ?? ""}:${f.scenarioName}:${f.stepName ?? ""}:${(f.errorMessage ?? "").split("\n")[0]}`;
82
+ if (seen.has(key))
83
+ continue;
84
+ seen.add(key);
85
+ out.push(f);
86
+ }
87
+ return out;
88
+ }