@fliwright/tdd 0.1.0 → 0.1.1

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 (33) hide show
  1. package/README.md +25 -3
  2. package/dist/baseline/BaselineManager.d.ts +3 -3
  3. package/dist/daemon/FlutterDaemonController.d.ts +1 -0
  4. package/dist/daemon/FlutterDaemonController.js +13 -2
  5. package/dist/daemon/SubprocessDaemonTransport.d.ts +3 -0
  6. package/dist/daemon/SubprocessDaemonTransport.js +25 -9
  7. package/dist/executor/FocusedRerunRecipe.js +9 -2
  8. package/dist/executor/PersistentTestExecutor.d.ts +1 -4
  9. package/dist/executor/PersistentTestExecutor.js +31 -38
  10. package/dist/executor/TestRunResults.d.ts +13 -0
  11. package/dist/executor/TestRunResults.js +19 -0
  12. package/dist/index.d.ts +3 -17
  13. package/dist/index.js +1 -8
  14. package/dist/runtime/TddRuntime.d.ts +5 -19
  15. package/dist/runtime/TddRuntime.js +78 -115
  16. package/dist/types.d.ts +17 -192
  17. package/package.json +4 -4
  18. package/dist/devassist/DevAssistCoordinator.d.ts +0 -74
  19. package/dist/devassist/DevAssistCoordinator.js +0 -388
  20. package/dist/executor/ResultReporter.d.ts +0 -23
  21. package/dist/executor/ResultReporter.js +0 -50
  22. package/dist/generator/RedFirstTestGenerator.d.ts +0 -32
  23. package/dist/generator/RedFirstTestGenerator.js +0 -189
  24. package/dist/repair/TddRepairPlanner.d.ts +0 -54
  25. package/dist/repair/TddRepairPlanner.js +0 -132
  26. package/dist/selectors/SelectorSynthesizer.d.ts +0 -34
  27. package/dist/selectors/SelectorSynthesizer.js +0 -174
  28. package/dist/spec/InteractionSpec.d.ts +0 -94
  29. package/dist/spec/InteractionSpec.js +0 -236
  30. package/dist/spec/InteractionSpecCoverage.d.ts +0 -17
  31. package/dist/spec/InteractionSpecCoverage.js +0 -69
  32. package/dist/workflow/RedFirstWorkflow.d.ts +0 -28
  33. package/dist/workflow/RedFirstWorkflow.js +0 -33
@@ -1,4 +1,4 @@
1
- import { waitForVmServiceEndpoint, EndpointLeaseManager, ScenarioCoordinator, FliwrightDriver, VmServiceEndpointResolver, explicitEndpointSource } from '@fliwright/core';
1
+ import { waitForVmServiceEndpoint, EndpointLeaseManager, FliwrightDriver, VmServiceEndpointResolver, explicitEndpointSource } from '@fliwright/core';
2
2
  import { dirname } from 'node:path';
3
3
  import { mkdir, writeFile } from 'node:fs/promises';
4
4
  import { FlutterDaemonController } from '../daemon/FlutterDaemonController.js';
@@ -7,32 +7,26 @@ import { SubprocessDaemonTransport } from '../daemon/SubprocessDaemonTransport.j
7
7
  import { decideSync, looksStructuralAfterReload } from '../daemon/ReloadStrategy.js';
8
8
  import { PersistentTestExecutor } from '../executor/PersistentTestExecutor.js';
9
9
  import { BaselineManager } from '../baseline/BaselineManager.js';
10
- import { TddRepairPlanner } from '../repair/TddRepairPlanner.js';
11
10
  import { buildTddFailureContext } from '../diagnostics/TddFailureContext.js';
12
11
  import { DEFAULT_CYCLE_TIMEOUT_MS } from '../types.js';
13
- const defaultScenario = {
12
+ const defaultBaseline = {
14
13
  homeRoute: '/',
15
14
  resetCategories: ['navigation', 'mock'],
16
15
  };
17
- /** Default cap on repair→cycle iterations (design §7 P3). Prevents unbounded AI edits. */
18
- const DEFAULT_REPAIR_ITERATIONS = 3;
19
16
  export class TddRuntime {
20
17
  daemon;
21
18
  executor;
22
19
  driverFactory;
23
20
  injectedBaseline;
24
21
  baseline;
25
- /** Optional AI repair planner (design §6.2, wired P3). Absent → no repair loop (additive). */
26
- repairPlanner;
27
22
  driver;
28
23
  app;
29
24
  vmServiceUrl;
30
25
  configRoot;
31
26
  sharedConfig;
32
27
  startAppParams;
33
- testScenario;
34
28
  defaultScenarioName;
35
- scenario = defaultScenario;
29
+ baselineConfig = defaultBaseline;
36
30
  focusedTest;
37
31
  lastResult;
38
32
  started = false;
@@ -57,7 +51,6 @@ export class TddRuntime {
57
51
  }));
