playwright-intelligence-engine 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +229 -229
  2. package/dist/cli/index.d.ts.map +1 -1
  3. package/dist/core/version.d.ts +3 -3
  4. package/dist/index.js +81 -24
  5. package/package.json +76 -76
  6. package/src/authoring/author.ts +81 -81
  7. package/src/authoring/generation-contract.ts +283 -283
  8. package/src/authoring/hybrid-author.ts +115 -115
  9. package/src/authoring/index.ts +7 -7
  10. package/src/authoring/llm-author.ts +282 -282
  11. package/src/authoring/naming/name-plan.ts +28 -28
  12. package/src/authoring/naming/name-planner.ts +339 -339
  13. package/src/authoring/naming/naming-linter.ts +292 -292
  14. package/src/cli/index.ts +1238 -1172
  15. package/src/collectors/git-diff-collector.ts +190 -190
  16. package/src/core/version.ts +25 -25
  17. package/src/diagnostics/diagnostic-report.ts +204 -204
  18. package/src/diagnostics/failure-classifier.ts +701 -701
  19. package/src/evaluation/repository-runner.ts +197 -197
  20. package/src/gate/quality.ts +101 -101
  21. package/src/generator/architecture-generator.ts +582 -582
  22. package/src/generator/assertion-quality-gate.ts +88 -88
  23. package/src/generator/candidate-writer.ts +288 -288
  24. package/src/generator/test-generator.ts +52 -52
  25. package/src/index.ts +107 -107
  26. package/src/intelligence/evidence-bundle.ts +300 -300
  27. package/src/intelligence/generation-agent.ts +561 -561
  28. package/src/intelligence/generation-verifier.ts +1115 -1115
  29. package/src/intelligence/locator-disambiguation-engine.ts +331 -331
  30. package/src/intelligence/project-intelligence.ts +140 -140
  31. package/src/intelligence/repository-profile.ts +796 -796
  32. package/src/intelligence/trace-proposal-workflow.ts +318 -318
  33. package/src/intelligence/workflow-planner.ts +966 -966
  34. package/src/mcp/server.ts +970 -970
  35. package/src/perception/app-model.ts +32 -32
  36. package/src/perception/crawler.ts +263 -263
  37. package/src/perception/index.ts +3 -3
  38. package/src/repair/assertion-hasher.ts +386 -386
  39. package/src/repair/diff-allowlist.ts +612 -612
  40. package/src/repair/intent-validator.ts +761 -761
  41. package/src/repair/repair-planner.ts +467 -467
  42. package/src/repair/statement-patcher.ts +544 -544
  43. package/src/reproduce/interactive-workflow-runner.ts +828 -828
  44. package/src/sandbox/execution-runner.ts +408 -408
  45. package/src/selector/abstention-policy.ts +175 -175
  46. package/src/selector/candidate-extractor.ts +343 -343
  47. package/src/selector/repair-candidate-ranker.ts +92 -92
  48. package/src/selector/selector-scorer.ts +344 -344
