playwright-smart-test 1.0.7 โ†’ 1.0.9

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
@@ -189,83 +189,103 @@ Generate a starter configuration with `npx playwright-smart-test init` or create
189
189
 
190
190
  ## ๐Ÿ”Œ GitHub Actions CI/CD Integration
191
191
 
192
- Add this step to your Pull Request workflow (`.github/workflows/regression.yml`):
192
+ Add this step to your Pull Request workflow (`.github/workflows/smart-regression.yml`):
193
193
 
194
194
  ```yaml
195
195
  name: Playwright Smart Regression
196
196
 
197
197
  on:
198
198
  pull_request:
199
- branches: [main, master]
199
+ types: [opened, synchronize, reopened]
200
+ push:
201
+ branches: [main]
200
202
 
201
203
  jobs:
202
- test:
204
+ smart-regression:
203
205
  runs-on: ubuntu-latest
206
+ permissions:
207
+ contents: read
208
+ issues: write # Required for posting/updating PR comments
209
+ pull-requests: write # Required for PR comment metadata
210
+
204
211
  steps:
205
- - name: Checkout Repository
212
+ - name: Checkout code
206
213
  uses: actions/checkout@v4
207
214
  with:
208
- fetch-depth: 0 # Full history needed for git diff
215
+ ref: ${{ github.event.pull_request.head.ref || github.ref }}
216
+ fetch-depth: 0 # Full history needed for git diff
217
+
218
+ - name: Fetch target base branch
219
+ if: github.event_name == 'pull_request'
220
+ run: |
221
+ git fetch origin ${{ github.base_ref }}:refs/remotes/origin/${{ github.base_ref }}
209
222
 
210
223
  - name: Setup Node.js
211
224
  uses: actions/setup-node@v4
212
225
  with:
213
- node-version: 20
226
+ node-version: 22
214
227
  cache: 'npm'
215
228
 
216
- - name: Install Dependencies
229
+ - name: Install dependencies
217
230
  run: npm ci
218
231
 
219
- - name: Install Playwright Browsers
220
- run: npx playwright install --with-deps
232
+ - name: Install Playwright Chromium
233
+ run: npx playwright install --with-deps chromium
221
234
 
222
- - name: Run Smart Regression Analysis
223
- id: smart-regression
235
+ - name: Run AI Smart Regression Selection & Targeted E2E Tests
224
236
  env:
225
237
  GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
238
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
226
239
  run: |
227
- npx playwright-smart-test analyze --base "origin/${{ github.base_ref }}" --output pr-report.md
228
- npx playwright-smart-test run --base "origin/${{ github.base_ref }}"
229
-
230
- - name: Post PR Comment
231
- if: always()
232
- uses: thollander/actions-comment-pull-request@v2
233
- with:
234
- filePath: pr-report.md
235
- comment_tag: smart-regression-report
240
+ npx playwright-smart-test run --comment --base "${{ github.event_name == 'pull_request' && format('origin/{0}', github.base_ref) || 'HEAD~1' }}"
236
241
  ```
237
242
 
238
243
  ---
239
244
 
240
245
  ## ๐Ÿ“Š Sample PR Impact Report
241
246
 
242
- When running `playwright-smart-test comment` or saving with `--output`, the agent produces clean GitHub Flavored Markdown:
247
+ When running `playwright-smart-test run --comment` or `playwright-smart-test comment`, the agent automatically posts an interactive analysis report directly to the GitHub Pull Request and GitHub Actions Step Summary:
243
248
 