58
52
  this.injectedBaseline = deps.baseline;
59
53
  this.baseline = deps.baseline;
60
- this.repairPlanner = deps.repair;
61
54
  }
62
55
  async start(opts) {
63
56
  const startSignature = startOptsSignature(opts);
@@ -68,7 +61,7 @@ export class TddRuntime {
68
61
  return this.snapshot();
69
62
  }
70
63
  try {
71
- this.scenario = opts.scenario ?? defaultScenario;
64
+ this.baselineConfig = opts.baselineConfig ?? defaultBaseline;
72
65
  this.launchMode = opts.launchMode ?? (opts.app ? 'start' : 'attach');
73
66
  this.startSignature = startSignature;
74
67
  this.configRoot = opts.configRoot;
@@ -93,18 +86,11 @@ export class TddRuntime {
93
86
  await this.verifyManagedEndpoint(vmServiceUrl);
94
87
  await this.driver.connect(vmServiceUrl);
95
88
  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
89
  this.baseline = this.baseline ?? this.injectedBaseline ?? new BaselineManager(this.driver);
103
90
  await this.executor.boot({ sharedConfig: this.sharedConfig, scenarioMode: this.launchMode === 'start' ? 'managed-start' : 'attach',
104
91
  defaultScenario: opts.defaultScenario,
105
92
  configRoot: opts.configRoot,
106
93
  vmServiceUrl,
107
- driverProvider: async () => this.requireDriver(),
108
94
  });
109
95
  this.started = true;
110
96
  this.markUpdated();
@@ -132,21 +118,24 @@ export class TddRuntime {
132
118
  this.markUpdated();
133
119
  this.persistStatus();
134
120
  }
135
- async setTestScenario(scenario) {
121
+ /** Select the named scenario that Vitest fixtures prepare before every attempt. */
122
+ async setDefaultScenario(name) {
136
123
  return this.enqueueOperation(async () => {
137
- // Reboot the worker environment so each retry prepares the named scenario.
124
+ if (!this.started)
125
+ throw new Error('TddRuntime is not started.');
138
126
  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;
127
+ await this.executor.boot({ sharedConfig: this.sharedConfig,
128
+ scenarioMode: this.launchMode === 'start' ? 'managed-start' : 'attach',
129
+ configRoot: this.configRoot, vmServiceUrl: this.vmServiceUrl, defaultScenario: name });
130
+ this.defaultScenarioName = name;
143
131
  this.markUpdated();
132
+ this.persistStatus();
144
133
  return this.snapshot();
145
134
  });
146
135
  }
147
- async setScenario(scenario) {
136
+ async setBaselineConfig(config) {
148
137
  return await this.enqueueOperation(async () => {
149
- this.scenario = scenario;
138
+ this.baselineConfig = config;
150
139
  this.markUpdated();
151
140
  this.persistStatus();
152
141
  return this.snapshot();
@@ -170,10 +159,6 @@ export class TddRuntime {
170
159
  // The caller's promise (deferred) is resolved separately so a timeout can return early, while the
171
160
  // chain task keeps awaiting the real body — guaranteeing the single-threaded executor is never
172
161
  // 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
162
  const deferred = makeDeferred();
178
163
  const task = () => this.runCycleWithEscalation(testName, opts, deferred);
179
164
  const run = this.operationChain.then(task, task);
@@ -213,13 +198,13 @@ export class TddRuntime {
213
198
  configRoot: this.configRoot,
214
199
  defaultScenario: this.defaultScenarioName,
215
200
  vmServiceUrl,
216
- driverProvider: async () => this.requireDriver(),
217
201
  });
218
202
  }
219
203
  this.driver = this.driverFactory();
220
204
  await this.verifyManagedEndpoint(vmServiceUrl);
221
205
  await this.driver.connect(vmServiceUrl);
222
206
  this.driverConnections += 1;
207
+ this.baseline = this.injectedBaseline ?? new BaselineManager(this.driver);
223
208
  this.markUpdated();
224
209
  this.persistStatus();
225
210
  return this.snapshot();
@@ -235,30 +220,39 @@ export class TddRuntime {
235
220
  }
236
221
  async runCycleWithEscalation(testName, opts, deferred) {
237
222
  const timeoutMs = opts.timeoutMs ?? DEFAULT_CYCLE_TIMEOUT_MS;
223
+ const deadline = new AbortController();
224
+ const attempts = [];
225
+ const requestedSync = opts.sync === 'auto' ? decideSync(opts.changes) : opts.sync ?? 'none';
238
226
  const runAll = async () => {
239
- const first = await this.performCycle(testName, opts);
227
+ const first = await this.performCycle(testName, requestedSync, opts.fullReset, deadline.signal);
228
+ attempts.push({ ...first, requestedSync });
229
+ deadline.signal.throwIfAborted();
240
230
  if ((opts.autoEscalate ?? true) && looksStructuralAfterReload(first) && this.canRestart()) {
231
+ const retryStartedAt = Date.now();
241
232
  try {
242
- const escalated = await this.performCycle(testName, {
243
- ...opts,
244
- sync: 'restart',
245
- fullReset: true,
246
- changes: undefined,
247
- autoEscalate: false,
248
- });
233
+ const escalated = await this.performCycle(testName, 'restart', true, deadline.signal);
234
+ attempts.push({ ...escalated, requestedSync: 'restart' });
249
235
  if (escalated.lastSync === 'restart')
250
- return { ...escalated, syncEscalated: true };
236
+ return { ...escalated, attempts, syncEscalated: true };
251
237
  }
252
- catch {
253
- // Escalation is best-effort: if the restart cycle itself fails, surface the reload result.
238
+ catch (error) {
239
+ deadline.signal.throwIfAborted();
240
+ // Keep the first result as the primary failure if the retry cannot produce a test result.
241
+ const message = error instanceof Error ? error.message : String(error);
242
+ attempts.push({
243
+ status: 'red', file: first.file, testName: first.testName, durationMs: Date.now() - retryStartedAt,
244
+ requestedSync: 'restart', lastSync: 'restart', baselineVersion: this.baseline?.version ?? first.baselineVersion,
245
+ failure: { message },
246
+ });
254
247
  }
255
248
  }
256
- return first;
249
+ return { ...first, attempts };
257
250
  };
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.
251
+ // Resolve the caller early. Keep the queue occupied until the active stage finishes.
252
+ let timeoutResult;
260
253
  const timer = setTimeout(() => {
261
- const timeoutResult = this.timeoutResult(testName, timeoutMs);
254
+ deadline.abort();
255
+ timeoutResult = { ...this.timeoutResult(testName, timeoutMs), attempts: attempts.slice() };
262
256
  this.lastResult = timeoutResult;
263
257
  this.markUpdated();
264
258
  this.persistStatus();
@@ -266,71 +260,29 @@ export class TddRuntime {
266
260
  }, timeoutMs);
267
261
  try {
268
262
  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;
263
+ deadline.signal.throwIfAborted();
264
+ this.lastResult = result;
278
265
  this.markUpdated();
279
266
  this.persistStatus();
280
- deferred.resolve(finalResult);
281
- return finalResult;
267
+ deferred.resolve(result);
268
+ return result;
282
269
  }
283
270
  catch (error) {
284
- clearTimeout(timer);
271
+ if (timeoutResult) {
272
+ if (timeoutResult.attempts?.length !== attempts.length) {
273
+ timeoutResult = { ...timeoutResult, attempts };
274
+ this.lastResult = timeoutResult;
275
+ this.markUpdated();
276
+ this.persistStatus();
277
+ }
278
+ return timeoutResult;
279
+ }
285
280
  deferred.reject(error);
286
281
  throw error;
287
282
  }
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;
283
+ finally {
284
+ clearTimeout(timer);
331
285
  }
332
- const trace = { mode: repairOpts.mode, steps, capped };
333
- return { ...current, repair: trace };
334
286
  }
335
287
  timeoutResult(testName, timeoutMs) {
336
288
  const focused = this.focusedTest;
@@ -356,7 +308,7 @@ export class TddRuntime {
356
308
  unsupportedState: undefined,
357
309
  };
358
310
  }
359
- async performCycle(testName, opts) {
311
+ async performCycle(testName, requestedSync, fullReset, deadline) {
360
312
  if (!this.started)
361
313
  throw new Error('TddRuntime is not started.');
362
314
  const focused = this.focusedTest;
@@ -364,13 +316,15 @@ export class TddRuntime {
364
316
  throw new Error('No focused test. Call focus(file, testName) before cycle().');
365
317
  const actualTestName = testName ?? focused.testName;
366
318
  const startedAt = Date.now();
367
- const requestedSync = opts.sync ?? 'none';
368
- const resolvedSync = requestedSync === 'auto' ? decideSync(opts.changes) : requestedSync;
369
319
  let lastSync = 'none';
370
320
  try {
371
- lastSync = await this.controlPhase(() => this.sync(resolvedSync));
321
+ lastSync = await this.controlPhase(() => {
322
+ deadline.throwIfAborted();
323
+ return this.sync(requestedSync);
324
+ });
372
325
  }
373
326
  catch (error) {
327
+ deadline.throwIfAborted();
374
328
  const baselineVersion = this.baseline?.version ?? 0;
375
329
  const message = error instanceof Error ? error.message : String(error);
376
330
  return {
@@ -391,12 +345,14 @@ export class TddRuntime {
391
345
  }),
392
346
  };
393
347
  }
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
- }));
348
+ deadline.throwIfAborted();
349
+ const resetReport = this.defaultScenarioName
350
+ ? { version: this.requireBaseline().version, unsupported: [] }
351
+ : await this.controlPhase(() => {
352
+ deadline.throwIfAborted();
353
+ return this.requireBaseline().reset(this.baselineConfig, { full: fullReset ?? lastSync === 'restart' });
354
+ });
355
+ deadline.throwIfAborted();
400
356
  const outcome = await this.executor.rerun(focused.file, actualTestName);
401
357
  const unsupportedState = resetReport.unsupported;
402
358
  const failureContext = outcome.status === 'red'
@@ -503,7 +459,10 @@ export class TddRuntime {
503
459
  if (!this.app) {
504
460
  if (sync === 'restart')
505
461
  throw new Error('Hot restart requires a daemon-started app.');
506
- await this.requireDriver().reloadSources?.();
462
+ const driver = this.requireDriver();
463
+ if (!driver.reloadSources)
464
+ throw new Error('Connected driver does not support hot reload.');
465
+ await driver.reloadSources();
507
466
  return 'reload';
508
467
  }
509
468
  if (sync === 'reload') {
@@ -545,6 +504,8 @@ export class TddRuntime {
545
504
  this.app = undefined;
546
505
  this.vmServiceUrl = undefined;
547
506
  this.configRoot = undefined;
507
+ this.sharedConfig = undefined;
508
+ this.defaultScenarioName = undefined;
548
509
  this.startAppParams = undefined;
549
510
  this.baseline = undefined;
550
511
  this.focusedTest = undefined;
@@ -571,7 +532,9 @@ function startOptsSignature(opts) {
571
532
  configRoot: opts.configRoot,
572
533
  sharedConfig: opts.sharedConfig,
573
534
  launchMode: opts.launchMode ?? (opts.app ? 'start' : 'attach'),
574
- scenario: opts.scenario ?? defaultScenario,
535
+ baselineConfig: opts.baselineConfig ?? defaultBaseline,
536
+ defaultScenario: opts.defaultScenario,
537
+ statusFilePath: opts.statusFilePath,
575
538
  vmServiceUrl: opts.vmServiceUrl,
576
539
  });
577
540
  }
package/dist/types.d.ts CHANGED
@@ -1,8 +1,10 @@
1
- import type { RepairProposal, RepairResult } from '@fliwright/core';
1
+ import type { PersistentTestExecutor } from './executor/PersistentTestExecutor.js';
2
+ import type { ResetContext } from './baseline/BaselineManager.js';
2
3
  import type { AppHandle, AppStartParams } from './daemon/DaemonTransport.js';
3
4
  import type { TddFailureContext } from './diagnostics/TddFailureContext.js';
4
5
  export type ResetCategory = 'navigation' | 'riverpod' | 'mock' | 'storage' | 'secureStorage' | 'authTokens' | 'webview' | 'localDb' | 'timers' | 'isolates' | 'permissions';
5
- export interface Scenario {
6
+ /** Low-level reset options. Business setup uses a named TestScenario via defaultScenario. */
7
+ export interface BaselineConfig {
6
8
  homeRoute: string;
7
9
  resetCategories: ResetCategory[];
8
10
  riverpodOverrides?: unknown[];
@@ -29,7 +31,7 @@ export interface RuntimeSnapshot {
29
31
  launchMode: 'start' | 'attach';
30
32
  restartCapable: boolean;
31
33
  driverConnections: number;
32
- fixtureDriverSharing: 'in-process-provider' | 'vm-service-url';
34
+ fixtureDriverSharing: 'vm-service-url';
33
35
  notes?: string[];
34
36
  focusedTest?: {
35
37
  file: string;
@@ -46,13 +48,13 @@ export interface StartOpts {
46
48
  vmServiceUrl?: string;
47
49
  configRoot: string;
48
50
  launchMode?: 'start' | 'attach';
49
- scenario?: Scenario;
51
+ baselineConfig?: BaselineConfig;
50
52
  defaultScenario?: string;
51
53
  /**
52
54
  * Optional path the runtime writes its {@link RuntimeSnapshot} to after each state change
53
55
  * (start/focus/cycle/reconnect/stop), as a best-effort, non-blocking JSON dump. Lets read-only
54
56
  * monitors (e.g. the VS Code TDD Loop panel) observe the loop without a second driver connection.
55
- * Defaults to `<projectRoot>/.fliwright/tdd-status.json` when set by the CLI layer.
57
+ * Defaults to `~/.fliwright/<project-path>/runtime/tdd-status.json` when set by the CLI layer.
56
58
  */
57
59
  statusFilePath?: string;
58
60
  }
@@ -77,77 +79,6 @@ export interface CycleOpts {
77
79
  * never overlaps the single-threaded executor. Design §8 Timeout. Default {@link DEFAULT_CYCLE_TIMEOUT_MS}.
78
80
  */
79
81
  timeoutMs?: number;
80
- /**
81
- * Run an inline AI repair closed loop (design §7 P3 / §10 P3). When set, a red initial cycle is
82
- * followed by repair → cycle again, up to {@link TddRepairOpts.iterations} (default 3).
83
- * - `'suggest'`: stop after emitting the repair diff/plan (no apply, no loop).
84
- * - `'safe-apply'`: apply only guarded safe repairs and loop until green or the cap.
85
- * Additive: omitted → identical to today's behavior. Requires a repair planner wired into
86
- * {@link TddRuntimeDeps.repair}.
87
- */
88
- repair?: TddRepairOpts;
89
- }
90
- /**
91
- * Options for the AI repair closed loop (design §7 P3).
92
- *
93
- * - `'suggest'` emits a repair plan (diff + proposed safe actions) for agent approval and applies
94
- * nothing; the loop does not iterate.
95
- * - `'safe-apply'` applies only guarded safe repairs (those that pass the AgentRepair guardrail)
96
- * and loops `cycle(red) → repair → cycle` until green or the iteration cap.
97
- */
98
- export interface TddRepairOpts {
99
- mode: 'suggest' | 'safe-apply';
100
- /**
101
- * Maximum number of repair→cycle iterations in safe-apply mode. Default 3. Ignored for 'suggest'
102
- * (which never loops). The cap prevents unbounded AI edits; reaching it still red is a terminal
103
- * state surfaced to the agent.
104
- */
105
- iterations?: number;
106
- }
107
- /**
108
- * One proposed repair action with its guardrail verdict. `safe` is true only when the AgentRepair
109
- * `validate()` guard accepts it (i.e. it is a bounded runtime action, never a `codePatch`).
110
- */
111
- export interface TddRepairProposalEntry {
112
- proposal: RepairProposal;
113
- /** True when the guardrail accepts this proposal; false when rejected as unsafe/unsupported. */
114
- safe: boolean;
115
- /** Rejection reason from the guardrail, when `safe` is false. */
116
- reason?: string;
117
- }
118
- /**
119
- * A repair plan: the proposed patch text (for agent approval / `suggest` mode) plus the individual
120
- * repair actions and their guardrail verdicts. In `suggest` mode this is returned without applying;
121
- * in `safe-apply` mode only the `safe` entries are executed.
122
- */
123
- export interface TddRepairPlan {
124
- mode: 'suggest' | 'safe-apply';
125
- /** Human/agent-readable patch/diff describing the proposed minimal fix. */
126
- diff: string;
127
- /** Individual proposed repair actions with their guardrail verdicts. */
128
- proposals: TddRepairProposalEntry[];
129
- }
130
- /**
131
- * The outcome of one repair step inside the closed loop: the plan proposed, and (in safe-apply mode)
132
- * the AgentRepair execute results for the actions actually attempted.
133
- */
134
- export interface TddRepairStep {
135
- /** 1-based index of this repair iteration within the loop. */
136
- iteration: number;
137
- plan: TddRepairPlan;
138
- /** Only populated in safe-apply mode: one AgentRepair result per safe proposal that was executed. */
139
- applied?: RepairResult[];
140
- }
141
- /**
142
- * The full repair trace returned by the closed loop. Empty when no repair was requested, when the
143
- * initial cycle was already green, or when no repair planner is configured.
144
- */
145
- export interface TddRepairTrace {
146
- mode: 'suggest' | 'safe-apply';
147
- /** Per-iteration repair steps (one for each cycle(red) → repair pass). */
148
- steps: TddRepairStep[];
149
- /** True when the iteration cap was reached while still red. */
150
- capped: boolean;
151
82
  }
152
83
  /** Default per-cycle timeout (design §8). Generous: real reruns are sub-second; restarts are seconds. */
153
84
  export declare const DEFAULT_CYCLE_TIMEOUT_MS = 60000;
@@ -159,6 +90,8 @@ export interface TddCycleResult {
159
90
  lastSync: 'reload' | 'restart' | 'none';
160
91
  /** True only when an automatic reload failure retry escalated this cycle to one restart. */
161
92
  syncEscalated?: boolean;
93
+ /** Ordered results for the completed attempts in this cycle, including failed restart retries. */
94
+ attempts?: TddCycleAttempt[];
162
95
  baselineVersion: number;
163
96
  failure?: {
164
97
  message?: string;
@@ -169,6 +102,10 @@ export interface TddCycleResult {
169
102
  timelineNodeId?: string;
170
103
  unsupportedState?: ResetCategory[];
171
104
  }
105
+ export interface TddCycleAttempt extends Omit<TddCycleResult, 'attempts' | 'syncEscalated'> {
106
+ /** Resolved sync mode requested for this attempt. `lastSync` records the confirmed mode. */
107
+ requestedSync: TddCycleResult['lastSync'];
108
+ }
172
109
  export interface TddSyncResult {
173
110
  lastSync: TddCycleResult['lastSync'];
174
111
  snapshot: RuntimeSnapshot;
@@ -184,131 +121,19 @@ export interface TddRuntimeDeps {
184
121
  keepAppAlive?: boolean;
185
122
  }): Promise<void>;
186
123
  };
187
- executor?: {
188
- boot(opts: {
189
- sharedConfig?: StartOpts['sharedConfig'];
190
- configRoot: string;
191
- vmServiceUrl?: string;
192
- driverProvider: () => Promise<unknown>;
193
- defaultScenario?: string;
194
- scenarioMode?: 'managed-start' | 'attach';
195
- }): Promise<void>;
196
- rerun(file: string, testName?: string): Promise<{
197
- status: 'red' | 'green';
198
- testName?: string;
199
- failure?: {
200
- message?: string;
201
- };
202
- timelinePath?: string;
203
- timelineNodeId?: string;
204
- failureDetails?: {
205
- source?: {
206
- file: string;
207
- line: number;
208
- snippet: string;
209
- };
210
- assertion?: {
211
- matcher: string;
212
- expected: string;
213
- actual: string;
214
- timeout: number;
215
- };
216
- artifacts?: {
217
- failureContextPath?: string;
218
- screenshotPath?: string;
219
- screenshotBase64?: string;
220
- widgetTree?: unknown;
221
- timelinePath?: string;
222
- timelineNodeId?: string;
223
- };
224
- };
225
- }>;
226
- dispose(): Promise<void>;
227
- };
228
- driverFactory?: () => {
124
+ executor?: Pick<PersistentTestExecutor, 'boot' | 'rerun' | 'dispose'>;
125
+ driverFactory?: () => ResetContext['driver'] & {
229
126
  connect(vmServiceUrl: string): Promise<void>;
230
127
  dispose(options?: {
231
128
  signal?: AbortSignal;
232
129
  }): Promise<void>;
233
- page: {
234
- resetToHome(options?: {
235
- homeRoute?: string;
236
- }): Promise<void>;
237
- };
238
- mock: {
239
- clear(): Promise<void>;
240
- clearCalls(): Promise<void>;
241
- loadRules?(mockDir?: string): Promise<void>;
242
- listRules?(): Array<{
243
- endpoint: string;
244
- method: string;
245
- rules: string[];
246
- activeRule: string;
247
- }>;
248
- switchRule?(endpoint: string, ruleName: string, method?: string): Promise<void>;
249
- };
250
- state?: {
251
- override(key: string, value: unknown): Promise<void>;
252
- };
253
- storage?: {
254
- reset(seed?: Record<string, unknown>): Promise<{
255
- status: 'ok' | 'unsupported';
256
- clearedKeys?: number;
257
- seededKeys?: number;
258
- message?: string;
259
- }>;
260
- };
261
- app?: {
262
- hasCapability?(name: string): Promise<boolean>;
263
- listCapabilities?(): Promise<Array<{
264
- name: string;
265
- methods: string[];
266
- }>>;
267
- invoke(capability: string, method: string, input?: unknown): Promise<unknown>;
268
- };
130
+ /** Resolves on confirmed VM reload, rejects if reload fails. */
269
131
  reloadSources?(): Promise<unknown>;
270
132
  };
271
133
  baseline?: {
272
- reset(scenario: Scenario, opts: {
134
+ reset(scenario: BaselineConfig, opts: {
273
135
  full?: boolean;
274
136
  }): Promise<ResetReport>;
275
137
  get version(): number;
276
138
  };
277
- /**
278
- * Optional AI repair planner (design §6.2 `repair?: AgentRepair`, wired in P3). When absent, the
279
- * cycle behaves identically to today (no repair loop). When present, a cycle requested with
280
- * {@link CycleOpts.repair} runs the closed loop: cycle(red) → repair → cycle, capped by an
281
- * iteration limit, applying only guardrail-safe repairs in 'safe-apply' mode.
282
- *
283
- * Exposed as a minimal interface so production can pass a `TddRepairPlanner` while tests inject a
284
- * fake without depending on `@fliwright/core`'s `AgentRepair` directly.
285
- */
286
- repair?: TddRepairPlannerLike;
287
- }
288
- /**
289
- * Minimal repair-planner contract injected into {@link TddRuntimeDeps.repair}. Production wires a
290
- * {@link TddRepairPlanner} backed by `@fliwright/core`'s `AgentRepair`; tests pass a fake that
291
- * proposes deterministic patches.
292
- */
293
- export interface TddRepairPlannerLike {
294
- /**
295
- * Propose a minimal repair plan for a red cycle result.
296
- *
297
- * - `'suggest'`: returns the plan (diff + proposed actions with guardrail verdicts) and applies
298
- * nothing. The loop does not iterate.
299
- * - `'safe-apply'`: applies only the guardrail-safe proposals via the underlying `AgentRepair`
300
- * and returns the plan plus the execute results for the attempted actions.
301
- */
302
- propose(result: TddCycleResult, mode: 'suggest' | 'safe-apply'): Promise<TddRepairPlan & {
303
- applied?: RepairResult[];
304
- }>;
305
- }
306
- /**
307
- * Result of a cycle that ran the optional repair closed loop. When no repair was requested the
308
- * runtime returns a plain {@link TddCycleResult}; when {@link CycleOpts.repair} is set, the cycle
309
- * returns this shape carrying the final cycle outcome plus the repair trace.
310
- */
311
- export interface TddRepairCycleResult extends TddCycleResult {
312
- /** Repair trace: diffs suggested/applied across the loop. Empty iff the initial cycle was green. */
313
- repair: TddRepairTrace;
314
139
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@fliwright/tdd",
3
- "version": "0.1.0",
4
- "description": "Experimental persistent red-green-refactor workflows for Fliwright.",
3
+ "version": "0.1.1",
4
+ "description": "Experimental persistent focused test execution and Flutter synchronization for Fliwright.",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -29,8 +29,8 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "vitest": "5.0.5",
32
- "@fliwright/core": "0.1.0",
33
- "@fliwright/vitest": "0.1.0"
32
+ "@fliwright/core": "0.1.1",
33
+ "@fliwright/vitest": "0.1.1"
34
34
  },
35
35
  "devDependencies": {
36
36
  "typescript": "^5.5.0"