@fliwright/tdd 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/dist/baseline/AppCapabilityResetAdapter.d.ts +6 -0
  4. package/dist/baseline/AppCapabilityResetAdapter.js +41 -0
  5. package/dist/baseline/BaselineManager.d.ts +67 -0
  6. package/dist/baseline/BaselineManager.js +145 -0
  7. package/dist/baseline/StorageResetAdapter.d.ts +19 -0
  8. package/dist/baseline/StorageResetAdapter.js +43 -0
  9. package/dist/daemon/DaemonTransport.d.ts +37 -0
  10. package/dist/daemon/DaemonTransport.js +1 -0
  11. package/dist/daemon/FlutterDaemonController.d.ts +19 -0
  12. package/dist/daemon/FlutterDaemonController.js +109 -0
  13. package/dist/daemon/FlutterDaemonEndpointSource.d.ts +23 -0
  14. package/dist/daemon/FlutterDaemonEndpointSource.js +37 -0
  15. package/dist/daemon/ReloadStrategy.d.ts +28 -0
  16. package/dist/daemon/ReloadStrategy.js +72 -0
  17. package/dist/daemon/SubprocessDaemonTransport.d.ts +29 -0
  18. package/dist/daemon/SubprocessDaemonTransport.js +155 -0
  19. package/dist/devassist/DevAssistCoordinator.d.ts +74 -0
  20. package/dist/devassist/DevAssistCoordinator.js +388 -0
  21. package/dist/diagnostics/TddFailureContext.d.ts +56 -0
  22. package/dist/diagnostics/TddFailureContext.js +220 -0
  23. package/dist/executor/FocusedRerunRecipe.d.ts +7 -0
  24. package/dist/executor/FocusedRerunRecipe.js +57 -0
  25. package/dist/executor/PersistentTestExecutor.d.ts +59 -0
  26. package/dist/executor/PersistentTestExecutor.js +242 -0
  27. package/dist/executor/ResultReporter.d.ts +23 -0
  28. package/dist/executor/ResultReporter.js +50 -0
  29. package/dist/generator/RedFirstTestGenerator.d.ts +32 -0
  30. package/dist/generator/RedFirstTestGenerator.js +189 -0
  31. package/dist/index.d.ts +36 -0
  32. package/dist/index.js +20 -0
  33. package/dist/repair/TddRepairPlanner.d.ts +54 -0
  34. package/dist/repair/TddRepairPlanner.js +132 -0
  35. package/dist/runtime/TddRuntime.d.ts +87 -0
  36. package/dist/runtime/TddRuntime.js +589 -0
  37. package/dist/selectors/SelectorSynthesizer.d.ts +34 -0
  38. package/dist/selectors/SelectorSynthesizer.js +174 -0
  39. package/dist/spec/InteractionSpec.d.ts +94 -0
  40. package/dist/spec/InteractionSpec.js +236 -0
  41. package/dist/spec/InteractionSpecCoverage.d.ts +17 -0
  42. package/dist/spec/InteractionSpecCoverage.js +69 -0
  43. package/dist/types.d.ts +314 -0
  44. package/dist/types.js +2 -0
  45. package/dist/workflow/RedFirstWorkflow.d.ts +28 -0
  46. package/dist/workflow/RedFirstWorkflow.js +33 -0
  47. package/package.json +42 -3
