@fliwright/cli 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 (81) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +59 -2
  3. package/dist/ArtifactReferences.d.ts +7 -0
  4. package/dist/ArtifactReferences.js +82 -0
  5. package/dist/CommandRegistry.d.ts +40 -0
  6. package/dist/CommandRegistry.js +177 -0
  7. package/dist/InspectionOutput.d.ts +5 -0
  8. package/dist/InspectionOutput.js +11 -0
  9. package/dist/RecordingReplay.d.ts +24 -0
  10. package/dist/RecordingReplay.js +79 -0
  11. package/dist/WorkflowContext.d.ts +20 -0
  12. package/dist/WorkflowContext.js +1 -0
  13. package/dist/capabilities/form.d.ts +13 -0
  14. package/dist/capabilities/form.js +9 -0
  15. package/dist/capabilities/interaction.d.ts +226 -0
  16. package/dist/capabilities/interaction.js +447 -0
  17. package/dist/capabilities/session.d.ts +18 -0
  18. package/dist/capabilities/session.js +55 -0
  19. package/dist/catalog.d.ts +36 -0
  20. package/dist/catalog.js +69 -0
  21. package/dist/commands/app-inspect.d.ts +96 -0
  22. package/dist/commands/app-inspect.js +70 -0
  23. package/dist/commands/app.d.ts +53 -0
  24. package/dist/commands/app.js +104 -0
  25. package/dist/commands/artifact-query.d.ts +138 -0
  26. package/dist/commands/artifact-query.js +81 -0
  27. package/dist/commands/artifacts.d.ts +40 -0
  28. package/dist/commands/artifacts.js +311 -0
  29. package/dist/commands/doctor.d.ts +11 -0
  30. package/dist/commands/doctor.js +285 -0
  31. package/dist/commands/flow-runtime.d.ts +40 -0
  32. package/dist/commands/flow-runtime.js +37 -0
  33. package/dist/commands/flow.d.ts +122 -0
  34. package/dist/commands/flow.js +236 -0
  35. package/dist/commands/generate-test.d.ts +46 -0
  36. package/dist/commands/generate-test.js +233 -0
  37. package/dist/commands/init.d.ts +22 -0
  38. package/dist/commands/init.js +262 -0
  39. package/dist/commands/mock-management.d.ts +53 -0
  40. package/dist/commands/mock-management.js +65 -0
  41. package/dist/commands/mock.d.ts +8 -0
  42. package/dist/commands/mock.js +27 -0
  43. package/dist/commands/record.d.ts +55 -0
  44. package/dist/commands/record.js +216 -0
  45. package/dist/commands/run.d.ts +93 -0
  46. package/dist/commands/run.js +707 -0
  47. package/dist/commands/scenario.d.ts +26 -0
  48. package/dist/commands/scenario.js +39 -0
  49. package/dist/commands/tdd.d.ts +72 -0
  50. package/dist/commands/tdd.js +218 -0
  51. package/dist/config.d.ts +20 -0
  52. package/dist/config.js +40 -0
  53. package/dist/index.d.ts +10 -0
  54. package/dist/index.js +139 -0
  55. package/dist/registry/devices.d.ts +2 -0
  56. package/dist/registry/devices.js +12 -0
  57. package/dist/registry/finite.d.ts +38 -0
  58. package/dist/registry/finite.js +121 -0
  59. package/dist/registry/flow-schemas.d.ts +405 -0
  60. package/dist/registry/flow-schemas.js +98 -0
  61. package/dist/registry/flow.d.ts +3 -0
  62. package/dist/registry/flow.js +56 -0
  63. package/dist/registry/generation-schema.d.ts +112 -0
  64. package/dist/registry/generation-schema.js +36 -0
  65. package/dist/registry/session.d.ts +2 -0
  66. package/dist/registry/session.js +24 -0
  67. package/dist/registry/tdd.d.ts +3 -0
  68. package/dist/registry/tdd.js +118 -0
  69. package/dist/reporter.d.ts +95 -0
  70. package/dist/reporter.js +61 -0
  71. package/dist/run.d.ts +6 -0
  72. package/dist/run.js +5 -0
  73. package/dist/session/ConnectionHost.d.ts +43 -0
  74. package/dist/session/ConnectionHost.js +129 -0
  75. package/dist/session/client.d.ts +38 -0
  76. package/dist/session/client.js +120 -0
  77. package/dist/session/worker.d.ts +1 -0
  78. package/dist/session/worker.js +161 -0
  79. package/dist/vm-discovery.d.ts +14 -0
  80. package/dist/vm-discovery.js +85 -0
  81. package/package.json +78 -3
