explorbot 0.1.9 → 0.1.11

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 (157) hide show
  1. package/README.md +27 -1
  2. package/bin/explorbot-cli.ts +86 -15
  3. package/boat/api-tester/src/ai/curler-tools.ts +3 -3
  4. package/boat/api-tester/src/ai/curler.ts +1 -1
  5. package/boat/api-tester/src/apibot.ts +2 -2
  6. package/boat/api-tester/src/config.ts +1 -1
  7. package/dist/bin/explorbot-cli.js +85 -14
  8. package/dist/boat/api-tester/src/ai/curler-tools.js +2 -2
  9. package/dist/boat/api-tester/src/apibot.js +2 -2
  10. package/dist/package.json +2 -2
  11. package/dist/rules/navigator/output.md +9 -0
  12. package/dist/rules/navigator/verification-actions.md +2 -0
  13. package/dist/src/action-result.js +23 -1
  14. package/dist/src/action.js +46 -38
  15. package/dist/src/ai/bosun.js +16 -2
  16. package/dist/src/ai/conversation.js +39 -0
  17. package/dist/src/ai/experience-compactor.js +235 -50
  18. package/dist/src/ai/historian/codeceptjs.js +109 -0
  19. package/dist/src/ai/historian/experience.js +320 -0
  20. package/dist/src/ai/historian/mixin.js +2 -0
  21. package/dist/src/ai/historian/playwright.js +145 -0
  22. package/dist/src/ai/historian/utils.js +18 -0
  23. package/dist/src/ai/historian.js +19 -398
  24. package/dist/src/ai/navigator.js +133 -80
  25. package/dist/src/ai/pilot.js +254 -13
  26. package/dist/src/ai/planner/subpages.js +1 -30
  27. package/dist/src/ai/planner.js +33 -13
  28. package/dist/src/ai/provider.js +55 -18
  29. package/dist/src/ai/rerunner.js +3 -3
  30. package/dist/src/ai/researcher/deep-analysis.js +1 -1
  31. package/dist/src/ai/researcher/fingerprint-worker.js +1 -1
  32. package/dist/src/ai/researcher/locators.js +1 -1
  33. package/dist/src/ai/researcher/sections.js +8 -1
  34. package/dist/src/ai/researcher.js +43 -41
  35. package/dist/src/ai/rules.js +26 -14
  36. package/dist/src/ai/tester.js +90 -26
  37. package/dist/src/ai/tools.js +18 -10
  38. package/dist/src/api/request-store.js +20 -0
  39. package/dist/src/api/xhr-capture.js +19 -3
  40. package/dist/src/browser-server.js +16 -3
  41. package/dist/src/command-handler.js +1 -1
  42. package/dist/src/commands/add-rule-command.js +12 -9
  43. package/dist/src/commands/base-command.js +20 -0
  44. package/dist/src/commands/clean-command.js +3 -2
  45. package/dist/src/commands/compact-command.js +138 -0
  46. package/dist/src/commands/context-command.js +7 -1
  47. package/dist/src/commands/drill-command.js +4 -1
  48. package/dist/src/commands/experience-command.js +104 -0
  49. package/dist/src/commands/explore-command.js +54 -19
  50. package/dist/src/commands/freesail-command.js +2 -0
  51. package/dist/src/commands/index.js +7 -3
  52. package/dist/src/commands/init-command.js +11 -10
  53. package/dist/src/commands/learn-command.js +1 -1
  54. package/dist/src/commands/navigate-command.js +4 -1
  55. package/dist/src/commands/plan-clear-command.js +4 -1
  56. package/dist/src/commands/plan-command.js +43 -4
  57. package/dist/src/commands/plan-edit-command.js +1 -1
  58. package/dist/src/commands/plan-load-command.js +4 -1
  59. package/dist/src/commands/plan-reload-command.js +4 -1
  60. package/dist/src/commands/plan-save-command.js +20 -8
  61. package/dist/src/commands/rerun-command.js +4 -0
  62. package/dist/src/commands/research-command.js +5 -2
  63. package/dist/src/commands/start-command.js +5 -1
  64. package/dist/src/commands/test-command.js +7 -1
  65. package/dist/src/components/App.js +15 -5
  66. package/dist/src/execution-controller.js +13 -2
  67. package/dist/src/experience-tracker.js +174 -83
  68. package/dist/src/explorbot.js +31 -22
  69. package/dist/src/explorer.js +12 -5
  70. package/dist/src/observability.js +50 -99
  71. package/dist/src/playwright-recorder.js +309 -0
  72. package/dist/src/reporter.js +17 -2
  73. package/dist/src/stats.js +2 -0
  74. package/dist/src/suite.js +1 -1
  75. package/dist/src/test-plan.js +12 -0
  76. package/dist/src/utils/aria.js +37 -1
  77. package/dist/src/utils/error-page.js +30 -7
  78. package/dist/src/utils/logger.js +1 -1
  79. package/dist/src/utils/next-steps.js +37 -0
  80. package/dist/src/utils/rules-loader.js +1 -1
  81. package/dist/src/utils/test-files.js +1 -1
  82. package/dist/src/utils/url-matcher.js +50 -0
  83. package/package.json +2 -2
  84. package/rules/navigator/output.md +9 -0
  85. package/rules/navigator/verification-actions.md +2 -0
  86. package/src/action-result.ts +26 -1
  87. package/src/action.ts +44 -37
  88. package/src/ai/bosun.ts +16 -2
  89. package/src/ai/conversation.ts +37 -0
  90. package/src/ai/experience-compactor.ts +270 -63
  91. package/src/ai/historian/codeceptjs.ts +130 -0
  92. package/src/ai/historian/experience.ts +383 -0
  93. package/src/ai/historian/mixin.ts +4 -0
  94. package/src/ai/historian/playwright.ts +169 -0
  95. package/src/ai/historian/utils.ts +23 -0
  96. package/src/ai/historian.ts +35 -468
  97. package/src/ai/navigator.ts +140 -85
  98. package/src/ai/pilot.ts +259 -14
  99. package/src/ai/planner/subpages.ts +1 -24
  100. package/src/ai/planner.ts +34 -14
  101. package/src/ai/provider.ts +52 -18
  102. package/src/ai/rerunner.ts +3 -3
  103. package/src/ai/researcher/deep-analysis.ts +1 -1
  104. package/src/ai/researcher/fingerprint-worker.ts +1 -1
  105. package/src/ai/researcher/locators.ts +2 -2
  106. package/src/ai/researcher/sections.ts +7 -1
  107. package/src/ai/researcher.ts +47 -42
  108. package/src/ai/rules.ts +27 -14
  109. package/src/ai/task-agent.ts +1 -1
  110. package/src/ai/tester.ts +94 -26
  111. package/src/ai/tools.ts +53 -29
  112. package/src/api/request-store.ts +22 -0
  113. package/src/api/xhr-capture.ts +21 -3
  114. package/src/browser-server.ts +17 -3
  115. package/src/command-handler.ts +1 -1
  116. package/src/commands/add-rule-command.ts +13 -9
  117. package/src/commands/base-command.ts +26 -1
  118. package/src/commands/clean-command.ts +4 -3
  119. package/src/commands/compact-command.ts +156 -0
  120. package/src/commands/context-command.ts +8 -2
  121. package/src/commands/drill-command.ts +5 -2
  122. package/src/commands/experience-command.ts +125 -0
  123. package/src/commands/explore-command.ts +58 -21
  124. package/src/commands/freesail-command.ts +2 -0
  125. package/src/commands/index.ts +7 -3
  126. package/src/commands/init-command.ts +11 -10
  127. package/src/commands/learn-command.ts +2 -2
  128. package/src/commands/navigate-command.ts +5 -2
  129. package/src/commands/plan-clear-command.ts +5 -2
  130. package/src/commands/plan-command.ts +47 -5
  131. package/src/commands/plan-edit-command.ts +2 -2
  132. package/src/commands/plan-load-command.ts +5 -2
  133. package/src/commands/plan-reload-command.ts +5 -2
  134. package/src/commands/plan-save-command.ts +20 -9
  135. package/src/commands/rerun-command.ts +5 -0
  136. package/src/commands/research-command.ts +6 -3
  137. package/src/commands/start-command.ts +6 -2
  138. package/src/commands/test-command.ts +8 -2
  139. package/src/components/App.tsx +16 -5
  140. package/src/config.ts +6 -1
  141. package/src/execution-controller.ts +14 -3
  142. package/src/experience-tracker.ts +198 -100
  143. package/src/explorbot.ts +33 -23
  144. package/src/explorer.ts +14 -5
  145. package/src/observability.ts +50 -109
  146. package/src/playwright-recorder.ts +305 -0
  147. package/src/reporter.ts +17 -3
  148. package/src/stats.ts +4 -0
  149. package/src/suite.ts +1 -1
  150. package/src/test-plan.ts +12 -0
  151. package/src/utils/aria.ts +38 -1
  152. package/src/utils/error-page.ts +32 -7
  153. package/src/utils/logger.ts +1 -1
  154. package/src/utils/next-steps.ts +51 -0
  155. package/src/utils/rules-loader.ts +1 -1
  156. package/src/utils/test-files.ts +1 -1
  157. package/src/utils/url-matcher.ts +43 -0
