explorbot 0.1.10 → 0.1.12

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