@@ -0,0 +1,388 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { readFile, mkdir, writeFile } from 'node:fs/promises';
3
+ import { join, resolve } from 'node:path';
4
+ import { promisify } from 'node:util';
5
+ import { execFile } from 'node:child_process';
6
+ import { AiRuntime, DevAssistTraceStore, PassiveAgent, TimelineRecorder, buildChangeSetSnapshot, } from '@fliwright/core';
7
+ import { generateRedFirstTest } from '../generator/RedFirstTestGenerator.js';
8
+ import { validateInteractionSpec } from '../spec/InteractionSpec.js';
9
+ const execFileAsync = promisify(execFile);
10
+ export class DevAssistCoordinator {
11
+ deps;
12
+ cwd;
13
+ traceStore;
14
+ now;
15
+ constructor(deps = {}) {
16
+ this.deps = deps;
17
+ this.cwd = resolve(deps.cwd ?? process.cwd());
18
+ this.traceStore = deps.traceStore ?? new DevAssistTraceStore({ root: join(this.cwd, '.fliwright', 'devassist') });
19
+ this.now = deps.now ?? (() => new Date());
20
+ }
21
+ async cycle(input = {}) {
22
+ const action = input.action ?? (input.devAssistSessionId ? 'continue' : 'start');
23
+ if (action === 'start')
24
+ return await this.start(input);
25
+ if (!input.devAssistSessionId) {
26
+ return { status: 'blocked', reason: `DevAssist action '${action}' requires devAssistSessionId.` };
27
+ }
28
+ return await this.resume(input, action);
29
+ }
30
+ async start(input) {
31
+ if (!this.deps.runtime) {
32
+ return { status: 'blocked', reason: 'Start the persistent TDD runtime before running a DevAssist cycle.' };
33
+ }
34
+ const changeSet = await this.captureChangeSet(input);
35
+ const sessionId = this.deps.createSessionId?.() ?? randomUUID();
36
+ return await this.generateAndRun({ input, changeSet, sessionId });
37
+ }
38
+ async resume(input, action) {
39
+ if (!this.deps.runtime) {
40
+ return { status: 'blocked', reason: 'Start the persistent TDD runtime before running a DevAssist cycle.' };
41
+ }
42
+ let trace;
43
+ try {
44
+ trace = await this.traceStore.read(input.devAssistSessionId);
45
+ }
46
+ catch {
47
+ return { status: 'blocked', reason: `DevAssist session '${input.devAssistSessionId}' was not found.` };
48
+ }
49
+ const changeSet = await this.captureChangeSet(input);
50
+ if (action === 'regenerate') {
51
+ if (trace.cycles.at(-1)?.status !== 'needs_regeneration') {
52
+ return {
53
+ status: 'needs_review',
54
+ devAssistSessionId: trace.devAssistSessionId,
55
+ candidateTestPath: trace.candidate.path,
56
+ changeSet,
57
+ reason: 'Regeneration is available only after the candidate becomes invalid.',
58
+ };
59
+ }
60
+ return await this.generateAndRun({
61
+ input: { ...input, request: trace.request },
62
+ changeSet,
63
+ sessionId: trace.devAssistSessionId,
64
+ previousTrace: trace,
65
+ });
66
+ }
67
+ const candidatePath = trace.candidate.path;
68
+ const candidateSource = await readFile(candidatePath, 'utf8').catch(() => undefined);
69
+ if (!candidateSource || hash(candidateSource) !== trace.candidate.hash) {
70
+ return await this.persistNeedsRegeneration(trace, changeSet, 'The generated candidate changed or is missing. Regenerate explicitly to replace its test intent.');
71
+ }
72
+ return await this.runCandidate(trace, changeSet);
73
+ }
74
+ async generateAndRun(options) {
75
+ const inference = await this.infer({ request: options.input.request, changeSet: options.changeSet });
76
+ const validation = validateInteractionSpec(inference.spec);
77
+ const candidatePath = join(this.cwd, '.fliwright', 'generated', `${options.sessionId}.test.ts`);
78
+ const now = this.now().toISOString();
79
+ if (!validation.ok) {
80
+ const trace = this.newTrace(options, inference, {
81
+ path: candidatePath,
82
+ hash: '',
83
+ testName: inference.testName,
84
+ validation: { eligible: false, reason: validation.issues.map((issue) => `${issue.path} ${issue.message}`).join('; ') },
85
+ }, now);
86
+ const devAssistTracePath = await this.traceStore.write(trace);
87
+ return {
88
+ status: 'needs_review',
89
+ devAssistSessionId: options.sessionId,
90
+ devAssistTracePath,
91
+ candidateTestPath: candidatePath,
92
+ changeSet: options.changeSet,
93
+ reason: trace.candidate.validation.reason,
94
+ };
95
+ }
96
+ if (!hasSupportedAssertion(validation.spec)) {
97
+ const trace = this.newTrace(options, inference, {
98
+ path: candidatePath,
99
+ hash: '',
100
+ testName: inference.testName,
101
+ validation: { eligible: false, reason: 'The inferred candidate has no supported assertion.' },
102
+ }, now);
103
+ const devAssistTracePath = await this.traceStore.write(trace);
104
+ return {
105
+ status: 'needs_review',
106
+ devAssistSessionId: options.sessionId,
107
+ devAssistTracePath,
108
+ candidateTestPath: candidatePath,
109
+ changeSet: options.changeSet,
110
+ reason: trace.candidate.validation.reason,
111
+ };
112
+ }
113
+ const rendered = generateRedFirstTest(validation.spec, { testName: inference.testName });
114
+ if (rendered.warnings.length > 0) {
115
+ const trace = this.newTrace(options, inference, {
116
+ path: candidatePath,
117
+ hash: '',
118
+ testName: inference.testName,
119
+ validation: { eligible: false, reason: rendered.warnings.join(' ') },
120
+ }, now);
121
+ const devAssistTracePath = await this.traceStore.write(trace);
122
+ return {
123
+ status: 'needs_review',
124
+ devAssistSessionId: options.sessionId,
125
+ devAssistTracePath,
126
+ candidateTestPath: candidatePath,
127
+ changeSet: options.changeSet,
128
+ reason: trace.candidate.validation.reason,
129
+ };
130
+ }
131
+ await mkdir(join(candidatePath, '..'), { recursive: true });
132
+ await writeFile(candidatePath, rendered.testCode, 'utf8');
133
+ const trace = this.newTrace(options, inference, {
134
+ path: candidatePath,
135
+ hash: hash(rendered.testCode),
136
+ testName: rendered.testName,
137
+ validation: { eligible: true },
138
+ }, now);
139
+ return await this.runCandidate(trace, options.changeSet);
140
+ }
141
+ newTrace(options, inference, candidate, now) {
142
+ return {
143
+ version: 1,
144
+ devAssistSessionId: options.sessionId,
145
+ ...(options.input.request ? { request: options.input.request } : options.previousTrace?.request ? { request: options.previousTrace.request } : {}),
146
+ changeSets: [...(options.previousTrace?.changeSets ?? []), options.changeSet],
147
+ inference: {
148
+ promptTemplateVersion: 'devassist-v1',
149
+ provider: inference.provider ?? 'configured-ai',
150
+ ...(inference.model ? { model: inference.model } : {}),
151
+ evidence: {
152
+ changeFiles: options.changeSet.files.map((file) => file.path),
153
+ validation: candidate.validation,
154
+ },
155
+ },
156
+ candidate,
157
+ cycles: [...(options.previousTrace?.cycles ?? [])],
158
+ createdAt: options.previousTrace?.createdAt ?? now,
159
+ updatedAt: now,
160
+ };
161
+ }
162
+ async runCandidate(trace, changeSet) {
163
+ const runtime = this.deps.runtime;
164
+ await runtime.focus(trace.candidate.path, trace.candidate.testName);
165
+ const cycle = await runtime.cycle(trace.candidate.testName, {
166
+ sync: 'auto',
167
+ changes: changeSet.files.map((file) => file.path),
168
+ autoEscalate: true,
169
+ });
170
+ const diagnosis = cycle.status === 'red' ? await this.diagnose(cycle) : undefined;
171
+ const timelinePath = cycle.timelinePath ?? cycle.failureContext?.artifacts?.timelinePath;
172
+ const timelineNodeId = cycle.timelineNodeId ?? cycle.failureContext?.artifacts?.timelineNodeId;
173
+ const candidateInvalid = cycle.failureContext?.kind === 'test-error';
174
+ const status = candidateInvalid ? 'needs_regeneration' : cycle.status;
175
+ const artifacts = artifactReferences(cycle);
176
+ const nextTrace = {
177
+ ...trace,
178
+ changeSets: trace.changeSets.at(-1)?.hash === changeSet.hash ? trace.changeSets : [...trace.changeSets, changeSet],
179
+ cycles: [...trace.cycles, {
180
+ changeSet,
181
+ status,
182
+ sync: { decision: cycle.lastSync, ...(cycle.syncEscalated ? { escalation: true } : {}) },
183
+ ...(timelinePath ? { timelinePath } : {}),
184
+ ...(timelineNodeId ? { timelineNodeId } : {}),
185
+ ...(artifacts.length > 0 ? { artifacts } : {}),
186
+ ...(diagnosis ? { diagnosis: diagnosisReference(diagnosis) } : {}),
187
+ ...(cycle.failure?.message ? { reason: cycle.failure.message } : {}),
188
+ completedAt: this.now().toISOString(),
189
+ }],
190
+ updatedAt: this.now().toISOString(),
191
+ };
192
+ const devAssistTracePath = await this.traceStore.write(nextTrace);
193
+ return {
194
+ status,
195
+ devAssistSessionId: trace.devAssistSessionId,
196
+ devAssistTracePath,
197
+ candidateTestPath: trace.candidate.path,
198
+ changeSet,
199
+ sync: { decision: cycle.lastSync, ...(cycle.syncEscalated ? { escalation: true } : {}) },
200
+ ...(timelinePath ? { timelinePath } : {}),
201
+ ...(timelineNodeId ? { timelineNodeId } : {}),
202
+ ...(artifacts.length > 0 ? { artifacts } : {}),
203
+ ...(diagnosis ? { diagnosis } : {}),
204
+ nextCall: candidateInvalid
205
+ ? { action: 'regenerate', devAssistSessionId: trace.devAssistSessionId }
206
+ : { action: 'continue', devAssistSessionId: trace.devAssistSessionId },
207
+ };
208
+ }
209
+ async persistNeedsRegeneration(trace, changeSet, reason) {
210
+ const updated = {
211
+ ...trace,
212
+ changeSets: [...trace.changeSets, changeSet],
213
+ cycles: [...trace.cycles, {
214
+ changeSet,
215
+ status: 'needs_regeneration',
216
+ sync: { decision: 'none' },
217
+ reason,
218
+ completedAt: this.now().toISOString(),
219
+ }],
220
+ updatedAt: this.now().toISOString(),
221
+ };
222
+ const devAssistTracePath = await this.traceStore.write(updated);
223
+ return {
224
+ status: 'needs_regeneration',
225
+ devAssistSessionId: trace.devAssistSessionId,
226
+ devAssistTracePath,
227
+ candidateTestPath: trace.candidate.path,
228
+ changeSet,
229
+ sync: { decision: 'none' },
230
+ reason,
231
+ nextCall: { action: 'regenerate', devAssistSessionId: trace.devAssistSessionId },
232
+ };
233
+ }
234
+ async infer(input) {
235
+ if (this.deps.infer)
236
+ return await this.deps.infer(input);
237
+ const aiRuntime = this.deps.aiRuntime ?? new AiRuntime();
238
+ const result = await aiRuntime.generate({
239
+ prompt: [
240
+ 'Produce one Fliwright DevAssist candidate as JSON.',
241
+ 'Use only supported InteractionSpec actions and assertions. The candidate must contain an observable assertion and must not authorize side effects.',
242
+ `Developer request: ${input.request ?? 'Infer one focused behavior from the changed files.'}`,
243
+ `Change set: ${JSON.stringify({ baseRevision: input.changeSet.baseRevision, files: input.changeSet.files.map((file) => file.path) })}`,
244
+ ].join('\n'),
245
+ schema: inferenceSchema,
246
+ });
247
+ return result;
248
+ }
249
+ async diagnose(cycle) {
250
+ if (this.deps.diagnose)
251
+ return await this.deps.diagnose(cycle);
252
+ const failure = toAgentVisibleFailure(cycle);
253
+ if (!failure)
254
+ return undefined;
255
+ try {
256
+ const passiveAgent = new PassiveAgent({
257
+ aiRuntime: this.deps.aiRuntime ?? new AiRuntime(),
258
+ recorder: new TimelineRecorder({ runId: `devassist-${Date.now()}`, testName: cycle.testName ?? 'DevAssist candidate' }),
259
+ passive: true,
260
+ });
261
+ return (await passiveAgent.diagnose(failure, {
262
+ allowedTools: ['fliwright artifacts timeline', 'fliwright app snapshot', 'fliwright app observe'],
263
+ screenshotPath: cycle.failureContext?.artifacts?.screenshotPath,
264
+ snapshotPath: cycle.failureContext?.artifacts?.timelinePath,
265
+ })) ?? undefined;
266
+ }
267
+ catch {
268
+ return undefined;
269
+ }
270
+ }
271
+ async captureChangeSet(input) {
272
+ if (this.deps.changeSetProvider)
273
+ return await this.deps.changeSetProvider(input);
274
+ const files = input.files
275
+ ? input.files.map((path) => ({ path, status: 'modified' }))
276
+ : await changedFiles(this.cwd);
277
+ const snapshots = await Promise.all(files.map(async (file) => {
278
+ const content = await readFile(resolve(this.cwd, file.path), 'utf8').catch(() => undefined);
279
+ return {
280
+ path: file.path,
281
+ status: content === undefined ? 'deleted' : file.status,
282
+ content,
283
+ };
284
+ }));
285
+ return buildChangeSetSnapshot({
286
+ baseRevision: input.baseRevision ?? await currentRevision(this.cwd),
287
+ files: snapshots,
288
+ });
289
+ }
290
+ }
291
+ const inferenceSchema = {
292
+ type: 'object',
293
+ properties: {
294
+ testName: { type: 'string' },
295
+ provider: { type: 'string' },
296
+ model: { type: 'string' },
297
+ spec: { type: 'object' },
298
+ },
299
+ required: ['testName', 'spec'],
300
+ };
301
+ async function changedFiles(cwd) {
302
+ try {
303
+ const { stdout } = await execFileAsync('git', ['status', '--porcelain=v1', '-z'], { cwd });
304
+ const records = stdout.split('\0').filter(Boolean);
305
+ const files = [];
306
+ for (let index = 0; index < records.length; index += 1) {
307
+ const record = records[index];
308
+ if (record.length <= 3)
309
+ continue;
310
+ const marker = record.slice(0, 2);
311
+ files.push({ path: record.slice(3), status: statusFromPorcelain(marker) });
312
+ if (marker.includes('R') || marker.includes('C'))
313
+ index += 1;
314
+ }
315
+ return files
316
+ .filter((file, index, candidates) => candidates.findIndex((candidate) => candidate.path === file.path) === index)
317
+ .sort((left, right) => left.path.localeCompare(right.path));
318
+ }
319
+ catch {
320
+ return [];
321
+ }
322
+ }
323
+ async function currentRevision(cwd) {
324
+ try {
325
+ const { stdout } = await execFileAsync('git', ['rev-parse', 'HEAD'], { cwd });
326
+ return stdout.trim() || undefined;
327
+ }
328
+ catch {
329
+ return undefined;
330
+ }
331
+ }
332
+ function hash(value) {
333
+ return createHash('sha256').update(value).digest('hex');
334
+ }
335
+ function statusFromPorcelain(marker) {
336
+ if (marker === '??')
337
+ return 'untracked';
338
+ if (marker.includes('D'))
339
+ return 'deleted';
340
+ if (marker.includes('A') || marker.includes('C'))
341
+ return 'added';
342
+ return 'modified';
343
+ }
344
+ function hasSupportedAssertion(spec) {
345
+ return Boolean(spec.assertions?.length) || spec.flows.some((flow) => Boolean(flow.expectedOutcome?.length));
346
+ }
347
+ function diagnosisReference(diagnosis) {
348
+ return {
349
+ summary: diagnosis.summary,
350
+ rootCause: diagnosis.rootCause,
351
+ suggestedActions: [...diagnosis.suggestedActions],
352
+ confidence: diagnosis.confidence,
353
+ };
354
+ }
355
+ function artifactReferences(cycle) {
356
+ const artifacts = cycle.failureContext?.artifacts;
357
+ return [
358
+ cycle.timelinePath ?? artifacts?.timelinePath ? { kind: 'trace', path: cycle.timelinePath ?? artifacts.timelinePath } : undefined,
359
+ artifacts?.failureContextPath ? { kind: 'diagnostics', path: artifacts.failureContextPath } : undefined,
360
+ artifacts?.screenshotPath ? { kind: 'screenshot', path: artifacts.screenshotPath } : undefined,
361
+ ].filter((artifact) => Boolean(artifact));
362
+ }
363
+ function toAgentVisibleFailure(cycle) {
364
+ const context = cycle.failureContext;
365
+ if (!context)
366
+ return undefined;
367
+ const codeByKind = {
368
+ 'missing-element': 'selector_not_found',
369
+ 'ambiguous-element': 'actionability_failed',
370
+ 'wrong-text': 'assertion_failed',
371
+ 'navigation-failed': 'navigation_failed',
372
+ 'mock-not-called': 'assertion_failed',
373
+ 'state-mismatch': 'assertion_failed',
374
+ timeout: 'step_failed',
375
+ disconnected: 'step_failed',
376
+ 'test-error': 'step_failed',
377
+ };
378
+ return {
379
+ code: codeByKind[context.kind],
380
+ title: context.testName ?? cycle.testName ?? 'DevAssist candidate failed',
381
+ message: context.message,
382
+ timelineNodeId: context.artifacts?.timelineNodeId,
383
+ recoveryHints: (context.recoveryHints ?? []).map((hint) => ({
384
+ kind: 'manual',
385
+ description: hint.message,
386
+ })),
387
+ };
388
+ }
@@ -0,0 +1,56 @@
1
+ import type { ResetCategory, TddCycleResult } from '../types.js';
2
+ export type TddFailureKind = 'missing-element' | 'ambiguous-element' | 'wrong-text' | 'navigation-failed' | 'mock-not-called' | 'state-mismatch' | 'timeout' | 'disconnected' | 'test-error';
3
+ export interface TddFailureContext {
4
+ kind: TddFailureKind;
5
+ message: string;
6
+ testFile: string;
7
+ testName?: string;
8
+ lastSync?: TddCycleResult['lastSync'];
9
+ baselineVersion?: number;
10
+ unsupportedState?: ResetCategory[];
11
+ source?: TddFailureSource;
12
+ assertion?: TddFailureAssertion;
13
+ artifacts?: TddFailureArtifacts;
14
+ recoveryHints?: TddRecoveryHint[];
15
+ }
16
+ export type TddRecoveryHintKind = 'inspect-source' | 'inspect-snapshot' | 'refine-selector' | 'disambiguate-selector' | 'check-navigation' | 'configure-mock' | 'seed-state' | 'sync-app' | 'increase-timeout' | 'reconnect' | 'configure-reset-adapter';
17
+ export interface TddRecoveryHint {
18
+ kind: TddRecoveryHintKind;
19
+ priority: 'high' | 'medium' | 'low';
20
+ message: string;
21
+ actions: string[];
22
+ }
23
+ export interface BuildTddFailureContextInput {
24
+ file: string;
25
+ testName?: string;
26
+ message?: string;
27
+ /** Override the heuristic classification (e.g. an explicit cycle timeout / disconnect). */
28
+ kind?: TddFailureKind;
29
+ lastSync?: TddCycleResult['lastSync'];
30
+ baselineVersion?: number;
31
+ unsupportedState?: ResetCategory[];
32
+ source?: TddFailureSource;
33
+ assertion?: TddFailureAssertion;
34
+ artifacts?: TddFailureArtifacts;
35
+ }
36
+ export interface TddFailureSource {
37
+ file: string;
38
+ line: number;
39
+ snippet: string;
40
+ }
41
+ export interface TddFailureAssertion {
42
+ matcher: string;
43
+ expected: string;
44
+ actual: string;
45
+ timeout: number;
46
+ }
47
+ export interface TddFailureArtifacts {
48
+ failureContextPath?: string;
49
+ screenshotPath?: string;
50
+ screenshotBase64?: string;
51
+ widgetTree?: unknown;
52
+ timelinePath?: string;
53
+ timelineNodeId?: string;
54
+ }
55
+ export declare function buildTddFailureContext(input: BuildTddFailureContextInput): TddFailureContext;
56
+ export declare function classifyFailure(message: string): TddFailureKind;
@@ -0,0 +1,220 @@
1
+ export function buildTddFailureContext(input) {
2
+ const message = input.message?.trim() || 'Focused TDD test failed without a structured failure message.';
3
+ const kind = input.kind ?? classifyFailure(message);
4
+ const context = {
5
+ kind,
6
+ message,
7
+ testFile: input.file,
8
+ testName: input.testName,
9
+ lastSync: input.lastSync,
10
+ baselineVersion: input.baselineVersion,
11
+ unsupportedState: input.unsupportedState?.length ? input.unsupportedState : undefined,
12
+ source: input.source,
13
+ assertion: input.assertion,
14
+ artifacts: input.artifacts,
15
+ };
16
+ const recoveryHints = buildRecoveryHints(context);
17
+ return {
18
+ ...context,
19
+ recoveryHints: recoveryHints.length > 0 ? recoveryHints : undefined,
20
+ };
21
+ }
22
+ export function classifyFailure(message) {
23
+ const normalized = message.toLowerCase();
24
+ if (normalized.includes('strict mode violation')
25
+ || normalized.includes('multiple widgets')
26
+ || normalized.includes('ambiguous')) {
27
+ return 'ambiguous-element';
28
+ }
29
+ if (normalized.includes('no widget found')
30
+ || normalized.includes('could not find')
31
+ || normalized.includes('not found')
32
+ || normalized.includes('tobevisible')
33
+ || normalized.includes('to be visible')) {
34
+ return 'missing-element';
35
+ }
36
+ if (normalized.includes('currentroute')
37
+ || normalized.includes('reset route')
38
+ || normalized.includes('route')
39
+ || normalized.includes('navigation')) {
40
+ return 'navigation-failed';
41
+ }
42
+ if (normalized.includes('tohavetext')
43
+ || normalized.includes('tocontaintext')
44
+ || (normalized.includes('expected') && normalized.includes('received'))) {
45
+ return 'wrong-text';
46
+ }
47
+ if (normalized.includes('waitforcall')
48
+ || normalized.includes('recorded calls')
49
+ || normalized.includes('mock')
50
+ || normalized.includes('called at least')) {
51
+ return 'mock-not-called';
52
+ }
53
+ if (normalized.includes('state') || normalized.includes('provider')) {
54
+ return 'state-mismatch';
55
+ }
56
+ return 'test-error';
57
+ }
58
+ function buildRecoveryHints(context) {
59
+ const hints = [];
60
+ if (context.unsupportedState?.length) {
61
+ hints.push({
62
+ kind: 'configure-reset-adapter',
63
+ priority: 'high',
64
+ message: `Baseline reset could not fully control: ${context.unsupportedState.join(', ')}.`,
65
+ actions: [
66
+ 'Add the missing host app reset handler/capability, or remove the unsupported category from the scenario while iterating.',
67
+ 'If the category is required for determinism, configure it before trusting a green result.',
68
+ ],
69
+ });
70
+ }
71
+ if (context.source) {
72
+ hints.push({
73
+ kind: 'inspect-source',
74
+ priority: 'medium',
75
+ message: `Inspect the failing test source at ${context.source.file}:${context.source.line}.`,
76
+ actions: [
77
+ 'Open the reported source line and compare the assertion or locator with the current app snapshot.',
78
+ 'Prefer fixing stale generated test code before changing app behavior.',
79
+ ],
80
+ });
81
+ }
82
+ if (context.artifacts?.screenshotPath || context.artifacts?.widgetTree || context.artifacts?.timelinePath) {
83
+ hints.push({
84
+ kind: 'inspect-snapshot',
85
+ priority: 'medium',
86
+ message: 'Use the captured artifacts to compare expected UI with the actual rendered app state.',
87
+ actions: [
88
+ 'Inspect screenshot, widget tree, or timeline artifacts before editing code.',
89
+ 'If the UI is correct but the locator is stale, update the generated test selector.',
90
+ ],
91
+ });
92
+ }
93
+ switch (context.kind) {
94
+ case 'missing-element':
95
+ hints.push({
96
+ kind: 'refine-selector',
97
+ priority: 'high',
98
+ message: 'The generated test is looking for a widget that is not currently discoverable.',
99
+ actions: [
100
+ 'Capture a fresh fliwright app snapshot and replace brittle text/type selectors with key or semantics selectors when available.',
101
+ 'If the widget should exist but does not render, fix the app state/setup before changing the assertion.',
102
+ ],
103
+ });
104
+ maybeSuggestSync(hints, context);
105
+ break;
106
+ case 'ambiguous-element':
107
+ hints.push({
108
+ kind: 'disambiguate-selector',
109
+ priority: 'high',
110
+ message: 'The locator matches multiple widgets.',
111
+ actions: [
112
+ 'Narrow the selector using a stable key, semantics label, ancestor scope, or visible text unique to the intended widget.',
113
+ 'Avoid broad text/type locators in generated tests when several widgets share the same label.',
114
+ ],
115
+ });
116
+ break;
117
+ case 'wrong-text':
118
+ hints.push({
119
+ kind: 'inspect-source',
120
+ priority: 'high',
121
+ message: 'The assertion expected different text or value than the app produced.',
122
+ actions: [
123
+ 'Decide whether the generated expectation is stale or the product behavior is wrong.',
124
+ 'Update the test only when the current app output is the intended behavior.',
125
+ ],
126
+ });
127
+ break;
128
+ case 'navigation-failed':
129
+ hints.push({
130
+ kind: 'check-navigation',
131
+ priority: 'high',
132
+ message: 'The app is not on the expected route or reset route.',
133
+ actions: [
134
+ 'Check scenario.homeRoute and any navigation preconditions in the generated test.',
135
+ 'If routing code changed, rerun with sync:auto or restart before editing assertions.',
136
+ ],
137
+ });
138
+ break;
139
+ case 'mock-not-called':
140
+ hints.push({
141
+ kind: 'configure-mock',
142
+ priority: 'high',
143
+ message: 'The expected mocked endpoint was not called or did not match the active mock profile.',
144
+ actions: [
145
+ 'Verify the mock endpoint, HTTP method, active rule, and mockProfile used by the scenario.',
146
+ 'Check whether the app reached the action that should trigger the request.',
147
+ ],
148
+ });
149
+ break;
150
+ case 'state-mismatch':
151
+ hints.push({
152
+ kind: 'seed-state',
153
+ priority: 'high',
154
+ message: 'The app state does not match the test precondition.',
155
+ actions: [
156
+ 'Seed required storage/Riverpod/app state through the scenario before the cycle.',
157
+ 'If reset categories are unsupported, configure the host app reset contract first.',
158
+ ],
159
+ });
160
+ break;
161
+ case 'timeout':
162
+ hints.push({
163
+ kind: 'increase-timeout',
164
+ priority: 'medium',
165
+ message: 'The cycle exceeded its wall-clock budget.',
166
+ actions: [
167
+ 'Inspect whether the app is stuck, a locator wait is too broad, or the timeoutMs budget is too small.',
168
+ 'Keep the next cycle serialized; do not start a second runtime while the previous body is finishing.',
169
+ ],
170
+ });
171
+ break;
172
+ case 'disconnected':
173
+ hints.push({
174
+ kind: 'reconnect',
175
+ priority: 'high',
176
+ message: 'The Flutter VM service connection appears disconnected.',
177
+ actions: [
178
+ 'Call fliwright tdd reconnect, then rerun the focused cycle.',
179
+ 'If reconnect fails, restart the app/runtime and preserve the generated test file.',
180
+ ],
181
+ });
182
+ break;
183
+ case 'test-error':
184
+ hints.push({
185
+ kind: 'inspect-source',
186
+ priority: 'high',
187
+ message: 'The failure is not recognized as a selector, mock, navigation, state, or timeout issue.',
188
+ actions: [
189
+ 'Read the raw error and failing source line before editing.',
190
+ 'If this is a compile/runtime error, fix the test or app code and rerun the same focused cycle.',
191
+ ],
192
+ });
193
+ break;
194
+ default:
195
+ break;
196
+ }
197
+ return dedupeHints(hints);
198
+ }
199
+ function maybeSuggestSync(hints, context) {
200
+ if (context.lastSync === 'restart')
201
+ return;
202
+ hints.push({
203
+ kind: 'sync-app',
204
+ priority: 'low',
205
+ message: 'A missing widget can be caused by stale hot-reload state after structural app changes.',
206
+ actions: [
207
+ 'If app structure, generated code, assets, or providers changed, rerun with sync:auto or sync:restart.',
208
+ ],
209
+ });
210
+ }
211
+ function dedupeHints(hints) {
212
+ const seen = new Set();
213
+ return hints.filter((hint) => {
214
+ const key = `${hint.kind}:${hint.message}`;
215
+ if (seen.has(key))
216
+ return false;
217
+ seen.add(key);
218
+ return true;
219
+ });
220
+ }
@@ -0,0 +1,7 @@
1
+ import type { Vitest } from 'vitest/node';
2
+ /**
3
+ * Encodes the Vitest 5 focused rerun recipe for the persistent TDD executor.
4
+ * Vitest 5 replaces changeNamePattern/changeFilenamePattern with specification-scoped
5
+ * filters plus rerunTestSpecifications.
6
+ */
7
+ export declare function focusAndRerun(vitest: Vitest, file: string, testName?: string): ReturnType<Vitest['rerunTestSpecifications']>;