@@ -1,375 +1,31 @@
1
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import dedent from 'dedent';
4
- import { z } from 'zod';
5
- import { ActionResult } from "../action-result.js";
6
- import { ConfigParser } from "../config.js";
7
- import { KnowledgeTracker } from "../knowledge-tracker.js";
1
+ import { readFileSync, writeFileSync } from 'node:fs';
8
2
  import { ExperienceTracker } from "../experience-tracker.js";
9
- import { Test } from "../test-plan.js";
10
- import { createDebug, tag } from "../utils/logger.js";
11
- import { extractStatePath } from "../utils/url-matcher.js";
12
- import { ASSERTION_TOOLS, CODECEPT_TOOLS } from "./tools.js";
13
- const debugLog = createDebug('explorbot:historian');
14
- export class Historian {
15
- provider;
16
- experienceTracker;
17
- reporter;
18
- stateManager;
19
- savedFiles = new Set();
20
- constructor(provider, experienceTracker, reporter, stateManager) {
3
+ import { tag } from "../utils/logger.js";
4
+ import { relativeToCwd } from "../utils/next-steps.js";
5
+ import { WithCodeceptJS } from "./historian/codeceptjs.js";
6
+ import { WithExperience } from "./historian/experience.js";
7
+ import { WithPlaywright } from "./historian/playwright.js";
8
+ export { isNonReusableCode } from "./historian/utils.js";
9
+ const HistorianBase = WithPlaywright(WithCodeceptJS(WithExperience(Object)));
10
+ export class Historian extends HistorianBase {
11
+ constructor(provider, experienceTracker, reporter, stateManager, config, recorder) {
12
+ super();
21
13
  this.provider = provider;
22
14
  this.experienceTracker = experienceTracker || new ExperienceTracker();
23
15
  this.reporter = reporter;
24
16
  this.stateManager = stateManager;
17
+ this.config = config;
18
+ this.recorder = recorder;
19
+ this.savedFiles = new Set();
20
+ }
21
+ isPlaywrightFramework() {
22
+ return this.config?.ai?.agents?.historian?.framework === 'playwright';
25
23
  }
26
24
  getSavedFiles() {
27
25
  return [...this.savedFiles];
28
26
  }
29
- async saveSession(task, initialState, conversation) {
30
- debugLog('Saving session experience');
31
- const result = this.determineResult(task);
32
- const toolExecutions = conversation.getToolExecutions();
33
- if (task instanceof Test) {
34
- task.generatedCode = this.toCode(conversation, task.description);
35
- }
36
- const steps = await this.extractSteps(toolExecutions);
37
- await this.detectRetryPatterns(toolExecutions, initialState);
38
- const verifiedSteps = await this.verifySteps(steps, initialState);
39
- if (verifiedSteps.length > 0) {
40
- const relatedUrls = this.extractVisitedUrls(toolExecutions, initialState.url || '');
41
- const entry = {
42
- scenario: task.description,
43
- result,
44
- steps: verifiedSteps,
45
- relatedUrls,
46
- };
47
- this.experienceTracker.saveSessionExperience(initialState, entry);
48
- }
49
- if (task instanceof Test && result !== 'failed') {
50
- await this.reportSession(task, steps);
51
- }
52
- tag('substep').log(`Historian saved session for: ${task.description}`);
53
- }
54
- async reportSession(test, steps) {
55
- if (!this.reporter)
56
- return;
57
- const reporterSteps = steps.map((step) => ({
58
- title: step.message,
59
- status: step.status === 'passed' ? 'passed' : 'failed',
60
- code: step.code ? step.code.split('\n').filter((l) => l.trim()) : [],
61
- discovery: step.discovery,
62
- }));
63
- await this.reporter.reportSteps(test, reporterSteps);
64
- }
65
- async extractSteps(toolExecutions) {
66
- const stepsWithDiffs = [];
67
- for (const exec of toolExecutions) {
68
- if (!CODECEPT_TOOLS.includes(exec.toolName))
69
- continue;
70
- if (!exec.output?.code)
71
- continue;
72
- if (!exec.wasSuccessful)
73
- continue;
74
- const message = this.getExecutionLabel(exec, `Executed ${exec.toolName}`);
75
- const ariaDiff = exec.output?.pageDiff?.ariaChanges || null;
76
- const urlChanged = exec.output?.pageDiff?.urlChanged || false;
77
- const step = {
78
- message,
79
- status: 'passed',
80
- tool: exec.toolName,
81
- code: this.stripComments(exec.output.code),
82
- };
83
- stepsWithDiffs.push({ step, ariaDiff, urlChanged });
84
- }
85
- await this.analyzeDiscoveries(stepsWithDiffs);
86
- return stepsWithDiffs.map((s) => s.step);
87
- }
88
- async verifySteps(steps, initialState) {
89
- if (steps.length === 0)
90
- return [];
91
- const existingExperience = this.experienceTracker
92
- .getRelevantExperience(initialState)
93
- .map((e) => e.content)
94
- .filter(Boolean)
95
- .join('\n');
96
- const existingSummary = existingExperience.length > 2000 ? existingExperience.substring(0, 2000) : existingExperience;
97
- const stepsList = steps.map((s, i) => `${i}. ${s.message}\n Code: ${s.code || 'none'}`).join('\n');
98
- const prompt = dedent `
99
- Review these test steps and determine which are valuable to save as experience
100
- for future test executions on this page.
101
-
102
- <steps>
103
- ${stepsList}
104
- </steps>
105
-
106
- ${existingSummary ? `<existing_experience>\n${existingSummary}\n</existing_experience>` : ''}
107
-
108
- For each step, determine if it is useful:
109
- - NOT useful if it uses auto-generated or unstable locators (ember IDs, numeric data-testid, random IDs)
110
- - NOT useful if it is already documented in existing experience
111
- - NOT useful if it requires an unclear precondition that would not be reproducible
112
- - NOT useful if it is trivial navigation (I.amOnPage) without meaningful context
113
- - USEFUL if it demonstrates how to interact with a specific UI component (expand dropdown, fill form, etc)
114
- - USEFUL if it shows a working approach for a common task on this page
115
- `;
116
- const schema = z.object({
117
- steps: z.array(z.object({
118
- stepIndex: z.number(),
119
- useful: z.boolean(),
120
- })),
121
- });
122
- try {
123
- const response = await this.provider.generateObject([
124
- { role: 'system', content: 'Evaluate test steps for experience value. Be selective — only keep steps that teach something reusable.' },
125
- { role: 'user', content: prompt },
126
- ], schema, undefined, { telemetryFunctionId: 'historian.verifySteps' });
127
- const usefulIndices = new Set((response?.object?.steps || []).filter((s) => s.useful).map((s) => s.stepIndex));
128
- const verified = steps.filter((_, i) => usefulIndices.has(i));
129
- debugLog('Verified %d/%d steps as useful', verified.length, steps.length);
130
- return verified;
131
- }
132
- catch (error) {
133
- debugLog('Step verification failed, keeping all steps: %s', error.message);
134
- return steps;
135
- }
136
- }
137
- async detectRetryPatterns(toolExecutions, initialState) {
138
- if (!this.experienceTracker || !this.stateManager)
139
- return;
140
- const failedByTool = new Map();
141
- const candidates = [];
142
- for (const exec of toolExecutions) {
143
- if (!CODECEPT_TOOLS.includes(exec.toolName))
144
- continue;
145
- if (!exec.output?.code)
146
- continue;
147
- if (!exec.wasSuccessful) {
148
- const bucket = failedByTool.get(exec.toolName) || [];
149
- bucket.push(exec);
150
- failedByTool.set(exec.toolName, bucket);
151
- continue;
152
- }
153
- const failed = failedByTool.get(exec.toolName);
154
- if (failed?.length) {
155
- candidates.push({ failed: [...failed], success: exec });
156
- failedByTool.set(exec.toolName, []);
157
- }
158
- }
159
- if (candidates.length === 0)
160
- return;
161
- const prompt = dedent `
162
- Analyze these retry patterns where a tool failed multiple times before succeeding.
163
- For each candidate, determine which failed attempts were trying to do the same thing as the success.
164
-
165
- ${candidates
166
- .map((c, i) => dedent `
167
- Candidate ${i}:
168
- Failed attempts:
169
- ${c.failed.map((f, j) => ` ${j}: ${this.getExecutionLabel(f, f.toolName)} → code: ${f.output?.code}`).join('\n')}
170
- Succeeded:
171
- ${this.getExecutionLabel(c.success, c.success.toolName)} → code: ${c.success.output.code}
172
- `)
173
- .join('\n\n')}
174
-
175
- For each candidate where failures share the same intent as the success:
176
- - candidateIndex: index of the candidate
177
- - failedIndices: which failed attempts share the same intent
178
- - intent: business-focused description of what was being done
179
- - explanation: actionable tip explaining which element works and what to avoid
180
- `;
181
- const schema = z.object({
182
- retryPatterns: z.array(z.object({
183
- candidateIndex: z.number(),
184
- failedIndices: z.array(z.number()),
185
- intent: z.string(),
186
- explanation: z.string(),
187
- })),
188
- });
189
- try {
190
- const response = await this.provider.generateObject([
191
- { role: 'system', content: 'Analyze retry patterns in web testing tool executions. Identify when failed attempts share the same intent as a successful one.' },
192
- { role: 'user', content: prompt },
193
- ], schema);
194
- for (const pattern of response?.object?.retryPatterns || []) {
195
- const candidate = candidates[pattern.candidateIndex];
196
- if (!candidate)
197
- continue;
198
- const url = candidate.success.output?.pageDiff?.currentUrl;
199
- let state = initialState;
200
- if (url && url !== initialState.url) {
201
- const transition = this.stateManager.getLastVisitToPath(url);
202
- if (transition) {
203
- state = ActionResult.fromState(transition.toState);
204
- }
205
- }
206
- await this.experienceTracker.saveSuccessfulResolution(state, pattern.intent, candidate.success.output.code, pattern.explanation);
207
- }
208
- debugLog('Detected %d retry patterns', response?.object?.retryPatterns?.length || 0);
209
- }
210
- catch (error) {
211
- debugLog('Failed to detect retry patterns: %s', error.message);
212
- }
213
- }
214
- async analyzeDiscoveries(stepsWithDiffs) {
215
- if (!stepsWithDiffs.some((s) => s.ariaDiff))
216
- return;
217
- const prompt = this.buildDiscoveryPrompt(stepsWithDiffs);
218
- const schema = z.object({
219
- discoveries: z.array(z.object({
220
- stepNumber: z.number(),
221
- discoveries: z.array(z.string()),
222
- })),
223
- });
224
- try {
225
- const response = await this.provider.generateObject([
226
- { role: 'system', content: 'Analyze test execution steps and identify valuable UI discoveries. Return multiple discoveries per step when multiple new elements appear. Return no discoveries for steps with no meaningful changes.' },
227
- { role: 'user', content: prompt },
228
- ], schema);
229
- for (const { stepNumber, discoveries } of response?.object?.discoveries || []) {
230
- const stepIndex = stepNumber - 1;
231
- if (!stepsWithDiffs[stepIndex])
232
- continue;
233
- if (discoveries.length === 0)
234
- continue;
235
- stepsWithDiffs[stepIndex].step.discovery = discoveries.join('\n');
236
- }
237
- }
238
- catch (error) {
239
- debugLog('Failed to analyze discoveries: %s', error.message);
240
- }
241
- }
242
- buildDiscoveryPrompt(stepsWithDiffs) {
243
- let prompt = dedent `
244
- Review these test steps and their ARIA diffs. Identify new UI elements that appeared
245
- which could be valuable for:
246
- - Deeper testing of this feature
247
- - Related features that can be triggered from this flow
248
-
249
- IMPORTANT:
250
- - Return MULTIPLE discoveries per step when multiple new elements appear (e.g., if 3 buttons appeared, return an array with 3 discoveries for that step)
251
- - Return NO discoveries (empty array) for a step if nothing new appeared or if elements were already discovered in previous steps
252
- - Only include steps that have discoveries
253
-
254
- Steps:
255
- `;
256
- for (let i = 0; i < stepsWithDiffs.length; i++) {
257
- const { step, ariaDiff, urlChanged } = stepsWithDiffs[i];
258
- prompt += `\n\nStep ${i + 1}: ${step.message}`;
259
- if (ariaDiff) {
260
- prompt += `\n${ariaDiff}`;
261
- }
262
- }
263
- prompt += dedent `
264
-
265
- Return discoveries in format:
266
- - stepNumber: which step revealed these elements
267
- - discoveries: array of brief descriptions like ["A new button appeared: Publish To Twitter", "A new input field appeared: Description"]
268
-
269
- Only return elements that are actionable and could lead to new test scenarios.
270
- Ignore generic UI changes (loading spinners, timestamps, etc).
271
- If errors or warnings appeared in the step, include them in the discoveries array.
272
- If multiple buttons, inputs, links, or other actionable elements appeared in the same step, include all of them in the discoveries array.
273
- `;
274
- return prompt;
275
- }
276
- determineResult(task) {
277
- if ('isSuccessful' in task && task.isSuccessful)
278
- return 'success';
279
- if ('hasAchievedAny' in task && task.hasAchievedAny())
280
- return 'partial';
281
- const hasPassedNotes = Object.values(task.notes).some((n) => n.status === 'passed');
282
- if (hasPassedNotes)
283
- return 'partial';
284
- return 'failed';
285
- }
286
- extractVisitedUrls(toolExecutions, initialUrl) {
287
- const urls = new Set();
288
- const initialPath = extractStatePath(initialUrl);
289
- for (const exec of toolExecutions) {
290
- const currentUrl = exec.output?.pageDiff?.currentUrl;
291
- if (!currentUrl)
292
- continue;
293
- const relativePath = extractStatePath(currentUrl);
294
- if (relativePath && relativePath !== initialPath) {
295
- urls.add(relativePath);
296
- }
297
- }
298
- return [...urls];
299
- }
300
- toCode(conversation, scenario) {
301
- const toolExecutions = conversation.getToolExecutions();
302
- const TRACKABLE_TOOLS = [...CODECEPT_TOOLS, ...ASSERTION_TOOLS];
303
- const successfulSteps = toolExecutions.filter((exec) => exec.wasSuccessful && TRACKABLE_TOOLS.includes(exec.toolName) && exec.output?.code);
304
- if (successfulSteps.length === 0) {
305
- return '';
306
- }
307
- const lines = [];
308
- lines.push(`Scenario('${this.escapeString(scenario)}', ({ I }) => {`);
309
- for (const exec of successfulSteps) {
310
- const explanation = this.getExecutionLabel(exec);
311
- if (explanation) {
312
- lines.push('');
313
- lines.push(` Section('${this.escapeString(explanation)}');`);
314
- }
315
- const code = this.stripComments(exec.output.code);
316
- const codeLines = code.includes('\n') ? code.split('\n') : code.split('; ');
317
- for (const codeLine of codeLines) {
318
- const trimmed = codeLine.trim();
319
- if (trimmed) {
320
- lines.push(` ${trimmed}`);
321
- }
322
- }
323
- }
324
- lines.push('});');
325
- return lines.join('\n');
326
- }
327
27
  savePlanToFile(plan) {
328
- const lines = [];
329
- lines.push(`import step, { Section } from 'codeceptjs/steps';`);
330
- lines.push('');
331
- lines.push(`Feature('${this.escapeString(plan.title)}')`);
332
- lines.push('');
333
- const startUrl = plan.url || plan.tests[0]?.startUrl;
334
- if (startUrl) {
335
- lines.push('Before(({ I }) => {');
336
- lines.push(` I.amOnPage('${this.escapeString(startUrl)}');`);
337
- lines.push(...this.getKnowledgeLines(startUrl));
338
- lines.push('});');
339
- lines.push('');
340
- }
341
- for (const test of plan.tests) {
342
- if (test.generatedCode) {
343
- if (test.isSuccessful) {
344
- lines.push(test.generatedCode);
345
- }
346
- else {
347
- lines.push(`// FAILED: ${test.scenario}`);
348
- lines.push(test.generatedCode.replace(/Scenario\(/, 'Scenario.skip('));
349
- }
350
- lines.push('');
351
- continue;
352
- }
353
- lines.push(`Scenario.todo('${this.escapeString(test.scenario)}', ({ I }) => {`);
354
- if (test.plannedSteps.length > 0) {
355
- for (const step of test.plannedSteps) {
356
- lines.push(` // ${step}`);
357
- }
358
- }
359
- else {
360
- lines.push(` // ${test.scenario}`);
361
- }
362
- lines.push('});');
363
- lines.push('');
364
- }
365
- const testsDir = ConfigParser.getInstance().getTestsDir();
366
- mkdirSync(testsDir, { recursive: true });
367
- const filename = plan.title.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase();
368
- const filePath = join(testsDir, `${filename}.js`);
369
- writeFileSync(filePath, lines.join('\n'));
370
- this.savedFiles.add(filePath);
371
- tag('substep').log(`Saved plan tests to: ${filePath}`);
372
- return filePath;
28
+ return this.isPlaywrightFramework() ? this.savePlaywrightPlanToFile(plan) : this.saveCodeceptPlanToFile(plan);
373
29
  }
374
30
  rewriteScenarioInFile(filePath, healedSteps) {
375
31
  let content = readFileSync(filePath, 'utf-8');
@@ -380,41 +36,6 @@ export class Historian {
380
36
  }
381
37
  writeFileSync(filePath, content);
382
38
  this.savedFiles.add(filePath);
383
- tag('substep').log(`Updated test file with healed steps: ${filePath}`);
384
- }
385
- getExecutionLabel(exec, fallback) {
386
- return exec.input?.explanation || exec.input?.assertion || exec.input?.note || fallback || '';
387
- }
388
- escapeString(str) {
389
- return str.replace(/'/g, "\\'").replace(/\n/g, ' ');
390
- }
391
- getKnowledgeLines(url, indent = ' ') {
392
- const knowledgeTracker = new KnowledgeTracker();
393
- const state = new ActionResult({ url });
394
- const { wait, waitForElement, code } = knowledgeTracker.getStateParameters(state, ['wait', 'waitForElement', 'code']);
395
- const lines = [];
396
- if (wait !== undefined) {
397
- lines.push(`${indent}I.wait(${wait});`);
398
- }
399
- if (waitForElement) {
400
- lines.push(`${indent}I.waitForElement(${JSON.stringify(waitForElement)});`);
401
- }
402
- if (code) {
403
- for (const codeLine of code.split('\n')) {
404
- const trimmed = codeLine.trim();
405
- if (trimmed)
406
- lines.push(`${indent}${trimmed}`);
407
- }
408
- }
409
- return lines;
410
- }
411
- stripComments(code) {
412
- return code
413
- .split('\n')
414
- .filter((line) => {
415
- const trimmed = line.trim();
416
- return trimmed && !trimmed.startsWith('//') && !trimmed.startsWith('/*') && !trimmed.startsWith('*');
417
- })
418
- .join('\n');
39
+ tag('substep').log(`Updated test file with healed steps: ${relativeToCwd(filePath)}`);
419
40
  }
420
41
  }