@@ -0,0 +1,56 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { z } from 'zod';
4
+ import { CliError } from '../CommandRegistry.js';
5
+ import * as flow from '../commands/flow.js';
6
+ import * as runtime from '../commands/flow-runtime.js';
7
+ import * as schemas from './flow-schemas.js';
8
+ import { connection } from './finite.js';
9
+ export function registerFlow(registry, deps = {}) {
10
+ const commands = [
11
+ ['list', schemas.FlowListParamsSchema, flow.flowListCommand],
12
+ ['get', schemas.FlowGetParamsSchema, flow.flowGetCommand],
13
+ ['bind-figma', schemas.FlowBindFigmaParamsSchema, flow.flowBindFigmaCommand],
14
+ ['agent-spec', schemas.FlowAgentSpecParamsSchema, flow.flowAgentSpecCommand],
15
+ ['clean', schemas.FlowCleanParamsSchema, flow.flowCleanCommand],
16
+ ['review-plan', schemas.FlowReviewPlanParamsSchema, flow.flowReviewPlanCommand],
17
+ ['review-bundle', schemas.FlowReviewBundleParamsSchema, flow.flowReviewBundleCommand],
18
+ ['review-capture-figma', schemas.FlowReviewCaptureFigmaParamsSchema, flow.flowReviewCaptureFigmaCommand],
19
+ ['review-report', schemas.FlowReviewReportParamsSchema, flow.flowReviewReportCommand],
20
+ ['generate-test', schemas.FlowGenerateTestParamsSchema, flow.flowGenerateTestCommand],
21
+ ['validate', schemas.FlowValidateParamsSchema, flow.flowValidateCommand],
22
+ ['review-capture-runtime', schemas.FlowReviewCaptureRuntimeParamsSchema.extend(connection), runtime.flowReviewCaptureRuntimeCommand],
23
+ ['review-run', schemas.FlowReviewRunParamsSchema.extend(connection), runtime.flowReviewRunCommand],
24
+ ];
25
+ for (const [name, input, execute] of commands)
26
+ registry.add({
27
+ path: `flow.${name}`, description: `Flow ${name}`, input, positional: name === 'list' ? [] : ['id'],
28
+ needsApp: name === 'review-run' || name === 'review-capture-runtime', effects: ['flow-artifacts'],
29
+ async execute(input, context) {
30
+ if (name === 'review-report') {
31
+ for (const key of ['runtimeCaptures', 'figmaCaptures']) {
32
+ const fileKey = `${key}File`;
33
+ const reportInput = input;
34
+ if (reportInput[fileKey] !== undefined) {
35
+ if (reportInput[key] !== undefined)
36
+ throw new CliError('INVALID_INPUT', `Choose ${key} or ${fileKey}.`, 2);
37
+ const body = await readFile(resolve(context.cwd, String(reportInput[fileKey])), 'utf8');
38
+ let parsed;
39
+ try {
40
+ parsed = JSON.parse(body);
41
+ }
42
+ catch {
43
+ throw new CliError('INVALID_INPUT', `${fileKey} must contain a JSON array.`, 2);
44
+ }
45
+ reportInput[key] = z.array(schemas.FlowReviewArtifactSchema).parse(parsed);
46
+ }
47
+ }
48
+ }
49
+ const data = await execute({ ...input, cwd: context.cwd, signal: context.signal }, deps);
50
+ if (data.validation?.errorCount > 0 || data.report?.summary.failed > 0 || data.report?.summary.missing > 0 || data.captures?.some((capture) => capture.status === 'failed')) {
51
+ throw new CliError('VALIDATION_FAILED', 'Flow validation or review failed.', 1, data);
52
+ }
53
+ return data;
54
+ },
55
+ });
56
+ }
@@ -0,0 +1,112 @@
1
+ import { z } from 'zod';
2
+ export declare const GenerateTestParamsSchema: z.ZodObject<{
3
+ mode: z.ZodDefault<z.ZodOptional<z.ZodEnum<["default", "red-first"]>>>;
4
+ spec: z.ZodOptional<z.ZodObject<{
5
+ app: z.ZodOptional<z.ZodAny>;
6
+ initialState: z.ZodOptional<z.ZodAny>;
7
+ elements: z.ZodArray<z.ZodAny, "many">;
8
+ flows: z.ZodArray<z.ZodAny, "many">;
9
+ assertions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
10
+ }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
11
+ app: z.ZodOptional<z.ZodAny>;
12
+ initialState: z.ZodOptional<z.ZodAny>;
13
+ elements: z.ZodArray<z.ZodAny, "many">;
14
+ flows: z.ZodArray<z.ZodAny, "many">;
15
+ assertions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
16
+ }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
17
+ app: z.ZodOptional<z.ZodAny>;
18
+ initialState: z.ZodOptional<z.ZodAny>;
19
+ elements: z.ZodArray<z.ZodAny, "many">;
20
+ flows: z.ZodArray<z.ZodAny, "many">;
21
+ assertions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
22
+ }, z.ZodTypeAny, "passthrough">>>;
23
+ flowId: z.ZodOptional<z.ZodString>;
24
+ allFlows: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
25
+ flowIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
26
+ testNamePrefix: z.ZodOptional<z.ZodString>;
27
+ source: z.ZodOptional<z.ZodString>;
28
+ snapshot: z.ZodOptional<z.ZodString>;
29
+ refs: z.ZodOptional<z.ZodArray<z.ZodObject<{
30
+ role: z.ZodString;
31
+ label: z.ZodString;
32
+ key: z.ZodOptional<z.ZodString>;
33
+ type: z.ZodOptional<z.ZodString>;
34
+ selector: z.ZodOptional<z.ZodString>;
35
+ textField: z.ZodOptional<z.ZodBoolean>;
36
+ }, "strip", z.ZodTypeAny, {
37
+ role: string;
38
+ label: string;
39
+ type?: string | undefined;
40
+ key?: string | undefined;
41
+ selector?: string | undefined;
42
+ textField?: boolean | undefined;
43
+ }, {
44
+ role: string;
45
+ label: string;
46
+ type?: string | undefined;
47
+ key?: string | undefined;
48
+ selector?: string | undefined;
49
+ textField?: boolean | undefined;
50
+ }>, "many">>;
51
+ description: z.ZodOptional<z.ZodString>;
52
+ testName: z.ZodOptional<z.ZodString>;
53
+ resetToHomeBeforeEach: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
54
+ homeRoute: z.ZodDefault<z.ZodOptional<z.ZodString>>;
55
+ outputFile: z.ZodOptional<z.ZodString>;
56
+ }, "strip", z.ZodTypeAny, {
57
+ mode: "default" | "red-first";
58
+ resetToHomeBeforeEach: boolean;
59
+ homeRoute: string;
60
+ allFlows: boolean;
61
+ description?: string | undefined;
62
+ source?: string | undefined;
63
+ testName?: string | undefined;
64
+ snapshot?: string | undefined;
65
+ outputFile?: string | undefined;
66
+ spec?: z.objectOutputType<{
67
+ app: z.ZodOptional<z.ZodAny>;
68
+ initialState: z.ZodOptional<z.ZodAny>;
69
+ elements: z.ZodArray<z.ZodAny, "many">;
70
+ flows: z.ZodArray<z.ZodAny, "many">;
71
+ assertions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
72
+ }, z.ZodTypeAny, "passthrough"> | undefined;
73
+ flowIds?: string[] | undefined;
74
+ flowId?: string | undefined;
75
+ testNamePrefix?: string | undefined;
76
+ refs?: {
77
+ role: string;
78
+ label: string;
79
+ type?: string | undefined;
80
+ key?: string | undefined;
81
+ selector?: string | undefined;
82
+ textField?: boolean | undefined;
83
+ }[] | undefined;
84
+ }, {
85
+ description?: string | undefined;
86
+ mode?: "default" | "red-first" | undefined;
87
+ source?: string | undefined;
88
+ testName?: string | undefined;
89
+ snapshot?: string | undefined;
90
+ resetToHomeBeforeEach?: boolean | undefined;
91
+ homeRoute?: string | undefined;
92
+ outputFile?: string | undefined;
93
+ spec?: z.objectInputType<{
94
+ app: z.ZodOptional<z.ZodAny>;
95
+ initialState: z.ZodOptional<z.ZodAny>;
96
+ elements: z.ZodArray<z.ZodAny, "many">;
97
+ flows: z.ZodArray<z.ZodAny, "many">;
98
+ assertions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
99
+ }, z.ZodTypeAny, "passthrough"> | undefined;
100
+ flowIds?: string[] | undefined;
101
+ flowId?: string | undefined;
102
+ testNamePrefix?: string | undefined;
103
+ allFlows?: boolean | undefined;
104
+ refs?: {
105
+ role: string;
106
+ label: string;
107
+ type?: string | undefined;
108
+ key?: string | undefined;
109
+ selector?: string | undefined;
110
+ textField?: boolean | undefined;
111
+ }[] | undefined;
112
+ }>;
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ export const GenerateTestParamsSchema = z.object({
3
+ mode: z.enum(['default', 'red-first']).optional().default('default')
4
+ .describe("Generation mode. Use 'red-first' with spec for TDD-oriented tests."),
5
+ spec: z.object({
6
+ app: z.any().optional(),
7
+ initialState: z.any().optional(),
8
+ elements: z.array(z.any()),
9
+ flows: z.array(z.any()),
10
+ assertions: z.array(z.any()).optional(),
11
+ }).passthrough().optional().describe('InteractionSpec from design/intention parsing for red-first TDD generation'),
12
+ flowId: z.string().optional().describe('Flow id to generate when mode is red-first and spec contains multiple flows'),
13
+ allFlows: z.boolean().optional().default(false)
14
+ .describe('Generate one red-first test for every selected flow in the InteractionSpec'),
15
+ flowIds: z.array(z.string()).optional()
16
+ .describe('Subset of flow ids to generate when allFlows is true'),
17
+ testNamePrefix: z.string().optional()
18
+ .describe('Prefix to apply to generated suite test names when allFlows is true'),
19
+ source: z.string().optional().describe('Flutter/Dart source code of the page or widget to test'),
20
+ snapshot: z.string().optional().describe('Agent-readable snapshot text from fliwright app snapshot'),
21
+ refs: z.array(z.object({
22
+ role: z.string(),
23
+ label: z.string(),
24
+ key: z.string().optional(),
25
+ type: z.string().optional(),
26
+ selector: z.string().optional(),
27
+ textField: z.boolean().optional(),
28
+ })).optional().describe('Structured refs from fliwright app snapshot'),
29
+ description: z.string().optional().describe('Natural language description of what the test should verify'),
30
+ testName: z.string().optional().describe('Name for the generated test'),
31
+ resetToHomeBeforeEach: z.boolean().optional().default(true)
32
+ .describe('Whether to generate a beforeEach hook that navigates to the home route before each test'),
33
+ homeRoute: z.string().optional().default('/')
34
+ .describe('Route used by the generated beforeEach home reset hook'),
35
+ outputFile: z.string().optional().describe('Optional path to write the generated test file'),
36
+ });
@@ -0,0 +1,2 @@
1
+ import { type CommandRegistry } from '../CommandRegistry.js';
2
+ export declare function registerSessions(registry: CommandRegistry): void;
@@ -0,0 +1,24 @@
1
+ import { z } from 'zod';
2
+ import { CliError } from '../CommandRegistry.js';
3
+ import { sessionOpenCommand, sessionListCommand, sessionRequest } from '../session/client.js';
4
+ import { str, bool } from './finite.js';
5
+ export function registerSessions(registry) {
6
+ registry.add({ path: 'session.open', description: 'Open an explicit local connection host', effects: ['local-worker', 'app-connection'],
7
+ input: z.object({ vmUrl: str, deviceId: str, target: str, config: str, projectId: str, flutterArgs: z.array(z.string()).optional(), scenario: str }),
8
+ execute: (input, context) => {
9
+ if (input.vmUrl && input.deviceId)
10
+ throw new CliError('INVALID_INPUT', 'Choose vmUrl or deviceId.', 2);
11
+ return sessionOpenCommand({ ...input, cwd: context.cwd }, context.signal);
12
+ } });
13
+ registry.add({ path: 'session.list', description: 'Probe local project connection sessions', effects: [], input: z.object({}), execute: (_input, context) => sessionListCommand(context.cwd) });
14
+ for (const type of ['status', 'close', 'reconnect', 'cancel'])
15
+ registry.add({
16
+ path: `session.${type}`, description: `Connection session ${type}`, effects: type === 'status' ? [] : ['session-state'],
17
+ input: z.object(type === 'cancel' ? { operationId: z.string().regex(/^[a-zA-Z0-9-]{1,64}$/) } : type === 'close' ? { keepAppAlive: bool } : type === 'status' ? { operationId: str } : {}), execute: (input, context) => {
18
+ const session = context.session ?? process.env.FLIWRIGHT_SESSION;
19
+ if (!session)
20
+ throw new CliError('SESSION_REQUIRED', 'Pass --session or FLIWRIGHT_SESSION.', 2);
21
+ return sessionRequest(context.cwd, session, { type, ...input }, context.signal);
22
+ },
23
+ });
24
+ }
@@ -0,0 +1,3 @@
1
+ import { type CommandRegistry } from '../CommandRegistry.js';
2
+ import type { ConnectionHost } from '../session/ConnectionHost.js';
3
+ export declare function registerTdd(registry: CommandRegistry, host?: ConnectionHost): void;
@@ -0,0 +1,118 @@
1
+ import { z } from 'zod';
2
+ import { TddRuntime } from '@fliwright/tdd';
3
+ import { tddStatusCommand, tddSyncCommand } from '../commands/tdd.js';
4
+ import { dirname, extname, resolve } from 'node:path';
5
+ import { ScenarioResolver } from '@fliwright/core';
6
+ import { analyzeInteractionSpecCoverage, validateInteractionSpec, DevAssistCoordinator, defaultStatusFilePath } from '@fliwright/tdd';
7
+ import { CliError } from '../CommandRegistry.js';
8
+ import { generateTestCommand } from '../commands/generate-test.js';
9
+ import { GenerateTestParamsSchema } from './generation-schema.js';
10
+ import { loadConfig, resolveProjectConfig } from '../config.js';
11
+ import { str, bool, positive } from './finite.js';
12
+ const cycle = { testName: str, sync: z.enum(['none', 'reload', 'restart', 'auto']).optional(), fullReset: bool,
13
+ changes: z.array(z.string()).optional(), autoEscalate: bool, timeoutMs: positive };
14
+ const repair = z.object({ mode: z.enum(['suggest', 'safe-apply']), iterations: positive });
15
+ export function registerTdd(registry, host) {
16
+ const add = (name, input, execute, persistent = true) => registry.add({
17
+ path: name, description: name.replaceAll('.', ' '), input, needsSession: persistent, effects: ['tdd-workflow'],
18
+ async execute(input, context) {
19
+ if ((name === 'generate-test' && input.mode === 'red-first') || name === 'tdd.prepare') {
20
+ const check = validateInteractionSpec(input.spec);
21
+ if (!check.ok)
22
+ throw new CliError('INVALID_INPUT', 'Invalid InteractionSpec.', 2, { issues: check.issues });
23
+ }
24
+ if (persistent && !host)
25
+ throw new CliError('SESSION_REQUIRED', 'Use --session from session open for persistent TDD.', 2);
26
+ return execute(input, context);
27
+ },
28
+ });
29
+ add('generate-test', GenerateTestParamsSchema, async (input, context) => generateTestCommand({ ...input, outputFile: input.outputFile ? resolve(context.cwd, input.outputFile) : undefined }, host ? { setTddWorkflowContext: (value) => host.setWorkflow(value) } : undefined), false);
30
+ add('tdd.validate-spec', z.object({ spec: z.unknown() }), (input) => {
31
+ const validation = validateInteractionSpec(input.spec);
32
+ if (!validation.ok)
33
+ throw new CliError('SPEC_INVALID', 'Interaction specification is invalid.', 1, { valid: false, issues: validation.issues });
34
+ return { valid: true, issues: [], coverage: analyzeInteractionSpecCoverage(validation.spec) };
35
+ }, false);
36
+ add('tdd.start', z.object({ config: str, vmUrl: str, deviceId: str, target: str, projectId: str, flutterArgs: z.array(z.string()).optional(),
37
+ mode: z.enum(['run', 'drive']).optional(), scenario: str, statusFile: str }), async (input, context) => {
38
+ if (input.vmUrl && input.deviceId)
39
+ throw new CliError('INVALID_INPUT', 'Choose vmUrl or deviceId.', 2);
40
+ if (input.scenario) {
41
+ const config = await loadConfig(context.cwd);
42
+ new ScenarioResolver(config.scenarios ?? {}).resolve(input.scenario);
43
+ }
44
+ const configRoot = input.config ? resolve(context.cwd, input.config) : context.cwd;
45
+ const sharedConfig = await resolveProjectConfig(extname(configRoot) ? dirname(configRoot) : configRoot);
46
+ const vmServiceUrl = input.vmUrl ?? (!input.deviceId ? host.status().endpoint : undefined);
47
+ const result = await host.startRuntime({ configRoot, vmServiceUrl, sharedConfig,
48
+ app: input.deviceId ? { deviceId: input.deviceId, target: input.target, projectId: input.projectId ?? context.cwd, flutterArgs: input.flutterArgs, mode: input.mode } : undefined,
49
+ launchMode: vmServiceUrl ? 'attach' : 'start', defaultScenario: input.scenario, statusFilePath: input.statusFile ?? defaultStatusFilePath(configRoot) });
50
+ return result;
51
+ });
52
+ add('tdd.status', z.object({}), (_input, context) => host ? host.status() : tddStatusCommand({ configRoot: context.cwd, print: false }), false);
53
+ add('tdd.focus', z.object({ file: str, testName: str }), async (input, context) => {
54
+ const workflow = host.getWorkflow();
55
+ const file = input.file ?? workflow?.testFile;
56
+ if (!file)
57
+ throw new CliError('FOCUS_REQUIRED', 'Pass file or prepare a test with outputFile.', 2);
58
+ await host.getRuntime().focus(resolve(context.cwd, file), input.testName ?? workflow?.testName);
59
+ return host.getRuntime().snapshot();
60
+ });
61
+ const runCycle = async (input) => {
62
+ const data = await host.getRuntime().cycle(input.testName, input);
63
+ if (data.status !== 'green')
64
+ throw new CliError('TEST_FAILED', 'Focused cycle is red.', 1, data);
65
+ return data;
66
+ };
67
+ add('tdd.cycle', z.object({ ...cycle, repair: repair.optional(), file: str, vmUrl: str, deviceId: str, target: str,
68
+ flutterArgs: z.array(z.string()).optional(), scenario: str, keepAppAlive: bool }), async (input, context) => {
69
+ if (host)
70
+ return runCycle(input);
71
+ if (!input.file)
72
+ throw new CliError('INVALID_INPUT', 'Finite cycle requires --file; use --session for persistent focus.', 2);
73
+ const config = await resolveProjectConfig(context.cwd);
74
+ // Resolve early, before app startup. Worker fixtures own per-attempt scenario preparation.
75
+ if (input.scenario)
76
+ new ScenarioResolver(config.scenarios ?? {}).resolve(input.scenario);
77
+ const runtime = new TddRuntime();
78
+ const abort = () => { void runtime.cancel(); };
79
+ context.signal.addEventListener('abort', abort, { once: true });
80
+ try {
81
+ context.signal.throwIfAborted();
82
+ await runtime.start({ configRoot: context.cwd, sharedConfig: config, vmServiceUrl: input.vmUrl ?? config.vmServiceUrl,
83
+ app: input.deviceId ? { deviceId: input.deviceId, target: input.target, projectId: context.cwd, flutterArgs: input.flutterArgs } : undefined,
84
+ defaultScenario: input.scenario });
85
+ await runtime.focus(resolve(context.cwd, input.file), input.testName);
86
+ const data = await runtime.cycle(input.testName, input);
87
+ context.signal.throwIfAborted();
88
+ if (data.status !== 'green')
89
+ throw new CliError('TEST_FAILED', 'Focused cycle is red.', 1, data);
90
+ return data;
91
+ }
92
+ finally {
93
+ context.signal.removeEventListener('abort', abort);
94
+ await runtime.stop({ keepAppAlive: input.keepAppAlive ?? !input.deviceId });
95
+ }
96
+ }, false);
97
+ add('tdd.repair', z.object({ ...cycle, mode: z.enum(['suggest', 'safe-apply']).default('suggest'), iterations: positive }), (input) => runCycle({ ...input, repair: { mode: input.mode, iterations: input.iterations } }));
98
+ add('tdd.reconnect', z.object({}), () => host.reconnectRuntime());
99
+ add('tdd.sync', z.object({ mode: z.enum(['none', 'reload', 'restart']), vmUrl: str, deviceId: str, target: str, keepAppAlive: bool }), (input, context) => host ? host.getRuntime().syncApp(input.mode) : tddSyncCommand({ ...input, sync: input.mode, mode: undefined, configRoot: context.cwd, print: false, signal: context.signal }), false);
100
+ add('tdd.scenario', z.object({ name: z.string().min(1) }), async (input, context) => {
101
+ const config = await loadConfig(context.cwd);
102
+ return host.getRuntime().setTestScenario(new ScenarioResolver(config.scenarios ?? {}).resolve(input.name));
103
+ });
104
+ add('tdd.stop', z.object({ keepAppAlive: bool }), (input) => host.stopRuntime(input.keepAppAlive));
105
+ add('tdd.prepare', GenerateTestParamsSchema.omit({ mode: true }).extend({ spec: z.unknown(), focus: z.boolean().default(true) }), async (input, context) => {
106
+ const result = await generateTestCommand({ ...input, mode: 'red-first', outputFile: input.outputFile ? resolve(context.cwd, input.outputFile) : undefined }, { setTddWorkflowContext: (value) => host.setWorkflow(value) });
107
+ if (input.focus && result.testFile && host.status().tdd) {
108
+ await host.getRuntime().focus(result.testFile, result.tests && result.tests.length > 1 ? undefined : result.testName);
109
+ return { ...result, focused: host.getRuntime().snapshot() };
110
+ }
111
+ return result;
112
+ });
113
+ add('devassist.cycle', z.object({ request: str, devAssistSessionId: str, action: z.enum(['start', 'continue', 'regenerate']).optional(), files: z.array(z.string()).optional(), baseRevision: str }), (input) => {
114
+ if (input.action && input.action !== 'start' && !input.devAssistSessionId)
115
+ throw new CliError('INVALID_INPUT', 'devAssistSessionId is required for continue/regenerate.', 2);
116
+ return new DevAssistCoordinator({ runtime: host.getRuntime() }).cycle(input);
117
+ });
118
+ }
@@ -0,0 +1,95 @@
1
+ export interface CliTestResult {
2
+ name: string;
3
+ passed: boolean;
4
+ duration: number;
5
+ error?: string;
6
+ }
7
+ export interface CliFailureEntry {
8
+ testName: string;
9
+ assertion: {
10
+ matcher: string;
11
+ expected: string;
12
+ actual: string;
13
+ timeout: number;
14
+ };
15
+ widgetTree: object;
16
+ diagnostics?: Array<{
17
+ kind: string;
18
+ timestamp: number;
19
+ data: unknown;
20
+ streamId?: string;
21
+ }>;
22
+ source: {
23
+ file: string;
24
+ line: number;
25
+ snippet: string;
26
+ };
27
+ screenshot?: {
28
+ mimeType: 'image/png';
29
+ base64?: string;
30
+ path?: string;
31
+ };
32
+ healingSuggestion?: {
33
+ originalSelector: string;
34
+ suggestedSelector: string;
35
+ confidence: number;
36
+ scores: {
37
+ position: number;
38
+ context: number;
39
+ codeBinding: number;
40
+ text: number;
41
+ weighted: number;
42
+ };
43
+ };
44
+ timestamp: string;
45
+ }
46
+ export interface CliRunArtifacts {
47
+ runId: string;
48
+ outputDir: string;
49
+ reportPath?: string;
50
+ manifestPath?: string;
51
+ screenshots: string[];
52
+ timelines?: string[];
53
+ }
54
+ export interface TimelineSummary {
55
+ path: string;
56
+ mode?: 'script' | 'test';
57
+ pages: number;
58
+ stepsPassed: number;
59
+ stepsFailed: number;
60
+ screenshots: number;
61
+ firstFailure?: {
62
+ code: string;
63
+ title: string;
64
+ message: string;
65
+ };
66
+ }
67
+ export interface CliRunResult {
68
+ status?: 'running' | 'passed' | 'failed' | 'skipped' | 'interrupted';
69
+ passed: boolean;
70
+ totalTests: number;
71
+ passedTests: number;
72
+ failedTests: number;
73
+ duration: number;
74
+ results: CliTestResult[];
75
+ /** Errors outside test attempts, including collection, suite hooks and worker/process failures. */
76
+ runnerErrors?: Array<{
77
+ phase: string;
78
+ message: string;
79
+ stack?: string;
80
+ file?: string;
81
+ }>;
82
+ failures?: CliFailureEntry[];
83
+ artifacts?: CliRunArtifacts;
84
+ timelines?: TimelineSummary[];
85
+ agentVisibleFailures?: Array<{
86
+ code: string;
87
+ title: string;
88
+ message: string;
89
+ timelineNodeId?: string;
90
+ }>;
91
+ reproduceCommand?: string;
92
+ }
93
+ export declare function formatPretty(result: CliRunResult): string;
94
+ export declare function formatJson(result: CliRunResult): string;
95
+ export declare function formatJunit(result: CliRunResult): string;
@@ -0,0 +1,61 @@
1
+ import chalk from 'chalk';
2
+ export function formatPretty(result) {
3
+ const lines = [];
4
+ const passed = result.results.filter((r) => r.passed);
5
+ const failed = result.results.filter((r) => !r.passed);
6
+ for (const test of passed) {
7
+ lines.push(chalk.green(` ✅ ${test.name} (${test.duration}ms)`));
8
+ }
9
+ for (const test of failed) {
10
+ lines.push(chalk.red(` ❌ ${test.name} (${test.duration}ms)`));
11
+ if (test.error) {
12
+ lines.push(chalk.gray(` → ${test.error.split('\n')[0]}`));
13
+ }
14
+ }
15
+ for (const error of result.runnerErrors ?? []) {
16
+ lines.push(chalk.red(` ❌ ${error.phase}: ${error.message}`));
17
+ }
18
+ lines.push('');
19
+ const summary = `Results: ${chalk.green(`${result.passedTests} passed`)}, ${chalk.red(`${result.failedTests} failed`)} (${result.duration}ms)`;
20
+ lines.push(summary);
21
+ if (result.artifacts?.reportPath) {
22
+ lines.push(chalk.gray(`Report: ${result.artifacts.reportPath}`));
23
+ }
24
+ if (result.artifacts?.screenshots.length) {
25
+ lines.push(chalk.gray(`Screenshots: ${result.artifacts.screenshots.length}`));
26
+ }
27
+ if (result.timelines?.length) {
28
+ const first = result.timelines[0];
29
+ lines.push(chalk.gray(`Timelines: ${result.timelines.length}`));
30
+ lines.push(chalk.gray(`Timeline summary: ${first.pages} page(s), ${first.stepsPassed} passed step(s), ${first.stepsFailed} failed step(s), ${first.screenshots} screenshot(s)`));
31
+ if (first.firstFailure) {
32
+ lines.push(chalk.gray(`First agent-visible failure: ${first.firstFailure.code} - ${first.firstFailure.message}`));
33
+ }
34
+ }
35
+ return lines.join('\n');
36
+ }
37
+ export function formatJson(result) {
38
+ return JSON.stringify(result, null, 2);
39
+ }
40
+ export function formatJunit(result) {
41
+ const escapeXml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
42
+ const testCases = result.results.map((test) => {
43
+ const attrs = `name="${escapeXml(test.name)}" time="${(test.duration / 1000).toFixed(3)}"`;
44
+ if (test.passed) {
45
+ return ` <testcase ${attrs} />`;
46
+ }
47
+ const errorMsg = test.error ? escapeXml(test.error.split('\n')[0]) : 'test failed';
48
+ return ` <testcase ${attrs}>\n <failure message="${errorMsg}" />\n </testcase>`;
49
+ }).join('\n');
50
+ const runnerErrors = result.runnerErrors ?? [];
51
+ const errorCases = runnerErrors.map((error, index) => ` <testcase name="runner ${index + 1}: ${escapeXml(error.phase)}"><error message="${escapeXml(error.message)}">${escapeXml(error.stack ?? error.message)}</error></testcase>`).join('\n');
52
+ return [
53
+ '<?xml version="1.0" encoding="UTF-8"?>',
54
+ '<testsuites>',
55
+ `<testsuite name="fliwright" tests="${result.totalTests + runnerErrors.length}" failures="${result.failedTests}" errors="${runnerErrors.length}" time="${(result.duration / 1000).toFixed(3)}">`,
56
+ testCases,
57
+ errorCases,
58
+ '</testsuite>',
59
+ '</testsuites>',
60
+ ].join('\n');
61
+ }
package/dist/run.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export { parseVitestOutput, runCommand, runVitest, finalizeRunArtifacts, RunFinalizationError, type RunOptions, type RunDeps, } from './commands/run.js';
2
+ export type { CliFailureEntry, CliRunArtifacts, CliRunResult, CliTestResult, } from './reporter.js';
3
+ export { verifyRecordingReplay, type RecordingReplayOptions, type RecordingReplayResult } from './RecordingReplay.js';
4
+ export { artifactsExportCommand, artifactsShowCommand, type ArtifactOptions } from './commands/artifacts.js';
5
+ export { artifactReferences, type ArtifactReference } from './ArtifactReferences.js';
6
+ export { collectCatalog, collectedCases, catalogCaseId, type CatalogCase, type CatalogSelection } from './catalog.js';
package/dist/run.js ADDED
@@ -0,0 +1,5 @@
1
+ export { parseVitestOutput, runCommand, runVitest, finalizeRunArtifacts, RunFinalizationError, } from './commands/run.js';
2
+ export { verifyRecordingReplay } from './RecordingReplay.js';
3
+ export { artifactsExportCommand, artifactsShowCommand } from './commands/artifacts.js';
4
+ export { artifactReferences } from './ArtifactReferences.js';
5
+ export { collectCatalog, collectedCases, catalogCaseId } from './catalog.js';
@@ -0,0 +1,43 @@
1
+ import { TddRuntime } from '@fliwright/tdd';
2
+ import { type CommandContext } from '../CommandRegistry.js';
3
+ import { type AppSessionDeps } from '../capabilities/session.js';
4
+ import type { TddWorkflowContext } from '../WorkflowContext.js';
5
+ /** Owns persistent objects only; run evidence, artifacts and endpoint leases keep their existing owners. */
6
+ export declare class ConnectionHost {
7
+ private readonly options;
8
+ private session?;
9
+ private runtime?;
10
+ private workflow?;
11
+ private queue;
12
+ private closed;
13
+ private closing;
14
+ constructor(options: AppSessionDeps & {
15
+ cwd: string;
16
+ vmUrl?: string;
17
+ id?: string;
18
+ runtimeFactory?: () => TddRuntime;
19
+ });
20
+ open(signal?: AbortSignal): Promise<{
21
+ connected: true;
22
+ }>;
23
+ whenIdle(): Promise<void>;
24
+ refreshEndpoint(): Promise<void>;
25
+ reconnectRuntime(): Promise<unknown>;
26
+ reconnect(): Promise<void>;
27
+ status(): {
28
+ connected: boolean;
29
+ endpoint: string | undefined;
30
+ tdd: import("@fliwright/tdd").RuntimeSnapshot | undefined;
31
+ workflow: TddWorkflowContext | undefined;
32
+ closed: boolean;
33
+ };
34
+ getRuntime(): TddRuntime;
35
+ startRuntime(input: Parameters<TddRuntime['start']>[0]): Promise<import("@fliwright/tdd").RuntimeSnapshot>;
36
+ stopRuntime(keepAppAlive?: boolean): Promise<import("@fliwright/tdd").RuntimeSnapshot>;
37
+ setWorkflow(context: TddWorkflowContext): void;
38
+ getWorkflow(): TddWorkflowContext | undefined;
39
+ execute(command: string, input: unknown, context?: Partial<CommandContext> & {
40
+ onStart?: () => Promise<void>;
41
+ }): Promise<unknown>;
42
+ close(keepAppAlive?: boolean): Promise<void>;
43
+ }