@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,589 @@
1
+ import { waitForVmServiceEndpoint, EndpointLeaseManager, ScenarioCoordinator, FliwrightDriver, VmServiceEndpointResolver, explicitEndpointSource } from '@fliwright/core';
2
+ import { dirname } from 'node:path';
3
+ import { mkdir, writeFile } from 'node:fs/promises';
4
+ import { FlutterDaemonController } from '../daemon/FlutterDaemonController.js';
5
+ import { FlutterDaemonEndpointSource } from '../daemon/FlutterDaemonEndpointSource.js';
6
+ import { SubprocessDaemonTransport } from '../daemon/SubprocessDaemonTransport.js';
7
+ import { decideSync, looksStructuralAfterReload } from '../daemon/ReloadStrategy.js';
8
+ import { PersistentTestExecutor } from '../executor/PersistentTestExecutor.js';
9
+ import { BaselineManager } from '../baseline/BaselineManager.js';
10
+ import { TddRepairPlanner } from '../repair/TddRepairPlanner.js';
11
+ import { buildTddFailureContext } from '../diagnostics/TddFailureContext.js';
12
+ import { DEFAULT_CYCLE_TIMEOUT_MS } from '../types.js';
13
+ const defaultScenario = {
14
+ homeRoute: '/',
15
+ resetCategories: ['navigation', 'mock'],
16
+ };
17
+ /** Default cap on repair→cycle iterations (design §7 P3). Prevents unbounded AI edits. */
18
+ const DEFAULT_REPAIR_ITERATIONS = 3;
19
+ export class TddRuntime {
20
+ daemon;
21
+ executor;
22
+ driverFactory;
23
+ injectedBaseline;
24
+ baseline;
25
+ /** Optional AI repair planner (design §6.2, wired P3). Absent → no repair loop (additive). */
26
+ repairPlanner;
27
+ driver;
28
+ app;
29
+ vmServiceUrl;
30
+ configRoot;
31
+ sharedConfig;
32
+ startAppParams;
33
+ testScenario;
34
+ defaultScenarioName;
35
+ scenario = defaultScenario;
36
+ focusedTest;
37
+ lastResult;
38
+ started = false;
39
+ launchMode = 'attach';
40
+ driverConnections = 0;
41
+ startSignature;
42
+ updatedAtMs = Date.now();
43
+ // Serializes runtime/app state mutations (design §8: only one operation at a time). This covers
44
+ // cycle(), manual sync, scenario updates, reconnect, and stop so an agent cannot reload/restart or
45
+ // swap baselines mid-rerun.
46
+ endpointLeases = new EndpointLeaseManager();
47
+ operationChain = Promise.resolve();
48
+ statusFilePath;
49
+ // Serializes best-effort status-file writes so concurrent snapshots never interleave bytes.
50
+ statusWriteChain = Promise.resolve();
51
+ constructor(deps = {}) {
52
+ this.daemon = deps.daemon ?? new FlutterDaemonController(new SubprocessDaemonTransport());
53
+ this.executor = deps.executor ?? new PersistentTestExecutor();
54
+ this.driverFactory = deps.driverFactory ?? (() => new FliwrightDriver({
55
+ cacheRoot: this.sharedConfig?.cacheRoot,
56
+ projectRoot: this.configRoot && (/\.[cm]?[jt]s$/.test(this.configRoot) ? dirname(this.configRoot) : this.configRoot),
57
+ }));
58
+ this.injectedBaseline = deps.baseline;
59
+ this.baseline = deps.baseline;
60
+ this.repairPlanner = deps.repair;
61
+ }
62
+ async start(opts) {
63
+ const startSignature = startOptsSignature(opts);
64
+ if (this.started) {
65
+ if (this.startSignature !== startSignature) {
66
+ throw new Error('TddRuntime is already started with different options. Stop it before reconfiguring.');
67
+ }
68
+ return this.snapshot();
69
+ }
70
+ try {
71
+ this.scenario = opts.scenario ?? defaultScenario;
72
+ this.launchMode = opts.launchMode ?? (opts.app ? 'start' : 'attach');
73
+ this.startSignature = startSignature;
74
+ this.configRoot = opts.configRoot;
75
+ this.sharedConfig = opts.sharedConfig;
76
+ this.startAppParams = opts.app;
77
+ this.statusFilePath = opts.statusFilePath;
78
+ let vmServiceUrl = opts.vmServiceUrl;
79
+ if (opts.app) {
80
+ await this.daemon.start();
81
+ const source = new FlutterDaemonEndpointSource({ controller: this.daemon, ...opts.app });
82
+ const endpoint = await source.acquire();
83
+ this.app = source.lastApp;
84
+ vmServiceUrl = endpoint.url;
85
+ this.launchMode = 'start';
86
+ }
87
+ if (!vmServiceUrl) {
88
+ throw new Error('TddRuntime.start requires either app start params or vmServiceUrl.');
89
+ }
90
+ this.vmServiceUrl = vmServiceUrl;
91
+ this.defaultScenarioName = opts.defaultScenario;
92
+ this.driver = this.driverFactory();
93
+ await this.verifyManagedEndpoint(vmServiceUrl);
94
+ await this.driver.connect(vmServiceUrl);
95
+ this.driverConnections += 1;
96
+ // Auto-wire the repair planner from the real driver's page so fliwright tdd repair works
97
+ // out of the box. Skipped when a planner was injected, and for non-FliwrightDriver test
98
+ // doubles (their page lacks the AgentRepair surface) — keeping the path additive.
99
+ if (!this.repairPlanner && this.driver instanceof FliwrightDriver) {
100
+ this.repairPlanner = TddRepairPlanner.forPage(this.driver.page);
101
+ }
102
+ this.baseline = this.baseline ?? this.injectedBaseline ?? new BaselineManager(this.driver);
103
+ await this.executor.boot({ sharedConfig: this.sharedConfig, scenarioMode: this.launchMode === 'start' ? 'managed-start' : 'attach',
104
+ defaultScenario: opts.defaultScenario,
105
+ configRoot: opts.configRoot,
106
+ vmServiceUrl,
107
+ driverProvider: async () => this.requireDriver(),
108
+ });
109
+ this.started = true;
110
+ this.markUpdated();
111
+ this.persistStatus();
112
+ return this.snapshot();
113
+ }
114
+ catch (error) {
115
+ await this.executor.dispose().catch(() => undefined);
116
+ await this.cleanupStartedResources().catch(() => undefined);
117
+ throw error;
118
+ }
119
+ }
120
+ /** Interrupt owned transports/execution; the operation chain still drains before reuse. */
121
+ async cancel() {
122
+ await Promise.allSettled([
123
+ this.driver?.dispose({ signal: AbortSignal.abort() }),
124
+ this.executor.dispose(),
125
+ this.daemon.dispose(),
126
+ ]);
127
+ }
128
+ /** Wait for real work, including a cycle whose caller already received timeout. */
129
+ async whenIdle() { await this.operationChain; }
130
+ async focus(file, testName) {
131
+ this.focusedTest = { file, testName };
132
+ this.markUpdated();
133
+ this.persistStatus();
134
+ }
135
+ async setTestScenario(scenario) {
136
+ return this.enqueueOperation(async () => {
137
+ // Reboot the worker environment so each retry prepares the named scenario.
138
+ await this.executor.dispose();
139
+ await this.executor.boot({ sharedConfig: this.sharedConfig, scenarioMode: this.launchMode === 'start' ? 'managed-start' : 'attach', configRoot: this.configRoot, vmServiceUrl: this.vmServiceUrl,
140
+ defaultScenario: scenario.name, driverProvider: async () => this.requireDriver() });
141
+ this.defaultScenarioName = scenario.name;
142
+ this.testScenario = scenario;
143
+ this.markUpdated();
144
+ return this.snapshot();
145
+ });
146
+ }
147
+ async setScenario(scenario) {
148
+ return await this.enqueueOperation(async () => {
149
+ this.scenario = scenario;
150
+ this.markUpdated();
151
+ this.persistStatus();
152
+ return this.snapshot();
153
+ });
154
+ }
155
+ async syncApp(sync) {
156
+ return await this.enqueueOperation(async () => {
157
+ if (!this.started)
158
+ throw new Error('TddRuntime is not started.');
159
+ const lastSync = await this.controlPhase(() => this.sync(sync));
160
+ this.markUpdated();
161
+ this.persistStatus();
162
+ return {
163
+ lastSync,
164
+ snapshot: this.snapshot(),
165
+ };
166
+ });
167
+ }
168
+ async cycle(testName, opts = {}) {
169
+ // Serialize overlapping cycles (design §8): each cycle runs to completion before the next starts.
170
+ // The caller's promise (deferred) is resolved separately so a timeout can return early, while the
171
+ // chain task keeps awaiting the real body — guaranteeing the single-threaded executor is never
172
+ // overlapped by the next cycle even after a timeout.
173
+ //
174
+ // When opts.repair is set, the same chain task also runs the AI repair closed loop after the
175
+ // initial cycle (design §7/§10 P3): the whole loop (initial cycle + repair proposals + re-cycles)
176
+ // lives inside this serialized task, so it can never overlap another cycle or be reentered.
177
+ const deferred = makeDeferred();
178
+ const task = () => this.runCycleWithEscalation(testName, opts, deferred);
179
+ const run = this.operationChain.then(task, task);
180
+ this.operationChain = run.then(noop, noop);
181
+ return deferred.promise;
182
+ }
183
+ /**
184
+ * Reconnect after a VM disconnect (design §8). Daemon-start relaunches the app and rebinds to the
185
+ * fresh VM service; attach retries the original URL. If the URL changed, the executor is rebooted
186
+ * so fixtures pick up the new `FLIWRIGHT_VM_SERVICE_URL`. Throws on failure; the caller surfaces a
187
+ * structured error. Awaited on the cycle chain so it never races an in-flight rerun.
188
+ */
189
+ async reconnect() {
190
+ return await this.enqueueOperation(async () => this.reconnectNow());
191
+ }
192
+ async reconnectNow() {
193
+ if (!this.started)
194
+ throw new Error('TddRuntime is not started; nothing to reconnect.');
195
+ await this.driver?.dispose().catch(() => undefined);
196
+ this.driver = undefined;
197
+ let vmServiceUrl = this.vmServiceUrl;
198
+ if (this.startAppParams) {
199
+ await this.daemon.start().catch(() => undefined);
200
+ const source = new FlutterDaemonEndpointSource({ controller: this.daemon, ...this.startAppParams });
201
+ const endpoint = await source.acquire();
202
+ this.app = source.lastApp;
203
+ vmServiceUrl = endpoint.url;
204
+ }
205
+ if (!vmServiceUrl)
206
+ throw new Error('Cannot reconnect: no VM service URL is available.');
207
+ const urlChanged = vmServiceUrl !== this.vmServiceUrl;
208
+ this.vmServiceUrl = vmServiceUrl;
209
+ if (urlChanged && this.configRoot) {
210
+ // Fixtures read FLIWRIGHT_VM_SERVICE_URL at run time; reboot so the new URL propagates.
211
+ await this.executor.dispose().catch(() => undefined);
212
+ await this.executor.boot({ sharedConfig: this.sharedConfig, scenarioMode: this.launchMode === 'start' ? 'managed-start' : 'attach',
213
+ configRoot: this.configRoot,
214
+ defaultScenario: this.defaultScenarioName,
215
+ vmServiceUrl,
216
+ driverProvider: async () => this.requireDriver(),
217
+ });
218
+ }
219
+ this.driver = this.driverFactory();
220
+ await this.verifyManagedEndpoint(vmServiceUrl);
221
+ await this.driver.connect(vmServiceUrl);
222
+ this.driverConnections += 1;
223
+ this.markUpdated();
224
+ this.persistStatus();
225
+ return this.snapshot();
226
+ }
227
+ async verifyManagedEndpoint(vmServiceUrl) {
228
+ if (!(this.driver instanceof FliwrightDriver))
229
+ return;
230
+ if (this.launchMode === 'start')
231
+ await waitForVmServiceEndpoint({ url: vmServiceUrl, kind: 'direct-vm', source: 'managed-launch', scope: 'execution-worker', acquiredAt: new Date().toISOString() });
232
+ await new VmServiceEndpointResolver([
233
+ explicitEndpointSource(vmServiceUrl, { source: 'flutter-daemon', scope: 'execution-worker' }),
234
+ ], { persistWorkspaceCache: false }).acquire();
235
+ }
236
+ async runCycleWithEscalation(testName, opts, deferred) {
237
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_CYCLE_TIMEOUT_MS;
238
+ const runAll = async () => {
239
+ const first = await this.performCycle(testName, opts);
240
+ if ((opts.autoEscalate ?? true) && looksStructuralAfterReload(first) && this.canRestart()) {
241
+ try {
242
+ const escalated = await this.performCycle(testName, {
243
+ ...opts,
244
+ sync: 'restart',
245
+ fullReset: true,
246
+ changes: undefined,
247
+ autoEscalate: false,
248
+ });
249
+ if (escalated.lastSync === 'restart')
250
+ return { ...escalated, syncEscalated: true };
251
+ }
252
+ catch {
253
+ // Escalation is best-effort: if the restart cycle itself fails, surface the reload result.
254
+ }
255
+ }
256
+ return first;
257
+ };
258
+ // Resolve the caller early on timeout, but keep awaiting `runAll` so the chain (and thus the
259
+ // next cycle) cannot advance past a still-running executor body.
260
+ const timer = setTimeout(() => {
261
+ const timeoutResult = this.timeoutResult(testName, timeoutMs);
262
+ this.lastResult = timeoutResult;
263
+ this.markUpdated();
264
+ this.persistStatus();
265
+ deferred.resolve(timeoutResult);
266
+ }, timeoutMs);
267
+ try {
268
+ const result = await runAll();
269
+ clearTimeout(timer);
270
+ // AI repair closed loop (design §7/§10 P3). Runs only when requested AND a planner is wired.
271
+ // Entirely serialized: lives inside this chain task, so it never overlaps another cycle and is
272
+ // not reentrant. 'suggest' stops after one proposal (no apply, no loop); 'safe-apply' loops
273
+ // cycle(red) → repair → cycle until green or the iteration cap. Omitted → byte-for-byte today.
274
+ const finalResult = opts.repair && this.repairPlanner && result.status === 'red'
275
+ ? await this.runRepairLoop(testName, opts, result)
276
+ : result;
277
+ this.lastResult = finalResult;
278
+ this.markUpdated();
279
+ this.persistStatus();
280
+ deferred.resolve(finalResult);
281
+ return finalResult;
282
+ }
283
+ catch (error) {
284
+ clearTimeout(timer);
285
+ deferred.reject(error);
286
+ throw error;
287
+ }
288
+ }
289
+ /**
290
+ * The AI repair closed loop (design §7/§10 P3). Runs serialized inside the cycle chain task after
291
+ * the initial red cycle. Proposes a minimal, guardrail-bounded repair via the wired planner, then
292
+ * (safe-apply only) re-cycles until green or the iteration cap. Never reentrant: the caller has
293
+ * already acquired the chain; this method calls {@link performCycle} directly (not {@link cycle}).
294
+ *
295
+ * In 'suggest' mode it proposes once, attaches the diff as a repair trace, and returns the original
296
+ * red result unchanged (nothing applied). In 'safe-apply' mode it applies only guardrail-safe
297
+ * repairs and re-cycles; reaching the cap still red is a terminal state surfaced via the trace.
298
+ */
299
+ async runRepairLoop(testName, opts, initialRed) {
300
+ const repairOpts = opts.repair;
301
+ const planner = this.repairPlanner;
302
+ const maxIterations = repairOpts.iterations && repairOpts.iterations > 0 ? repairOpts.iterations : DEFAULT_REPAIR_ITERATIONS;
303
+ const steps = [];
304
+ let current = initialRed;
305
+ let capped = false;
306
+ // Re-cycle options for each repair iteration: no nested repair, keep the caller's sync/reset
307
+ // policy, but disable auto-escalation (already attempted on the initial cycle).
308
+ const reCycleOpts = {
309
+ ...opts,
310
+ repair: undefined,
311
+ autoEscalate: false,
312
+ };
313
+ for (let iteration = 1; iteration <= maxIterations; iteration += 1) {
314
+ const planAndApplied = await planner.propose(current, repairOpts.mode);
315
+ const step = { iteration, plan: planAndApplied };
316
+ if (repairOpts.mode === 'safe-apply' && planAndApplied.applied) {
317
+ step.applied = planAndApplied.applied;
318
+ }
319
+ steps.push(step);
320
+ // 'suggest' never loops or applies: emit the diff and stop on the first proposal.
321
+ if (repairOpts.mode === 'suggest')
322
+ break;
323
+ // safe-apply: nothing safe was applied this iteration → no point re-cycling, stop.
324
+ if (!planAndApplied.applied || planAndApplied.applied.length === 0)
325
+ break;
326
+ current = await this.performCycle(testName, reCycleOpts);
327
+ if (current.status === 'green')
328
+ break;
329
+ if (iteration === maxIterations)
330
+ capped = true;
331
+ }
332
+ const trace = { mode: repairOpts.mode, steps, capped };
333
+ return { ...current, repair: trace };
334
+ }
335
+ timeoutResult(testName, timeoutMs) {
336
+ const focused = this.focusedTest;
337
+ const file = focused?.file ?? '<unknown>';
338
+ const actualName = testName ?? focused?.testName;
339
+ const baselineVersion = this.baseline?.version ?? 0;
340
+ const message = `TDD cycle exceeded the ${timeoutMs}ms budget and was returned as a timeout.`;
341
+ return {
342
+ status: 'red',
343
+ testName: actualName,
344
+ file,
345
+ durationMs: timeoutMs,
346
+ lastSync: 'none',
347
+ baselineVersion,
348
+ failure: { message },
349
+ failureContext: buildTddFailureContext({
350
+ file,
351
+ testName: actualName,
352
+ message,
353
+ kind: 'timeout',
354
+ baselineVersion,
355
+ }),
356
+ unsupportedState: undefined,
357
+ };
358
+ }
359
+ async performCycle(testName, opts) {
360
+ if (!this.started)
361
+ throw new Error('TddRuntime is not started.');
362
+ const focused = this.focusedTest;
363
+ if (!focused)
364
+ throw new Error('No focused test. Call focus(file, testName) before cycle().');
365
+ const actualTestName = testName ?? focused.testName;
366
+ const startedAt = Date.now();
367
+ const requestedSync = opts.sync ?? 'none';
368
+ const resolvedSync = requestedSync === 'auto' ? decideSync(opts.changes) : requestedSync;
369
+ let lastSync = 'none';
370
+ try {
371
+ lastSync = await this.controlPhase(() => this.sync(resolvedSync));
372
+ }
373
+ catch (error) {
374
+ const baselineVersion = this.baseline?.version ?? 0;
375
+ const message = error instanceof Error ? error.message : String(error);
376
+ return {
377
+ status: 'red',
378
+ testName: actualTestName,
379
+ file: focused.file,
380
+ durationMs: Date.now() - startedAt,
381
+ lastSync,
382
+ baselineVersion,
383
+ failure: { message },
384
+ failureContext: buildTddFailureContext({
385
+ file: focused.file,
386
+ testName: actualTestName,
387
+ message,
388
+ kind: 'test-error',
389
+ lastSync,
390
+ baselineVersion,
391
+ }),
392
+ };
393
+ }
394
+ const resetReport = this.defaultScenarioName ? { version: this.requireBaseline().version, applied: [], unsupported: [] } : this.testScenario ? await this.controlPhase(async () => {
395
+ await new ScenarioCoordinator(this.requireDriver()).apply(this.testScenario, { mode: 'attach' });
396
+ return { version: this.requireBaseline().version, applied: [], unsupported: [] };
397
+ }) : await this.controlPhase(() => this.requireBaseline().reset(this.scenario, {
398
+ full: opts.fullReset ?? lastSync === 'restart',
399
+ }));
400
+ const outcome = await this.executor.rerun(focused.file, actualTestName);
401
+ const unsupportedState = resetReport.unsupported;
402
+ const failureContext = outcome.status === 'red'
403
+ ? buildTddFailureContext({
404
+ file: focused.file,
405
+ testName: outcome.testName ?? actualTestName,
406
+ message: outcome.failure?.message,
407
+ lastSync,
408
+ baselineVersion: resetReport.version,
409
+ unsupportedState,
410
+ source: outcome.failureDetails?.source,
411
+ assertion: outcome.failureDetails?.assertion,
412
+ artifacts: outcome.failureDetails?.artifacts,
413
+ })
414
+ : undefined;
415
+ return {
416
+ status: outcome.status,
417
+ testName: outcome.testName ?? actualTestName,
418
+ file: focused.file,
419
+ durationMs: Date.now() - startedAt,
420
+ lastSync,
421
+ baselineVersion: resetReport.version,
422
+ failure: outcome.failure,
423
+ failureContext,
424
+ timelinePath: outcome.timelinePath ?? outcome.failureDetails?.artifacts?.timelinePath,
425
+ timelineNodeId: outcome.timelineNodeId ?? outcome.failureDetails?.artifacts?.timelineNodeId,
426
+ unsupportedState,
427
+ };
428
+ }
429
+ /**
430
+ * Best-effort, non-blocking dump of {@link snapshot} to {@link statusFilePath}, serialized so
431
+ * concurrent writes never interleave. Read-only monitors (VS Code TDD Loop panel) poll this file
432
+ * instead of opening a second driver connection. Never throws; failures are swallowed.
433
+ */
434
+ persistStatus() {
435
+ this.persistStatusTo(this.statusFilePath);
436
+ }
437
+ persistStatusTo(statusFilePath) {
438
+ if (!statusFilePath)
439
+ return;
440
+ const snapshot = this.snapshot();
441
+ this.statusWriteChain = this.statusWriteChain.then(async () => {
442
+ try {
443
+ await mkdir(dirname(statusFilePath), { recursive: true });
444
+ await writeFile(statusFilePath, `${JSON.stringify(snapshot, null, 2)}\n`, 'utf8');
445
+ }
446
+ catch {
447
+ /* best-effort: a missing status file just means the monitor shows "no snapshot" */
448
+ }
449
+ });
450
+ }
451
+ /** Current endpoint for an owning CLI host; changes after managed reconnect. */
452
+ get endpoint() { return this.vmServiceUrl; }
453
+ snapshot() {
454
+ return {
455
+ connected: this.started,
456
+ daemonStatus: this.started ? 'running' : 'stopped',
457
+ appId: this.app?.appId,
458
+ supportsRestart: this.started ? (this.app?.supportsRestart ?? false) : false,
459
+ launchMode: this.launchMode,
460
+ restartCapable: this.launchMode === 'start' && (this.app?.supportsRestart ?? false),
461
+ driverConnections: this.driverConnections,
462
+ fixtureDriverSharing: 'vm-service-url',
463
+ notes: [
464
+ 'Vitest 5.0.5 runs tests in worker processes, so live FliwrightDriver objects are not shared across the executor boundary.',
465
+ 'The TDD runtime injects FLIWRIGHT_VM_SERVICE_URL so fixtures connect to the same app VM service.',
466
+ ],
467
+ focusedTest: this.focusedTest,
468
+ lastResult: this.lastResult,
469
+ baselineVersion: this.baseline?.version ?? 0,
470
+ unsupportedState: this.lastResult?.unsupportedState,
471
+ updatedAtMs: this.updatedAtMs,
472
+ };
473
+ }
474
+ async stop(opts = {}) {
475
+ await this.enqueueOperation(async () => {
476
+ const statusFilePath = this.statusFilePath;
477
+ try {
478
+ await this.executor.dispose();
479
+ }
480
+ finally {
481
+ await this.cleanupStartedResources(opts);
482
+ }
483
+ // Publish a final "stopped" snapshot so monitors reflect the halted runtime.
484
+ this.markUpdated();
485
+ this.persistStatusTo(statusFilePath);
486
+ await this.statusWriteChain;
487
+ });
488
+ }
489
+ markUpdated() {
490
+ this.updatedAtMs = Date.now();
491
+ }
492
+ enqueueOperation(task) {
493
+ const run = this.operationChain.then(task, task);
494
+ this.operationChain = run.then(noop, noop);
495
+ return run;
496
+ }
497
+ async controlPhase(work) {
498
+ return this.vmServiceUrl ? this.endpointLeases.run(this.vmServiceUrl, work) : work();
499
+ }
500
+ async sync(sync) {
501
+ if (sync === 'none')
502
+ return 'none';
503
+ if (!this.app) {
504
+ if (sync === 'restart')
505
+ throw new Error('Hot restart requires a daemon-started app.');
506
+ await this.requireDriver().reloadSources?.();
507
+ return 'reload';
508
+ }
509
+ if (sync === 'reload') {
510
+ await this.daemon.reload(this.app.appId);
511
+ return 'reload';
512
+ }
513
+ await this.daemon.restart(this.app.appId);
514
+ return 'restart';
515
+ }
516
+ /** True only when a daemon-started app advertised restart support (gates auto-escalation). */
517
+ canRestart() {
518
+ return this.launchMode === 'start' && (this.app?.supportsRestart ?? false);
519
+ }
520
+ requireDriver() {
521
+ if (!this.driver)
522
+ throw new Error('TddRuntime driver is not connected.');
523
+ return this.driver;
524
+ }
525
+ requireBaseline() {
526
+ if (!this.baseline)
527
+ throw new Error('TddRuntime baseline is not initialized.');
528
+ return this.baseline;
529
+ }
530
+ async cleanupStartedResources(opts = {}) {
531
+ try {
532
+ await this.driver?.dispose();
533
+ }
534
+ finally {
535
+ try {
536
+ if (!opts.keepAppAlive && this.app)
537
+ await this.daemon.stop(this.app.appId);
538
+ }
539
+ finally {
540
+ try {
541
+ await this.daemon.dispose(opts);
542
+ }
543
+ finally {
544
+ this.driver = undefined;
545
+ this.app = undefined;
546
+ this.vmServiceUrl = undefined;
547
+ this.configRoot = undefined;
548
+ this.startAppParams = undefined;
549
+ this.baseline = undefined;
550
+ this.focusedTest = undefined;
551
+ this.lastResult = undefined;
552
+ this.startSignature = undefined;
553
+ this.launchMode = 'attach';
554
+ this.started = false;
555
+ }
556
+ }
557
+ }
558
+ }
559
+ }
560
+ function startOptsSignature(opts) {
561
+ return JSON.stringify({
562
+ app: opts.app
563
+ ? {
564
+ deviceId: opts.app.deviceId,
565
+ flutterArgs: opts.app.flutterArgs,
566
+ mode: opts.app.mode,
567
+ projectId: opts.app.projectId,
568
+ target: opts.app.target ?? 'lib/main.dart',
569
+ }
570
+ : undefined,
571
+ configRoot: opts.configRoot,
572
+ sharedConfig: opts.sharedConfig,
573
+ launchMode: opts.launchMode ?? (opts.app ? 'start' : 'attach'),
574
+ scenario: opts.scenario ?? defaultScenario,
575
+ vmServiceUrl: opts.vmServiceUrl,
576
+ });
577
+ }
578
+ function noop() {
579
+ /* chain keeper: swallows task rejections so the mutex never wedges */
580
+ }
581
+ function makeDeferred() {
582
+ let resolve;
583
+ let reject;
584
+ const promise = new Promise((res, rej) => {
585
+ resolve = res;
586
+ reject = rej;
587
+ });
588
+ return { promise, resolve, reject };
589
+ }
@@ -0,0 +1,34 @@
1
+ import type { LocatorHint, SpecElement } from '../spec/InteractionSpec.js';
2
+ export type SelectorSynthesisStatus = 'resolved' | 'ambiguous' | 'missing' | 'hint-only';
3
+ export interface WidgetCandidate {
4
+ key?: string;
5
+ text?: string;
6
+ type?: string;
7
+ semanticsLabel?: string;
8
+ role?: string;
9
+ }
10
+ export interface SelectorCandidate {
11
+ hint: LocatorHint;
12
+ confidence: number;
13
+ reason: string;
14
+ matchedWidgets?: WidgetCandidate[];
15
+ }
16
+ export interface SelectorTraceStep {
17
+ strategy: LocatorHint['strategy'];
18
+ status: 'selected' | 'candidate' | 'rejected' | 'missing';
19
+ value: string;
20
+ message: string;
21
+ }
22
+ export interface SelectorSynthesisResult {
23
+ elementId: string;
24
+ status: SelectorSynthesisStatus;
25
+ candidates: SelectorCandidate[];
26
+ trace: SelectorTraceStep[];
27
+ stabilityHints: Array<{
28
+ kind: 'add-key' | 'add-semantics' | 'refine-copy' | 'stale-hint';
29
+ description: string;
30
+ }>;
31
+ }
32
+ export declare function synthesizeSelector(element: SpecElement, widgets?: WidgetCandidate[]): SelectorSynthesisResult;
33
+ export declare function synthesizeSelectorsForElements(elements: SpecElement[], widgets?: WidgetCandidate[]): SelectorSynthesisResult[];
34
+ export declare function bestLocatorHint(element: SpecElement, widgets?: WidgetCandidate[]): LocatorHint;