244
249
  ```markdown
245
250
  ## ๐Ÿค– Playwright Smart Regression Selection Report
246
251
 
247
- **Risk Level:** ๐ŸŸ  **HIGH**
252
+ ### ๐Ÿ“Š Impact & Risk Assessment
248
253
 
249
- | Scope | Identified Areas |
254
+ | Metric | Assessment |
250
255
  | :--- | :--- |
256
+ | **Overall Risk** | ๐ŸŸ  **HIGH** |
257
+ | **Analysis Confidence** | ๐ŸŸข **HIGH** |
251
258
  | **Changed Components** | `checkout`, `payment` |
252
259
  | **Potentially Impacted Areas** | `cart`, `order-summary` |
253
260
 
254
261
  ### ๐Ÿง  AI Semantic Rationale
262
+
255
263
  - **Direct Impact:** Modified voucher code calculation logic in CheckoutPage.
256
264
  - **Ripple Effects:** Discount changes propagate into final payment charge payload.
257
265
 
266
+ <details>
267
+ <summary><b>๐Ÿ“ Modified Files Analyzed (3)</b></summary>
268
+
269
+ | File | Status | Diff Lines |
270
+ | :--- | :---: | :---: |
271
+ | `src/components/Checkout.tsx` | ๐ŸŸก Modified | +24 / -8 |
272
+ | `src/components/Payment.tsx` | ๐ŸŸก Modified | +12 / -3 |
273
+ | `src/types.ts` | ๐ŸŸก Modified | +2 / -0 |
274
+
275
+ </details>
276
+
258
277
  ### ๐Ÿงช Selected Regression Tests (3)
259
278
 
260
279
  | Spec File | Selection Type | Rationale |
261
280
  | :--- | :---: | :--- |
262
- | `tests/checkout.spec.ts` | ๐ŸŸข Direct | Directly touches changed component 'checkout'. |
263
- | `tests/payment.spec.ts` | ๐ŸŸก Ripple | Indirectly impacted by ripple effects on domain 'payment'. |
264
- | `tests/cart.spec.ts` | ๐ŸŸก Ripple | Indirectly impacted by ripple effects on domain 'cart'. |
281
+ | `playwright/e2e/tests/checkout.spec.ts` | ๐ŸŸข Direct | Directly touches changed component 'checkout'. |
282
+ | `playwright/e2e/tests/payment.spec.ts` | ๐ŸŸก Ripple | Indirectly impacted by ripple effects on domain 'payment'. |
283
+ | `playwright/e2e/tests/cart.spec.ts` | ๐ŸŸก Ripple | Indirectly impacted by ripple effects on domain 'cart'. |
265
284
 
266
285
  ### โšก Playwright Execution Command
286
+
267
287
  ```bash
268
- npx playwright test "tests/checkout.spec.ts" "tests/payment.spec.ts" "tests/cart.spec.ts"
288
+ npx playwright test "playwright/e2e/tests/checkout.spec.ts" "playwright/e2e/tests/payment.spec.ts" "playwright/e2e/tests/cart.spec.ts"
269
289
  ```
270
290
  ```
271
291
 
package/dist/cli/index.js CHANGED
@@ -15,7 +15,7 @@ const program = new Command();
15
15
  program
16
16
  .name('playwright-smart-test')
17
17
  .description('AI-Powered Smart Regression Test Selection Agent for Playwright')