@@ -1,408 +1,408 @@
1
- import { spawn, spawnSync } from 'node:child_process';
2
- import path from 'node:path';
3
- import fs from 'node:fs';
4
-
5
- export interface ExecutionOptions {
6
- cwd: string;
7
- args?: string[];
8
- env?: Record<string, string>;
9
- timeoutMs?: number;
10
- }
11
-
12
- export interface ExecutionResult {
13
- exitCode: number;
14
- stdout: string;
15
- stderr: string;
16
- durationMs: number;
17
- timedOut: boolean;
18
- truncated: boolean;
19
- }
20
-
21
- export class ExecutionRunner {
22
- public static readonly MAX_OUTPUT_BYTES = 16 * 1024 * 1024; // 16 MB max byte buffer limit
23
-
24
- private static readonly SAFE_ENV_KEYS = new Set([
25
- 'PATH',
26
- 'Path',
27
- 'PATHEXT',
28
- 'SYSTEMROOT',
29
- 'SystemRoot',
30
- 'SYSTEMDRIVE',
31
- 'SystemDrive',
32
- 'TEMP',
33
- 'TMP',
34
- 'HOMEDRIVE',
35
- 'HOMEPATH',
36
- 'USERPROFILE',
37
- 'APPDATA',
38
- 'LOCALAPPDATA',
39
- 'LANG',
40
- 'LC_ALL',
41
- 'NODE_ENV',
42
- 'TERM',
43
- 'SHELL',
44
- 'PWD',
45
- 'COMSPEC',
46
- 'ComSpec',
47
- 'CI',
48
- 'PW_INTELLIGENCE_REPRODUCE',
49
- 'PLAYWRIGHT_BROWSERS_PATH',
50
- ]);
51
-
52
- private static readonly DANGEROUS_ENV_KEYS = new Set([
53
- 'NODE_OPTIONS',
54
- 'LD_PRELOAD',
55
- 'LD_LIBRARY_PATH',
56
- 'DYLD_INSERT_LIBRARIES',
57
- 'DYLD_LIBRARY_PATH',
58
- 'PERL5OPT',
59
- 'PYTHONPATH',
60
- 'RUBYOPT',
61
- 'BASH_ENV',
62
- 'ENV',
63
- ]);
64
-
65
- private static readonly SIGNAL_MAP: Record<string, number> = {
66
- SIGHUP: 1,
67
- SIGINT: 2,
68
- SIGQUIT: 3,
69
- SIGILL: 4,
70
- SIGTRAP: 5,
71
- SIGABRT: 6,
72
- SIGBUS: 7,
73
- SIGFPE: 8,
74
- SIGKILL: 9,
75
- SIGUSR1: 10,
76
- SIGSEGV: 11,
77
- SIGUSR2: 12,
78
- SIGPIPE: 13,
79
- SIGALRM: 14,
80
- SIGTERM: 15,
81
- };
82
-
83
- /**
84
- * Sanitizes inherited and explicit environment variables (AUDIT-15).
85
- * Strictly filters against SAFE_ENV_KEYS and explicitly blocks dangerous
86
- * interpreter-injection keys like NODE_OPTIONS.
87
- */
88
- public static getSanitizedEnv(explicitEnv?: Record<string, string | undefined>): Record<string, string> {
89
- const sanitized: Record<string, string> = {};
90
-
91
- for (const [key, val] of Object.entries(process.env)) {
92
- if (ExecutionRunner.SAFE_ENV_KEYS.has(key) && val !== undefined) {
93
- sanitized[key] = val;
94
- }
95
- }
96
-
97
- if (explicitEnv) {
98
- for (const [key, val] of Object.entries(explicitEnv)) {
99
- if (val !== undefined) {
100
- const upperKey = key.toUpperCase();
101
- if (ExecutionRunner.DANGEROUS_ENV_KEYS.has(upperKey)) {
102
- // Reject dangerous interpreter override keys
103
- continue;
104
- }
105
- // Allow explicit test variables matching safe prefixes or safe allowlist
106
- if (
107
- ExecutionRunner.SAFE_ENV_KEYS.has(key) ||
108
- key.startsWith('PLAYWRIGHT_') ||
109
- key.startsWith('TEST_') ||
110
- key.startsWith('PW_') ||
111
- key === 'DEBUG' ||
112
- key === 'PORT'
113
- ) {
114
- sanitized[key] = val;
115
- }
116
- }
117
- }
118
- }
119
-
120
- return sanitized;
121
- }
122
-
123
- /**
124
- * Executes a command safely using child_process.spawn with an explicit argument array.
125
- * Eliminates shell injection risks, sanitizes environment, bounds buffer sizes strictly by bytes,
126
- * preserves signal exit codes, and terminates entire process trees upon timeout.
127
- */
128
- public static async run(
129
- command: string,
130
- options: ExecutionOptions
131
- ): Promise<ExecutionResult> {
132
- const args = options.args ?? [];
133
- const timeoutMs = options.timeoutMs ?? 120000; // Default 2 minutes
134
- const startTime = Date.now();
135
-
136
- return new Promise((resolve) => {
137
- let stdoutBytes = 0;
138
- let stderrBytes = 0;
139
- const stdoutChunks: Buffer[] = [];
140
- const stderrChunks: Buffer[] = [];
141
- let timedOut = false;
142
- let truncated = false;
143
-
144
- // On Windows, resolve npx/npm directly via node.exe with bundled CLI scripts to avoid cmd.exe shell injection
145
- const isWindows = process.platform === 'win32';
146
- let executable = command;
147
- let finalArgs = args;
148
-
149
- if (isWindows && (command === 'npx' || command === 'npm')) {
150
- const cliName = command === 'npx' ? 'npx-cli.js' : 'npm-cli.js';
151
- const bundledCli = path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', cliName);
152
- const cmdScript = path.join(path.dirname(process.execPath), `${command}.cmd`);
153
- if (fs.existsSync(bundledCli)) {
154
- executable = process.execPath;
155
- finalArgs = [bundledCli, ...args];
156
- } else if (fs.existsSync(cmdScript)) {
157
- executable = cmdScript;
158
- finalArgs = args;
159
- } else {
160
- executable = `${command}.cmd`;
161
- finalArgs = args;
162
- }
163
- }
164
-
165
- const child = spawn(executable, finalArgs, {
166
- cwd: options.cwd,
167
- env: ExecutionRunner.getSanitizedEnv(options.env),
168
- shell: false,
169
- windowsHide: true,
170
- });
171
-
172
- const timer = setTimeout(() => {
173
- timedOut = true;
174
- if (child.pid) {
175
- if (isWindows) {
176
- try {
177
- spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true });
178
- } catch {
179
- child.kill();
180
- }
181
- } else {
182
- child.kill('SIGTERM');
183
- setTimeout(() => {
184
- try {
185
- child.kill('SIGKILL');
186
- } catch {
187
- // process already dead
188
- }
189
- }, 2000);
190
- }
191
- }
192
- }, timeoutMs);
193
-
194
- child.stdout?.on('data', (chunk: Buffer | string) => {
195
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf-8');
196
- if (stdoutBytes + buf.length <= ExecutionRunner.MAX_OUTPUT_BYTES) {
197
- stdoutChunks.push(buf);
198
- stdoutBytes += buf.length;
199
- } else {
200
- const remaining = ExecutionRunner.MAX_OUTPUT_BYTES - stdoutBytes;
201
- if (remaining > 0) {
202
- stdoutChunks.push(buf.subarray(0, remaining));
203
- stdoutBytes += remaining;
204
- }
205
- truncated = true;
206
- }
207
- });
208
-
209
- child.stderr?.on('data', (chunk: Buffer | string) => {
210
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf-8');
211
- if (stderrBytes + buf.length <= ExecutionRunner.MAX_OUTPUT_BYTES) {
212
- stderrChunks.push(buf);
213
- stderrBytes += buf.length;
214
- } else {
215
- const remaining = ExecutionRunner.MAX_OUTPUT_BYTES - stderrBytes;
216
- if (remaining > 0) {
217
- stderrChunks.push(buf.subarray(0, remaining));
218
- stderrBytes += remaining;
219
- }
220
- truncated = true;
221
- }
222
- });
223
-
224
- child.on('error', (err) => {
225
- clearTimeout(timer);
226
- const stdoutStr = Buffer.concat(stdoutChunks).toString('utf-8');
227
- const stderrStr = Buffer.concat(stderrChunks).toString('utf-8');
228
- resolve({
229
- exitCode: -1,
230
- stdout: stdoutStr,
231
- stderr: stderrStr + `\nProcess error: ${err.message}`,
232
- durationMs: Date.now() - startTime,
233
- timedOut,
234
- truncated,
235
- });
236
- });
237
-
238
- child.on('close', (code, signal) => {
239
- clearTimeout(timer);
240
- // Correct signal-terminated process handling (AUDIT-08): never map code === null to 0
241
- let exitCode: number;
242
- if (code !== null) {
243
- exitCode = code;
244
- } else if (timedOut) {
245
- exitCode = -1;
246
- } else if (signal) {
247
- const sigNum = ExecutionRunner.SIGNAL_MAP[signal] ?? 15;
248
- exitCode = 128 + sigNum;
249
- } else {
250
- exitCode = 1;
251
- }
252
-
253
- const stdoutStr = Buffer.concat(stdoutChunks).toString('utf-8');
254
- const stderrStr = Buffer.concat(stderrChunks).toString('utf-8');
255
-
256
- resolve({
257
- exitCode,
258
- stdout: stdoutStr,
259
- stderr: stderrStr,
260
- durationMs: Date.now() - startTime,
261
- timedOut,
262
- truncated,
263
- });
264
- });
265
- });
266
- }
267
-
268
- /**
269
- * Executes a Playwright test specification via npx in the specified working directory.
270
- * Guarantees process isolation, command sanitization, and true execution proofs.
271
- */
272
- public static async runPlaywrightTest(options: {
273
- cwd: string;
274
- testFilePath: string;
275
- configPath?: string | undefined;
276
- grep?: string | undefined;
277
- timeoutMs?: number | undefined;
278
- env?: Record<string, string> | undefined;
279
- }): Promise<ExecutionResult> {
280
- const relOrNormPath = path.isAbsolute(options.testFilePath)
281
- ? path.relative(options.cwd, options.testFilePath).replace(/\\/g, '/') || options.testFilePath.replace(/\\/g, '/')
282
- : options.testFilePath.replace(/\\/g, '/');
283
- const args = ['playwright', 'test', relOrNormPath, '--reporter=line'];
284
- if (options.configPath) {
285
- args.push('--config', options.configPath);
286
- }
287
- if (options.grep) {
288
- args.push('-g', options.grep);
289
- }
290
- const runnerOptions: ExecutionOptions = {
291
- cwd: options.cwd,
292
- args,
293
- timeoutMs: options.timeoutMs ?? 60000,
294
- };
295
- if (options.env) {
296
- runnerOptions.env = options.env;
297
- }
298
- return ExecutionRunner.run('npx', runnerOptions);
299
- }
300
-
301
- /**
302
- * Computes the two-sided Wilson score confidence interval for binomial success rates.
303
- * Provides mathematically rigorous confidence bounds for flaky test verification.
304
- */
305
- public static computeWilsonScoreInterval(k: number, n: number, confidence = 0.95): WilsonScoreInterval {
306
- if (n <= 0) {
307
- return { lower: 0, upper: 0, center: 0, confidenceLevel: confidence };
308
- }
309
- const z = confidence === 0.99 ? 2.5758 : 1.95996;
310
- const p = Math.max(0, Math.min(1, k / n));
311
- const z2 = z * z;
312
- const denominator = 1 + z2 / n;
313
- const center = (p + z2 / (2 * n)) / denominator;
314
- const margin = (z * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n))) / denominator;
315
-
316
- const lower = Math.max(0, parseFloat(((center - margin) * 100).toFixed(2)));
317
- const upper = Math.min(100, parseFloat(((center + margin) * 100).toFixed(2)));
318
-
319
- return {
320
- lower,
321
- upper,
322
- center: parseFloat((center * 100).toFixed(2)),
323
- confidenceLevel: confidence,
324
- };
325
- }
326
-
327
- /**
328
- * Executes repeated trials of a Playwright test specification to statistically
329
- * evaluate flakiness and measure intent preservation with Wilson confidence intervals.
330
- */
331
- public static async runRepeatedPlaywrightTrials(options: {
332
- cwd: string;
333
- testFilePath: string;
334
- trials: number;
335
- configPath?: string | undefined;
336
- grep?: string | undefined;
337
- timeoutMs?: number | undefined;
338
- env?: Record<string, string> | undefined;
339
- }): Promise<RepeatedExecutionSummary> {
340
- const trialsCount = Math.max(1, options.trials);
341
- const results: ExecutionResult[] = [];
342
- const durations: number[] = [];
343
- let passed = 0;
344
- let failed = 0;
345
- let timedOut = 0;
346
-
347
- for (let i = 0; i < trialsCount; i++) {
348
- const res = await ExecutionRunner.runPlaywrightTest({
349
- cwd: options.cwd,
350
- testFilePath: options.testFilePath,
351
- configPath: options.configPath,
352
- grep: options.grep,
353
- timeoutMs: options.timeoutMs,
354
- env: options.env,
355
- });
356
-
357
- results.push(res);
358
- durations.push(res.durationMs);
359
-
360
- if (res.exitCode === 0) {
361
- passed++;
362
- } else {
363
- failed++;
364
- if (res.timedOut) {
365
- timedOut++;
366
- }
367
- }
368
- }
369
-
370
- const passRatePct = parseFloat(((passed / trialsCount) * 100).toFixed(2));
371
- const isFlaky = passed > 0 && failed > 0;
372
- const wilsonInterval95 = ExecutionRunner.computeWilsonScoreInterval(passed, trialsCount, 0.95);
373
- const averageDurationMs = durations.reduce((acc, d) => acc + d, 0) / durations.length;
374
-
375
- return {
376
- totalTrials: trialsCount,
377
- passedCount: passed,
378
- failedCount: failed,
379
- timedOutCount: timedOut,
380
- passRatePct,
381
- isFlaky,
382
- wilsonInterval95,
383
- averageDurationMs: parseFloat(averageDurationMs.toFixed(2)),
384
- trialDurationsMs: durations,
385
- trials: results,
386
- };
387
- }
388
- }
389
-
390
- export interface WilsonScoreInterval {
391
- lower: number;
392
- upper: number;
393
- center: number;
394
- confidenceLevel: number;
395
- }
396
-
397
- export interface RepeatedExecutionSummary {
398
- totalTrials: number;
399
- passedCount: number;
400
- failedCount: number;
401
- timedOutCount: number;
402
- passRatePct: number;
403
- isFlaky: boolean;
404
- wilsonInterval95: WilsonScoreInterval;
405
- averageDurationMs: number;
406
- trialDurationsMs: number[];
407
- trials: ExecutionResult[];
408
- }
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import path from 'node:path';
3
+ import fs from 'node:fs';
4
+
5
+ export interface ExecutionOptions {
6
+ cwd: string;
7
+ args?: string[];
8
+ env?: Record<string, string>;
9
+ timeoutMs?: number;
10
+ }
11
+
12
+ export interface ExecutionResult {
13
+ exitCode: number;
14
+ stdout: string;
15
+ stderr: string;
16
+ durationMs: number;
17
+ timedOut: boolean;
18
+ truncated: boolean;
19
+ }
20
+
21
+ export class ExecutionRunner {
22
+ public static readonly MAX_OUTPUT_BYTES = 16 * 1024 * 1024; // 16 MB max byte buffer limit
23
+
24
+ private static readonly SAFE_ENV_KEYS = new Set([
25
+ 'PATH',
26
+ 'Path',
27
+ 'PATHEXT',
28
+ 'SYSTEMROOT',
29
+ 'SystemRoot',
30
+ 'SYSTEMDRIVE',
31
+ 'SystemDrive',
32
+ 'TEMP',
33
+ 'TMP',
34
+ 'HOMEDRIVE',
35
+ 'HOMEPATH',
36
+ 'USERPROFILE',
37
+ 'APPDATA',
38
+ 'LOCALAPPDATA',
39
+ 'LANG',
40
+ 'LC_ALL',
41
+ 'NODE_ENV',
42
+ 'TERM',
43
+ 'SHELL',
44
+ 'PWD',
45
+ 'COMSPEC',
46
+ 'ComSpec',
47
+ 'CI',
48
+ 'PW_INTELLIGENCE_REPRODUCE',
49
+ 'PLAYWRIGHT_BROWSERS_PATH',
50
+ ]);
51
+
52
+ private static readonly DANGEROUS_ENV_KEYS = new Set([
53
+ 'NODE_OPTIONS',
54
+ 'LD_PRELOAD',
55
+ 'LD_LIBRARY_PATH',
56
+ 'DYLD_INSERT_LIBRARIES',
57
+ 'DYLD_LIBRARY_PATH',
58
+ 'PERL5OPT',
59
+ 'PYTHONPATH',
60
+ 'RUBYOPT',
61
+ 'BASH_ENV',
62
+ 'ENV',
63
+ ]);
64
+
65
+ private static readonly SIGNAL_MAP: Record<string, number> = {
66
+ SIGHUP: 1,
67
+ SIGINT: 2,
68
+ SIGQUIT: 3,
69
+ SIGILL: 4,
70
+ SIGTRAP: 5,
71
+ SIGABRT: 6,
72
+ SIGBUS: 7,
73
+ SIGFPE: 8,
74
+ SIGKILL: 9,
75
+ SIGUSR1: 10,
76
+ SIGSEGV: 11,
77
+ SIGUSR2: 12,
78
+ SIGPIPE: 13,
79
+ SIGALRM: 14,
80
+ SIGTERM: 15,
81
+ };
82
+
83
+ /**
84
+ * Sanitizes inherited and explicit environment variables (AUDIT-15).
85
+ * Strictly filters against SAFE_ENV_KEYS and explicitly blocks dangerous
86
+ * interpreter-injection keys like NODE_OPTIONS.
87
+ */
88
+ public static getSanitizedEnv(explicitEnv?: Record<string, string | undefined>): Record<string, string> {
89
+ const sanitized: Record<string, string> = {};
90
+
91
+ for (const [key, val] of Object.entries(process.env)) {
92
+ if (ExecutionRunner.SAFE_ENV_KEYS.has(key) && val !== undefined) {
93
+ sanitized[key] = val;
94
+ }
95
+ }
96
+
97
+ if (explicitEnv) {
98
+ for (const [key, val] of Object.entries(explicitEnv)) {
99
+ if (val !== undefined) {
100
+ const upperKey = key.toUpperCase();
101
+ if (ExecutionRunner.DANGEROUS_ENV_KEYS.has(upperKey)) {
102
+ // Reject dangerous interpreter override keys
103
+ continue;
104
+ }
105
+ // Allow explicit test variables matching safe prefixes or safe allowlist
106
+ if (
107
+ ExecutionRunner.SAFE_ENV_KEYS.has(key) ||
108
+ key.startsWith('PLAYWRIGHT_') ||
109
+ key.startsWith('TEST_') ||
110
+ key.startsWith('PW_') ||
111
+ key === 'DEBUG' ||
112
+ key === 'PORT'
113
+ ) {
114
+ sanitized[key] = val;
115
+ }
116
+ }
117
+ }
118
+ }
119
+
120
+ return sanitized;
121
+ }
122
+
123
+ /**
124
+ * Executes a command safely using child_process.spawn with an explicit argument array.
125
+ * Eliminates shell injection risks, sanitizes environment, bounds buffer sizes strictly by bytes,
126
+ * preserves signal exit codes, and terminates entire process trees upon timeout.
127
+ */
128
+ public static async run(
129
+ command: string,
130
+ options: ExecutionOptions
131
+ ): Promise<ExecutionResult> {
132
+ const args = options.args ?? [];
133
+ const timeoutMs = options.timeoutMs ?? 120000; // Default 2 minutes
134
+ const startTime = Date.now();
135
+
136
+ return new Promise((resolve) => {
137
+ let stdoutBytes = 0;
138
+ let stderrBytes = 0;
139
+ const stdoutChunks: Buffer[] = [];
140
+ const stderrChunks: Buffer[] = [];
141
+ let timedOut = false;
142
+ let truncated = false;
143
+
144
+ // On Windows, resolve npx/npm directly via node.exe with bundled CLI scripts to avoid cmd.exe shell injection
145
+ const isWindows = process.platform === 'win32';
146
+ let executable = command;
147
+ let finalArgs = args;
148
+
149
+ if (isWindows && (command === 'npx' || command === 'npm')) {
150
+ const cliName = command === 'npx' ? 'npx-cli.js' : 'npm-cli.js';
151
+ const bundledCli = path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', cliName);
152
+ const cmdScript = path.join(path.dirname(process.execPath), `${command}.cmd`);
153
+ if (fs.existsSync(bundledCli)) {
154
+ executable = process.execPath;
155
+ finalArgs = [bundledCli, ...args];
156
+ } else if (fs.existsSync(cmdScript)) {
157
+ executable = cmdScript;
158
+ finalArgs = args;
159
+ } else {
160
+ executable = `${command}.cmd`;
161
+ finalArgs = args;
162
+ }
163
+ }
164
+
165
+ const child = spawn(executable, finalArgs, {
166
+ cwd: options.cwd,
167
+ env: ExecutionRunner.getSanitizedEnv(options.env),
168
+ shell: false,
169
+ windowsHide: true,
170
+ });
171
+
172
+ const timer = setTimeout(() => {
173
+ timedOut = true;
174
+ if (child.pid) {
175
+ if (isWindows) {
176
+ try {
177
+ spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true });
178
+ } catch {
179
+ child.kill();
180
+ }
181
+ } else {
182
+ child.kill('SIGTERM');
183
+ setTimeout(() => {
184
+ try {
185
+ child.kill('SIGKILL');
186
+ } catch {
187
+ // process already dead
188
+ }
189
+ }, 2000);
190
+ }
191
+ }
192
+ }, timeoutMs);
193
+
194
+ child.stdout?.on('data', (chunk: Buffer | string) => {
195
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf-8');
196
+ if (stdoutBytes + buf.length <= ExecutionRunner.MAX_OUTPUT_BYTES) {
197
+ stdoutChunks.push(buf);
198
+ stdoutBytes += buf.length;
199
+ } else {
200
+ const remaining = ExecutionRunner.MAX_OUTPUT_BYTES - stdoutBytes;
201
+ if (remaining > 0) {
202
+ stdoutChunks.push(buf.subarray(0, remaining));
203
+ stdoutBytes += remaining;
204
+ }
205
+ truncated = true;
206
+ }
207
+ });
208
+
209
+ child.stderr?.on('data', (chunk: Buffer | string) => {
210
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf-8');
211
+ if (stderrBytes + buf.length <= ExecutionRunner.MAX_OUTPUT_BYTES) {
212
+ stderrChunks.push(buf);
213
+ stderrBytes += buf.length;
214
+ } else {
215
+ const remaining = ExecutionRunner.MAX_OUTPUT_BYTES - stderrBytes;
216
+ if (remaining > 0) {
217
+ stderrChunks.push(buf.subarray(0, remaining));
218
+ stderrBytes += remaining;
219
+ }
220
+ truncated = true;
221
+ }
222
+ });
223
+
224
+ child.on('error', (err) => {
225
+ clearTimeout(timer);
226
+ const stdoutStr = Buffer.concat(stdoutChunks).toString('utf-8');
227
+ const stderrStr = Buffer.concat(stderrChunks).toString('utf-8');
228
+ resolve({
229
+ exitCode: -1,
230
+ stdout: stdoutStr,
231
+ stderr: stderrStr + `\nProcess error: ${err.message}`,
232
+ durationMs: Date.now() - startTime,
233
+ timedOut,
234
+ truncated,
235
+ });
236
+ });
237
+
238
+ child.on('close', (code, signal) => {
239
+ clearTimeout(timer);
240
+ // Correct signal-terminated process handling (AUDIT-08): never map code === null to 0
241
+ let exitCode: number;
242
+ if (code !== null) {
243
+ exitCode = code;
244
+ } else if (timedOut) {
245
+ exitCode = -1;
246
+ } else if (signal) {
247
+ const sigNum = ExecutionRunner.SIGNAL_MAP[signal] ?? 15;
248
+ exitCode = 128 + sigNum;
249
+ } else {
250
+ exitCode = 1;
251
+ }
252
+
253
+ const stdoutStr = Buffer.concat(stdoutChunks).toString('utf-8');
254
+ const stderrStr = Buffer.concat(stderrChunks).toString('utf-8');
255
+
256
+ resolve({
257
+ exitCode,
258
+ stdout: stdoutStr,
259
+ stderr: stderrStr,
260
+ durationMs: Date.now() - startTime,
261
+ timedOut,
262
+ truncated,
263
+ });
264
+ });
265
+ });
266
+ }
267
+
268
+ /**
269
+ * Executes a Playwright test specification via npx in the specified working directory.
270
+ * Guarantees process isolation, command sanitization, and true execution proofs.
271
+ */
272
+ public static async runPlaywrightTest(options: {
273
+ cwd: string;
274
+ testFilePath: string;
275
+ configPath?: string | undefined;
276
+ grep?: string | undefined;
277
+ timeoutMs?: number | undefined;
278
+ env?: Record<string, string> | undefined;
279
+ }): Promise<ExecutionResult> {
280
+ const relOrNormPath = path.isAbsolute(options.testFilePath)
281
+ ? path.relative(options.cwd, options.testFilePath).replace(/\\/g, '/') || options.testFilePath.replace(/\\/g, '/')
282
+ : options.testFilePath.replace(/\\/g, '/');
283
+ const args = ['playwright', 'test', relOrNormPath, '--reporter=line'];
284
+ if (options.configPath) {
285
+ args.push('--config', options.configPath);
286
+ }
287
+ if (options.grep) {
288
+ args.push('-g', options.grep);
289
+ }
290
+ const runnerOptions: ExecutionOptions = {
291
+ cwd: options.cwd,
292
+ args,
293
+ timeoutMs: options.timeoutMs ?? 60000,
294
+ };
295
+ if (options.env) {
296
+ runnerOptions.env = options.env;
297
+ }
298
+ return ExecutionRunner.run('npx', runnerOptions);
299
+ }
300
+
301
+ /**
302
+ * Computes the two-sided Wilson score confidence interval for binomial success rates.
303
+ * Provides mathematically rigorous confidence bounds for flaky test verification.
304
+ */
305
+ public static computeWilsonScoreInterval(k: number, n: number, confidence = 0.95): WilsonScoreInterval {
306
+ if (n <= 0) {
307
+ return { lower: 0, upper: 0, center: 0, confidenceLevel: confidence };
308
+ }
309
+ const z = confidence === 0.99 ? 2.5758 : 1.95996;
310
+ const p = Math.max(0, Math.min(1, k / n));
311
+ const z2 = z * z;
312
+ const denominator = 1 + z2 / n;
313
+ const center = (p + z2 / (2 * n)) / denominator;
314
+ const margin = (z * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n))) / denominator;
315
+
316
+ const lower = Math.max(0, parseFloat(((center - margin) * 100).toFixed(2)));
317
+ const upper = Math.min(100, parseFloat(((center + margin) * 100).toFixed(2)));
318
+
319
+ return {
320
+ lower,
321
+ upper,
322
+ center: parseFloat((center * 100).toFixed(2)),
323
+ confidenceLevel: confidence,
324
+ };
325
+ }
326
+
327
+ /**
328
+ * Executes repeated trials of a Playwright test specification to statistically
329
+ * evaluate flakiness and measure intent preservation with Wilson confidence intervals.
330
+ */
331
+ public static async runRepeatedPlaywrightTrials(options: {
332
+ cwd: string;
333
+ testFilePath: string;
334
+ trials: number;
335
+ configPath?: string | undefined;
336
+ grep?: string | undefined;
337
+ timeoutMs?: number | undefined;
338
+ env?: Record<string, string> | undefined;
339
+ }): Promise<RepeatedExecutionSummary> {
340
+ const trialsCount = Math.max(1, options.trials);
341
+ const results: ExecutionResult[] = [];
342
+ const durations: number[] = [];
343
+ let passed = 0;
344
+ let failed = 0;
345
+ let timedOut = 0;
346
+
347
+ for (let i = 0; i < trialsCount; i++) {
348
+ const res = await ExecutionRunner.runPlaywrightTest({
349
+ cwd: options.cwd,
350
+ testFilePath: options.testFilePath,
351
+ configPath: options.configPath,
352
+ grep: options.grep,
353
+ timeoutMs: options.timeoutMs,
354
+ env: options.env,
355
+ });
356
+
357
+ results.push(res);
358
+ durations.push(res.durationMs);
359
+
360
+ if (res.exitCode === 0) {
361
+ passed++;
362
+ } else {
363
+ failed++;
364
+ if (res.timedOut) {
365
+ timedOut++;
366
+ }
367
+ }
368
+ }
369
+
370
+ const passRatePct = parseFloat(((passed / trialsCount) * 100).toFixed(2));
371
+ const isFlaky = passed > 0 && failed > 0;
372
+ const wilsonInterval95 = ExecutionRunner.computeWilsonScoreInterval(passed, trialsCount, 0.95);
373
+ const averageDurationMs = durations.reduce((acc, d) => acc + d, 0) / durations.length;
374
+
375
+ return {
376
+ totalTrials: trialsCount,
377
+ passedCount: passed,
378
+ failedCount: failed,
379
+ timedOutCount: timedOut,
380
+ passRatePct,
381
+ isFlaky,
382
+ wilsonInterval95,
383
+ averageDurationMs: parseFloat(averageDurationMs.toFixed(2)),
384
+ trialDurationsMs: durations,
385
+ trials: results,
386
+ };
387
+ }
388
+ }
389
+
390
+ export interface WilsonScoreInterval {
391
+ lower: number;
392
+ upper: number;
393
+ center: number;
394
+ confidenceLevel: number;
395
+ }
396
+
397
+ export interface RepeatedExecutionSummary {
398
+ totalTrials: number;
399
+ passedCount: number;
400
+ failedCount: number;
401
+ timedOutCount: number;
402
+ passRatePct: number;
403
+ isFlaky: boolean;
404
+ wilsonInterval95: WilsonScoreInterval;
405
+ averageDurationMs: number;
406
+ trialDurationsMs: number[];
407
+ trials: ExecutionResult[];
408
+ }