18
- .version('1.0.7');
18
+ .version('1.0.9');
19
19
  async function executeAnalysis(options) {
20
20
  const cwd = options.cwd ? path.resolve(options.cwd) : process.cwd();
21
21
  const config = loadConfig(cwd, options.config);
@@ -8,6 +8,8 @@ export declare class GitDiffAnalyzer {
8
8
  private cwd;
9
9
  constructor(cwd?: string);
10
10
  private runGit;
11
+ private sanitizeGitRef;
12
+ private parseRemoteRef;
11
13
  getChangedFiles(options?: DiffOptions): Promise<DiffFile[]>;
12
14
  /**
13
15
  * Parse git diff --numstat output:
@@ -19,14 +19,72 @@ export class GitDiffAnalyzer {
19
19
  throw new Error(`Git command failed [git ${args.join(' ')}]: ${message}`);
20
20
  }
21
21
  }
22
+ sanitizeGitRef(ref) {
23
+ if (!ref) {
24
+ return null;
25
+ }
26
+ const safeRef = ref.trim();
27
+ if (!safeRef || safeRef.includes('\0') || safeRef.includes('\n') || safeRef.includes('\r')) {
28
+ return null;
29
+ }
30
+ if (safeRef.startsWith('-') || safeRef.includes(' ') || safeRef.includes('..')) {
31
+ return null;
32
+ }
33
+ if (safeRef.startsWith('/') || safeRef.endsWith('/')) {
34
+ return null;
35
+ }
36
+ const validPattern = /^(?:HEAD|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*|refs\/(?:heads|remotes|tags)\/[A-Za-z0-9._/-]+)$/;
37
+ if (!validPattern.test(safeRef)) {
38
+ return null;
39
+ }
40
+ return safeRef;
41
+ }
42
+ parseRemoteRef(ref) {
43
+ const safeRef = this.sanitizeGitRef(ref);
44
+ if (!safeRef) {
45
+ return null;
46
+ }
47
+ const match = safeRef.match(/^([A-Za-z0-9._-]+)\/([A-Za-z0-9._/-]+)$/);
48
+ if (!match) {
49
+ return null;
50
+ }
51
+ const remote = match[1];
52
+ const branch = match[2];
53
+ if (!remote || !branch || branch.includes('..') || branch.startsWith('/') || branch.endsWith('/')) {
54
+ return null;
55
+ }
56
+ return { remote, branch };
57
+ }
22
58
  async getChangedFiles(options = {}) {
23
59
  await this.runGit(['rev-parse', '--is-inside-work-tree']);
60
+ const safeBase = this.sanitizeGitRef(options.base);
61
+ const safeHead = this.sanitizeGitRef(options.head) ?? 'HEAD';
62
+ if (safeBase) {
63
+ try {
64
+ await this.runGit(['rev-parse', '--verify', safeBase]);
65
+ }
66
+ catch {
67
+ const remoteRef = this.parseRemoteRef(safeBase) ?? { remote: 'origin', branch: safeBase };
68
+ const { remote, branch } = remoteRef;
69
+ try {
70
+ await this.runGit(['fetch', '--depth=100', remote, `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`]);
71
+ }
72
+ catch {
73
+ try {
74
+ await this.runGit(['fetch', '--depth=100', remote, `+${branch}:refs/remotes/${remote}/${branch}`]);
75
+ }
76
+ catch {
77
+ // Ignore fetch failure and proceed with available refs.
78
+ }
79
+ }
80
+ }
81
+ }
24
82
  let diffRangeArgs;
25
- if (options.base && options.head) {
26
- diffRangeArgs = [`${options.base}...${options.head}`];
83
+ if (safeBase && safeHead) {
84
+ diffRangeArgs = [`${safeBase}...${safeHead}`];
27
85
  }
28
- else if (options.base) {
29
- diffRangeArgs = [options.base];
86
+ else if (safeBase) {
87
+ diffRangeArgs = [safeBase];
30
88
  }
31
89
  else if (options.staged) {
32
90
  diffRangeArgs = ['--cached'];
@@ -34,9 +92,30 @@ export class GitDiffAnalyzer {
34
92
  else {
35
93
  diffRangeArgs = ['HEAD'];
36
94
  }
37
- const numstatOutput = await this.runGit(['diff', '--numstat', ...diffRangeArgs]);
95
+ let numstatOutput;
96
+ try {
97
+ numstatOutput = await this.runGit(['diff', '--numstat', ...diffRangeArgs]);
98
+ }
99
+ catch (diffErr) {
100
+ const fallbackArgs = safeBase ? [safeBase] : ['HEAD'];
101
+ try {
102
+ numstatOutput = await this.runGit(['diff', '--numstat', ...fallbackArgs]);
103
+ diffRangeArgs = fallbackArgs;
104
+ }
105
+ catch (fallbackErr) {
106
+ const diffMessage = diffErr instanceof Error ? diffErr.message : String(diffErr);
107
+ console.warn(`[playwright-smart-test] Warning: git diff failed for [${diffRangeArgs.join(' ')}] and fallback [${fallbackArgs.join(' ')}]: ${diffMessage}`);
108
+ numstatOutput = '';
109
+ }
110
+ }
38
111
  const numstatMap = this.parseNumstat(numstatOutput);
39
- const rawDiff = await this.runGit(['diff', ...diffRangeArgs]);
112
+ let rawDiff;
113
+ try {
114
+ rawDiff = await this.runGit(['diff', ...diffRangeArgs]);
115
+ }
116
+ catch {
117
+ rawDiff = '';
118
+ }
40
119
  const patchesByFile = this.splitPatches(rawDiff);
41
120
  const allPaths = Array.from(new Set([...numstatMap.keys(), ...patchesByFile.keys()]));
42
121
  const files = allPaths.map((filePath) => {
@@ -96,21 +175,18 @@ export class GitDiffAnalyzer {
96
175
  const trimmed = section.trim();
97
176
  if (!trimmed)
98
177
  continue;
99
- // Extract the header line without regex backtracking
100
178
  const newlineIndex = trimmed.indexOf('\n');
101
179
  const headerLine = (newlineIndex === -1 ? trimmed : trimmed.slice(0, newlineIndex)).trim();
102
180
  if (!headerLine.startsWith('diff --git '))
103
181
  continue;
104
- const line = headerLine.slice(11); // Remove 'diff --git '
182
+ const line = headerLine.slice(11);
105
183
  const sepIndex = line.lastIndexOf(' b/');
106
184
  if (sepIndex !== -1) {
107
185
  let filePath = line.slice(sepIndex + 3).trim();
108
- // Fallback for deleted files where b/ is /dev/null
109
186
  if (filePath === '/dev/null' || filePath === 'dev/null') {
110
187
  const aPath = line.slice(0, sepIndex).trim();
111
188
  filePath = aPath.startsWith('a/') ? aPath.slice(2) : aPath;
112
189
  }
113
- // Clean quotes if path was enclosed in quotes by git
114
190
  if (filePath.startsWith('"') && filePath.endsWith('"')) {
115
191
  filePath = filePath.slice(1, -1);
116
192
  }
@@ -2,4 +2,5 @@ import { FinalSelectionResult } from '../config/schema.js';
2
2
  export declare class GitHubReporter {
3
3
  static generateMarkdown(result: FinalSelectionResult): string;
4
4
  private static getRiskBadge;
5
+ private static getConfidenceBadge;
5
6
  }
@@ -1,6 +1,7 @@
1
1
  export class GitHubReporter {
2
2
  static generateMarkdown(result) {
3
3
  const riskBadge = this.getRiskBadge(result.aiAnalysis.riskScore);
4
+ const confidenceBadge = this.getConfidenceBadge(result.aiAnalysis.confidenceScore);
4
5
  const changedBadges = result.changedComponents.length > 0
5
6
  ? result.changedComponents.map((c) => `\`${c}\``).join(', ')
6
7
  : '_None identified_';
@@ -8,7 +9,6 @@ export class GitHubReporter {
8
9
  ? result.impactedComponents.map((c) => `\`${c}\``).join(', ')
9
10
  : '_None_';
10
11
  let markdown = `## ๐Ÿค– Playwright Smart Regression Selection Report\n\n`;
11
- markdown += `**Risk Level:** ${riskBadge}\n\n`;
12
12
  if (result.isFullRegression) {
13
13
  markdown += `> [!WARNING]\n`;
14
14
  markdown += `> **Full Regression Suite Triggered**: ${result.fullRegressionReason || 'Critical configuration or high impact threshold reached.'}\n\n`;
@@ -17,16 +17,35 @@ export class GitHubReporter {
17
17
  markdown += `> [!NOTE]\n`;
18
18
  markdown += `> **Smoke Safety Net Activated**: ${result.smokeFallbackReason}\n\n`;
19
19
  }
20
- markdown += `| Scope | Identified Areas |\n`;
20
+ markdown += `### ๐Ÿ“Š Impact & Risk Assessment\n\n`;
21
+ markdown += `| Metric | Assessment |\n`;
21
22
  markdown += `| :--- | :--- |\n`;
23
+ markdown += `| **Overall Risk** | ${riskBadge} |\n`;
24
+ markdown += `| **Analysis Confidence** | ${confidenceBadge} |\n`;
22
25
  markdown += `| **Changed Components** | ${changedBadges} |\n`;
23
26
  markdown += `| **Potentially Impacted Areas** | ${impactedBadges} |\n\n`;
24
- markdown += `### ๐Ÿง  AI Semantic Rationale\n`;
27
+ markdown += `### ๐Ÿง  AI Semantic Rationale\n\n`;
25
28
  markdown += `- **Direct Impact:** ${result.aiAnalysis.directReason}\n`;
26
29
  if (result.aiAnalysis.rippleEffectReason) {
27
30
  markdown += `- **Ripple Effects:** ${result.aiAnalysis.rippleEffectReason}\n`;
28
31
  }
29
32
  markdown += `\n`;
33
+ if (result.changedFiles && result.changedFiles.length > 0) {
34
+ markdown += `<details>\n<summary><b>๐Ÿ“ Modified Files Analyzed (${result.changedFiles.length})</b></summary>\n\n`;
35
+ markdown += `| File | Status | Diff Lines |\n`;
36
+ markdown += `| :--- | :---: | :---: |\n`;
37
+ for (const file of result.changedFiles) {
38
+ const statusBadge = file.status === 'added'
39
+ ? '๐ŸŸข Added'
40
+ : file.status === 'deleted'
41
+ ? '๐Ÿ”ด Deleted'
42
+ : file.status === 'renamed'
43
+ ? '๐Ÿ”ต Renamed'
44
+ : '๐ŸŸก Modified';
45
+ markdown += `| \`${file.path}\` | ${statusBadge} | +${file.additions} / -${file.deletions} |\n`;
46
+ }
47
+ markdown += `\n</details>\n\n`;
48
+ }
30
49
  markdown += `### ๐Ÿงช Selected Regression Tests (${result.selectedSpecs.length})\n\n`;
31
50
  if (result.selectedSpecs.length === 0) {
32
51
  markdown += `_No tests selected. Changes do not impact any existing test suites._\n\n`;
@@ -51,7 +70,7 @@ export class GitHubReporter {
51
70
  }
52
71
  markdown += `\n`;
53
72
  }
54
- markdown += `### โšก Playwright Execution Command\n`;
73
+ markdown += `### โšก Playwright Execution Command\n\n`;
55
74
  if (result.selectedSpecs.length === 0 && !result.isFullRegression) {
56
75
  markdown += `_No tests executed (0 impacted tests identified)._\n\n`;
57
76
  }
@@ -74,4 +93,15 @@ export class GitHubReporter {
74
93
  return '๐ŸŸข **LOW**';
75
94
  }
76
95
  }
96
+ static getConfidenceBadge(confidence) {
97
+ switch (confidence) {
98
+ case 'HIGH':
99
+ return '๐ŸŸข **HIGH**';
100
+ case 'LOW':
101
+ return '๐Ÿ”ด **LOW**';
102
+ case 'MEDIUM':
103
+ default:
104
+ return '๐ŸŸก **MEDIUM**';
105
+ }
106
+ }
77
107
  }
@@ -12,8 +12,36 @@ export class TestSelector {
12
12
  async selectTests(changedFiles, catalog) {
13
13
  const allKnownSpecs = catalog.map((c) => c.filePath.replace(/\\/g, '/'));
14
14
  const deletedPaths = new Set(changedFiles.filter((f) => f.status === 'deleted').map((f) => f.path.replace(/\\/g, '/')));
15
- // Guardrail 1: Docs & Asset Fast-Path
15
+ // Guardrail 1a: Zero Modified Files
16
+ if (changedFiles.length === 0) {
17
+ return {
18
+ isFullRegression: false,
19
+ fullRegressionReason: undefined,
20
+ changedFiles,
21
+ changedComponents: [],
22
+ impactedComponents: [],
23
+ aiAnalysis: {
24
+ changedComponents: [],
25
+ impactedComponents: [],
26
+ directReason: 'Zero modified files detected against the base branch.',
27
+ rippleEffectReason: 'Working tree is clean and identical to the target branch. No regression test execution required.',
28
+ riskScore: 'LOW',
29
+ requiresFullRegression: false,
30
+ confidenceScore: 'HIGH',
31
+ recommendedTests: [],
32
+ },
33
+ selectedSpecs: [],
34
+ directlyModifiedSpecs: [],
35
+ componentRuleSpecs: [],
36
+ aiRecommendedSpecs: [],
37
+ playwrightCommand: 'npx playwright test',
38
+ };
39
+ }
40
+ // Guardrail 1b: Docs & Asset Fast-Path
16
41
  if (this.isDocsAndAssetsOnly(changedFiles)) {
42
+ const fileNames = changedFiles.map((f) => path.basename(f.path));
43
+ const preview = fileNames.slice(0, 4).join(', ') +
44
+ (fileNames.length > 4 ? ` (+${fileNames.length - 4} more)` : '');
17
45
  return {
18
46
  isFullRegression: false,
19
47
  fullRegressionReason: undefined,
@@ -23,8 +51,8 @@ export class TestSelector {
23
51
  aiAnalysis: {
24
52
  changedComponents: [],
25
53
  impactedComponents: [],
26
- directReason: 'Only documentation, assets, or markdown files modified.',
27
- rippleEffectReason: 'No regression test execution required.',
54
+ directReason: `Verified documentation/non-code changes only (${preview}). Static code analysis confirmed zero application source code, components, or domain logic were altered.`,
55
+ rippleEffectReason: 'Documentation, asset, or metadata changes do not alter runtime UI or application workflows. Safe to skip regression suite.',
28
56
  riskScore: 'LOW',
29
57
  requiresFullRegression: false,
30
58
  confidenceScore: 'HIGH',
@@ -134,7 +162,7 @@ export class TestSelector {
134
162
  }
135
163
  isDocsAndAssetsOnly(changedFiles) {
136
164
  if (changedFiles.length === 0)
137
- return true;
165
+ return false;
138
166
  const docsPatterns = this.config.safetyRules?.docsOnlyPatterns || [
139
167
  '**/*.md',
140
168
  'docs/**',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "playwright-smart-test",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "type": "module",
5
5
  "description": "AI-Powered Smart Regression Test Selection Agent for Playwright",
6
6
  "main": "dist/index.js",
@@ -69,4 +69,4 @@
69
69
  "overrides": {
70
70
  "minimatch": "^11.0.3"
71
71
  }
72
- }
72
+ }