@flowspec-qa/runner 0.3.0 → 0.4.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 (40) hide show
  1. package/dist/commands/capture.d.ts +22 -0
  2. package/dist/commands/capture.d.ts.map +1 -0
  3. package/dist/commands/capture.js +105 -0
  4. package/dist/commands/capture.js.map +1 -0
  5. package/dist/commands/discover.d.ts.map +1 -1
  6. package/dist/commands/discover.js +299 -32
  7. package/dist/commands/discover.js.map +1 -1
  8. package/dist/commands/generate.d.ts +3 -0
  9. package/dist/commands/generate.d.ts.map +1 -0
  10. package/dist/commands/generate.js +61 -0
  11. package/dist/commands/generate.js.map +1 -0
  12. package/dist/commands/ingest.d.ts.map +1 -1
  13. package/dist/commands/ingest.js +9 -1
  14. package/dist/commands/ingest.js.map +1 -1
  15. package/dist/commands/mcp-server.d.ts.map +1 -1
  16. package/dist/commands/mcp-server.js +2 -1
  17. package/dist/commands/mcp-server.js.map +1 -1
  18. package/dist/commands/projects.d.ts.map +1 -1
  19. package/dist/commands/projects.js +34 -0
  20. package/dist/commands/projects.js.map +1 -1
  21. package/dist/commands/record.d.ts +13 -0
  22. package/dist/commands/record.d.ts.map +1 -0
  23. package/dist/commands/record.js +85 -0
  24. package/dist/commands/record.js.map +1 -0
  25. package/dist/commands/report.d.ts +3 -0
  26. package/dist/commands/report.d.ts.map +1 -0
  27. package/dist/commands/report.js +40 -0
  28. package/dist/commands/report.js.map +1 -0
  29. package/dist/commands/run.d.ts.map +1 -1
  30. package/dist/commands/run.js +93 -29
  31. package/dist/commands/run.js.map +1 -1
  32. package/dist/commands/suites.js +1 -1
  33. package/dist/commands/suites.js.map +1 -1
  34. package/dist/index.js +11 -1
  35. package/dist/index.js.map +1 -1
  36. package/dist/project-resolver.d.ts +15 -0
  37. package/dist/project-resolver.d.ts.map +1 -0
  38. package/dist/project-resolver.js +15 -0
  39. package/dist/project-resolver.js.map +1 -0
  40. package/package.json +6 -5
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `flowspecqa capture` — Phase 13 (Manual Capture).
3
+ *
4
+ * Single-shot capture of the current device screen. Used to fill specific
5
+ * evidence gaps that the autonomous Discovery couldn't reach (e.g. a
6
+ * comprobante after PIN/2FA, an error state from a server-side condition).
7
+ *
8
+ * Usage:
9
+ * flowspecqa capture --entity X --label "Comprobante transferencia exitosa"
10
+ *
11
+ * Flow:
12
+ * 1. Auto-pick or accept --device serial.
13
+ * 2. Wake screen + read current hierarchy + take screenshot.
14
+ * 3. Build a single EvidenceRecord with capture_mode='manual'.
15
+ * 4. Upload to backend as a standalone manual capture.
16
+ * 5. Print the next step (validate in UI to promote to baseline).
17
+ *
18
+ * Spec: DISCOVERY_SPEC.md § 13.
19
+ */
20
+ import { Command } from 'commander';
21
+ export declare function captureCommand(): Command;
22
+ //# sourceMappingURL=capture.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capture.d.ts","sourceRoot":"","sources":["../../src/commands/capture.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAMpC,wBAAgB,cAAc,IAAI,OAAO,CAuFxC"}
@@ -0,0 +1,105 @@
1
+ /**
2
+ * `flowspecqa capture` — Phase 13 (Manual Capture).
3
+ *
4
+ * Single-shot capture of the current device screen. Used to fill specific
5
+ * evidence gaps that the autonomous Discovery couldn't reach (e.g. a
6
+ * comprobante after PIN/2FA, an error state from a server-side condition).
7
+ *
8
+ * Usage:
9
+ * flowspecqa capture --entity X --label "Comprobante transferencia exitosa"
10
+ *
11
+ * Flow:
12
+ * 1. Auto-pick or accept --device serial.
13
+ * 2. Wake screen + read current hierarchy + take screenshot.
14
+ * 3. Build a single EvidenceRecord with capture_mode='manual'.
15
+ * 4. Upload to backend as a standalone manual capture.
16
+ * 5. Print the next step (validate in UI to promote to baseline).
17
+ *
18
+ * Spec: DISCOVERY_SPEC.md § 13.
19
+ */
20
+ import { Command } from 'commander';
21
+ import { resolveProjectId } from '../project-resolver.js';
22
+ import chalk from 'chalk';
23
+ import ora from 'ora';
24
+ import { discoveryEngine } from '@flowspec-qa/runner-core';
25
+ export function captureCommand() {
26
+ return new Command('capture')
27
+ .description('Captura manual de una pantalla — útil para llenar gaps que el Discovery autónomo no alcanzó (ej: comprobantes post-2FA)')
28
+ .requiredOption('--entity <id>', 'Entity ID donde guardar la captura')
29
+ .requiredOption('--label <label>', 'Nombre humano del flujo o pantalla (ej: "Comprobante transferencia exitosa")')
30
+ .option('--project <id>', 'Project ID (UUID o nombre like TRUSTBANK)')
31
+ .option('--device <serial>', 'Serial del dispositivo. Auto-detectado si hay uno solo.')
32
+ .option('--app-id <id>', 'App package ID (opcional, mejora trazabilidad)')
33
+ .action(async (options) => {
34
+ // ── Auto-pick device if not specified ─────────────────────────
35
+ let deviceId = options.device;
36
+ if (!deviceId) {
37
+ const { detectAllDevices } = await import('@flowspec-qa/runner-core');
38
+ const ready = detectAllDevices('android').filter((d) => d.status === 'ready');
39
+ if (ready.length === 0) {
40
+ console.error(chalk.red('\n❌ Sin dispositivos Android listos. Conecta uno y habilita USB Debugging.\n'));
41
+ console.log(chalk.dim(' Ejecuta: flowspecqa devices para verificar.'));
42
+ process.exit(1);
43
+ }
44
+ if (ready.length === 1) {
45
+ deviceId = ready[0].id;
46
+ console.log(chalk.dim(`📱 Dispositivo auto-seleccionado: ${chalk.bold(ready[0].name)} (${deviceId})`));
47
+ }
48
+ else {
49
+ console.error(chalk.yellow('\n⚠️ Múltiples dispositivos conectados. Especifica uno con --device <serial>:\n'));
50
+ ready.forEach((d, i) => {
51
+ console.log(` ${i + 1}. ${chalk.bold(d.name.padEnd(28))} ${chalk.dim(d.id)}`);
52
+ });
53
+ process.exit(1);
54
+ }
55
+ }
56
+ // Resolve Project ID
57
+ const { FlowSpecQAApi } = await import('@flowspec-qa/runner-core');
58
+ let projectId;
59
+ try {
60
+ projectId = resolveProjectId(await FlowSpecQAApi.listProjects(), options.project);
61
+ }
62
+ catch (e) {
63
+ console.error(chalk.red(`\n❌ ${e.message}\n`));
64
+ process.exit(1);
65
+ }
66
+ console.log(chalk.cyan(`\n📸 Captura manual — ${chalk.bold(options.label)}`));
67
+ console.log(chalk.gray(` Entidad: ${options.entity}`));
68
+ console.log(chalk.gray(` Dispositivo: ${deviceId}\n`));
69
+ console.log(chalk.dim(' Asegúrate de que la app esté en la pantalla que quieres capturar.\n'));
70
+ const spinner = ora('Capturando estado del dispositivo...').start();
71
+ try {
72
+ const result = await discoveryEngine.captureSingleManualScreen({
73
+ entityId: options.entity,
74
+ projectId,
75
+ label: options.label,
76
+ appId: options.appId,
77
+ deviceId,
78
+ runnerVersion: '0.3.0',
79
+ onProgress: (step, detail) => {
80
+ spinner.text = detail || step;
81
+ },
82
+ });
83
+ spinner.succeed(chalk.green(`Captura registrada: ${chalk.bold(result.record_id.slice(0, 8))} · ` +
84
+ `calidad ${chalk.cyan(result.evidence_quality)} · ` +
85
+ `${result.elements_count} elementos · ` +
86
+ `${result.has_screenshot ? '📷 con screenshot' : '⚠️ sin screenshot'}`));
87
+ console.log('');
88
+ console.log(chalk.bold(' Próximos pasos'));
89
+ console.log(chalk.gray(' ──────────────────────────────────────────'));
90
+ console.log(` ${chalk.cyan('Validar ')} Abre la UI → Entidad ${options.entity} → tab "Baseline"`);
91
+ console.log(` ${chalk.cyan('Promover ')} Click "Validar evidencia" para que pase a baseline canónico`);
92
+ console.log(` ${chalk.cyan('Reusar ')} Próximo \`flowspecqa discover --mode incremental\` saltará esta pantalla`);
93
+ console.log('');
94
+ if (result.evidence_quality !== 'complete') {
95
+ console.log(chalk.yellow(` ⚠️ Calidad ${result.evidence_quality} — `
96
+ + 'considera capturar de nuevo si el screenshot quedó parcial.\n'));
97
+ }
98
+ }
99
+ catch (err) {
100
+ spinner.fail(chalk.red(`Captura fallida: ${err?.message || err}`));
101
+ process.exit(1);
102
+ }
103
+ });
104
+ }
105
+ //# sourceMappingURL=cap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BAAgB,eAAe,IAAI,OAAO,CAwMzC"}
1
+ {"version":3,"file":"discover.d.ts","sourceRoot":"","sources":["../../src/commands/discover.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAMpC,wBAAgB,eAAe,IAAI,OAAO,CA6ezC"}
@@ -1,6 +1,8 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
3
  import inquirer from 'inquirer';
4
+ import path from 'path';
5
+ import { classifyCorpus } from '@flowspec-qa/runner-core';
4
6
  export function discoverCommand() {
5
7
  return new Command('discover')
6
8
  .description('Descubre flujos de la aplicación y genera plan de pruebas con evidencias visuales')
@@ -12,6 +14,7 @@ export function discoverCommand() {
12
14
  .option('--password <password>', 'Contraseña (o env FLOWSPECQA_APP_PASSWORD)')
13
15
  .option('--device <serial>', 'Serial del dispositivo Android (de `flowspecqa devices`). Auto-seleccionado si hay uno solo.')
14
16
  .option('--no-interactive', 'Desactiva el loop interactivo — ejecuta Discovery de una sola pasada')
17
+ .option('--mode <mode>', 'Modo de Discovery: full (default), incremental, recapture, resume', 'full')
15
18
  .action(async (url, options) => {
16
19
  // ── Auto-selección de dispositivo ────────────────────────────────
17
20
  let deviceId = options.device;
@@ -54,8 +57,35 @@ export function discoverCommand() {
54
57
  const detailStr = detail ? chalk.gray(` — ${detail}`) : '';
55
58
  process.stdout.write(`\r${chalk.cyan(' →')} ${label}${detailStr}${' '.repeat(10)}\n`);
56
59
  };
60
+ // ── Validate --mode flag (Phase 8 atomization + Phase 11 incremental) ──
61
+ const mode = String(options.mode || 'full').toLowerCase();
62
+ const VALID_MODES = ['full', 'incremental', 'recapture', 'resume'];
63
+ if (!VALID_MODES.includes(mode)) {
64
+ console.error(chalk.red(`\n❌ --mode inválido: "${mode}". Valores aceptados: ${VALID_MODES.join(', ')}`));
65
+ process.exit(1);
66
+ }
67
+ // Sprint 6 implements incremental. Recapture and resume still pending.
68
+ if (mode === 'recapture') {
69
+ console.log(chalk.yellow(`⚠️ --mode recapture todavía es parcial — usa la misma lógica que incremental por ahora.\n` +
70
+ ` Sprint 6+ entregará el filtro estricto a pantallas marcadas needs_recapture.\n`));
71
+ }
72
+ if (mode === 'resume') {
73
+ if (!options.mobile) {
74
+ console.error(chalk.red(`\n❌ --mode resume solo está disponible para mobile (--mobile).\n`));
75
+ process.exit(1);
76
+ }
77
+ console.log(chalk.cyan(`🤝 Modo resume activado.\n` +
78
+ ` Asegúrate de tener la app abierta en el dispositivo y haber pasado\n` +
79
+ ` manualmente cualquier paso bloqueante (PIN/2FA/OTP/SSO/biometría).\n` +
80
+ ` Discovery NO va a reiniciar la app — captura desde el estado actual.\n`));
81
+ }
82
+ if (mode === 'incremental' && !options.entity) {
83
+ console.error(chalk.red(`\n❌ --mode incremental requiere --entity para consultar el baseline.\n`));
84
+ process.exit(1);
85
+ }
57
86
  console.log(chalk.blue(`\n🔍 FlowSpec QA Discovery — ${chalk.bold(url)}`));
58
- console.log(chalk.gray(` Framework: ${options.mobile ? 'Maestro (mobile)' : 'Playwright (web)'}\n`));
87
+ console.log(chalk.gray(` Framework: ${options.mobile ? 'Maestro (mobile)' : 'Playwright (web)'}`));
88
+ console.log(chalk.gray(` Modo: ${mode}\n`));
59
89
  try {
60
90
  const { discoveryEngine } = await import('@flowspec-qa/runner-core');
61
91
  // ── Interactive loop callback (mobile only, unless --no-interactive or non-TTY) ──
@@ -64,11 +94,149 @@ export function discoverCommand() {
64
94
  const interactiveEnabled = options.mobile &&
65
95
  options.interactive !== false &&
66
96
  process.stdout.isTTY === true;
97
+ // Track the corpus across the run + interactive loop so exploreElement
98
+ // can register EvidenceRecords into the same corpus.
99
+ let discoveryCorpus;
100
+ // ── Step 0: Ensure project_id is available ──────────────────
101
+ let projectId = options.project;
102
+ const { FlowSpecQAApi } = await import('@flowspec-qa/runner-core');
103
+ const projects = await FlowSpecQAApi.listProjects();
104
+ if (projectId) {
105
+ // If user provided a name (e.g. TRUSTBANK), resolve to UUID
106
+ const match = projects.find(p => p.name === projectId || p.id === projectId);
107
+ if (match)
108
+ projectId = match.id;
109
+ }
110
+ else {
111
+ if (projects.length === 0) {
112
+ console.error(chalk.red('\n❌ No tienes proyectos en FlowSpecQA.\n'));
113
+ process.exit(1);
114
+ }
115
+ if (projects.length === 1) {
116
+ projectId = projects[0].id;
117
+ console.log(chalk.dim(`\n📁 Auto-asociando al único proyecto: ${chalk.bold(projects[0].name)}`));
118
+ }
119
+ else {
120
+ if (interactiveEnabled) {
121
+ const { selectedProject } = await inquirer.prompt([{
122
+ type: 'list',
123
+ name: 'selectedProject',
124
+ message: 'Por favor, selecciona un proyecto:',
125
+ choices: projects.map(p => ({ name: p.name, value: p.id }))
126
+ }]);
127
+ projectId = selectedProject;
128
+ }
129
+ else {
130
+ console.error(chalk.red(`\n❌ Hay ${projects.length} proyectos: indica uno con --project <id|nombre>.\n`));
131
+ process.exit(1);
132
+ }
133
+ }
134
+ }
135
+ // ── Hybrid Discovery Decision Point ──────────────────────────
136
+ if (interactiveEnabled && mode === 'resume') {
137
+ console.log('\n' + chalk.cyan('─'.repeat(60)));
138
+ console.log(chalk.bold('🤖 Discovery Híbrido Activado'));
139
+ console.log(chalk.gray(' He detectado el dispositivo. ¿Cómo quieres explorar Consorcio?'));
140
+ console.log(chalk.cyan('─'.repeat(60)));
141
+ const { hybridChoice } = await inquirer.prompt([{
142
+ type: 'list',
143
+ name: 'hybridChoice',
144
+ message: 'Selecciona una estrategia:',
145
+ choices: [
146
+ { name: '🤖 Modo Automático (IA explora sola)', value: 'auto' },
147
+ { name: '🤝 Modo Asistido (Tú eliges los pasos, la IA los ejecuta)', value: 'assisted' },
148
+ { name: '🎬 Modo Manual (Tú grabas el flujo - Estilo JMeter)', value: 'manual' },
149
+ ],
150
+ }]);
151
+ if (hybridChoice === 'manual') {
152
+ console.log(chalk.yellow('\n🎬 Iniciando Modo Recorder guiado...'));
153
+ if (!options.entity) {
154
+ console.error(chalk.red('\n❌ El modo Recorder necesita --entity <id>.\n'));
155
+ process.exit(1);
156
+ }
157
+ const { runRecordSession } = await import('./record.js');
158
+ await runRecordSession({
159
+ entity: options.entity,
160
+ projectId: projectId,
161
+ deviceId: deviceId,
162
+ appId: url
163
+ });
164
+ return;
165
+ }
166
+ if (hybridChoice === 'assisted') {
167
+ console.log(chalk.cyan('\n🤝 Iniciando Discovery Asistido (Paso a Paso)...'));
168
+ // Set a flag to tell the loop to be more guided/step-by-step
169
+ options.assisted = true;
170
+ }
171
+ }
172
+ // ── onFormDetected — prompt tester for field values ─────────────────
173
+ const onFormDetected = interactiveEnabled
174
+ ? async (form) => {
175
+ console.log('\n' + chalk.cyan('─'.repeat(60)));
176
+ console.log(chalk.bold('📋 Discovery encontró un formulario\n'));
177
+ console.log(` ${chalk.bold('Pantalla:')} ${form.screenName}`);
178
+ console.log(` ${chalk.bold('Campos detectados:')}`);
179
+ form.fields.forEach((f) => {
180
+ console.log(` ${chalk.cyan('•')} ${chalk.bold(f.id)}${f.label ? ` — ${f.label}` : ''}`);
181
+ });
182
+ console.log(chalk.cyan('─'.repeat(60)));
183
+ const { explore } = await inquirer.prompt([{
184
+ type: 'confirm',
185
+ name: 'explore',
186
+ message: '¿Deseas explorar este flujo?',
187
+ default: true,
188
+ }]);
189
+ if (!explore)
190
+ return null;
191
+ console.log(chalk.bold('\n Ingresa los datos de prueba:'));
192
+ const answers = await inquirer.prompt(form.fields.map((f) => ({
193
+ type: 'input',
194
+ name: f.id,
195
+ message: ` › ${f.label || f.id}:`,
196
+ default: '',
197
+ })));
198
+ const testerLabel = (await inquirer.prompt([{
199
+ type: 'input',
200
+ name: 'label',
201
+ message: ' ¿Cómo quieres llamar a este flujo?',
202
+ default: `${form.screenName} — flujo principal`,
203
+ }])).label;
204
+ console.log(chalk.green(`\n ✅ Datos capturados para "${testerLabel}"`));
205
+ return answers;
206
+ }
207
+ : undefined;
208
+ // ── onRetryFailed — app no cargó tras reintentos automáticos ────────
209
+ const onRetryFailed = interactiveEnabled
210
+ ? async (message) => {
211
+ console.log('\n' + chalk.red('─'.repeat(60)));
212
+ console.log(chalk.bold.red('🚨 La app no pudo ser confirmada en primer plano\n'));
213
+ console.log(chalk.yellow(` ${message}`));
214
+ console.log(chalk.red('─'.repeat(60)));
215
+ const { proceed } = await inquirer.prompt([{
216
+ type: 'confirm',
217
+ name: 'proceed',
218
+ message: '¿Continuar de todas formas? (la evidencia capturada puede ser incorrecta)',
219
+ default: false,
220
+ }]);
221
+ if (!proceed) {
222
+ console.log(chalk.red('\n❌ Discovery abortado por el usuario.'));
223
+ process.exit(1);
224
+ }
225
+ return true;
226
+ }
227
+ : undefined;
67
228
  const onInteractiveLoop = interactiveEnabled
68
229
  ? async (evidence) => {
69
230
  const unexplored = discoveryEngine.detectUnexplored(evidence);
70
- if (unexplored.length === 0) {
71
- console.log(chalk.green('\n🎯 Todo lo encontrado ha sido explorado — generando suite final...'));
231
+ const currentScreen = evidence.screens[evidence.screens.length - 1]?.name;
232
+ // In assisted mode, we prioritize elements from the current screen
233
+ const displayList = options.assisted
234
+ ? unexplored.filter((u) => u.sourceScreen === currentScreen)
235
+ : unexplored;
236
+ // If current screen is fully explored in assisted mode, show ALL unexplored or finish
237
+ const effectiveList = (options.assisted && displayList.length === 0) ? unexplored : displayList;
238
+ if (effectiveList.length === 0) {
239
+ console.log(chalk.green('\n✅ Discovery completado — no quedan elementos sin explorar.'));
72
240
  return false;
73
241
  }
74
242
  // ── Summary banner ──────────────────────────────────────
@@ -82,42 +250,51 @@ export function discoverCommand() {
82
250
  ` ${chalk.red(errorStates + ' error states')}` +
83
251
  ` ${chalk.blue('Confianza: ~' + confScore + '%')}`);
84
252
  console.log(chalk.cyan('─'.repeat(60)));
85
- console.log(chalk.bold.yellow('\n🔍 Encontré estos elementos sin explorar:\n'));
86
- unexplored.forEach((u, i) => {
253
+ if (options.assisted) {
254
+ console.log(chalk.bold.cyan(`\n📍 Pantalla actual: ${chalk.white(currentScreen)}`));
255
+ console.log(chalk.dim(` Elige qué acción quieres que la IA ejecute ahora:\n`));
256
+ }
257
+ else {
258
+ console.log(chalk.bold.yellow('\n🔍 Elementos sin explorar:\n'));
259
+ }
260
+ effectiveList.forEach((u, i) => {
87
261
  const text = u.elementText ? chalk.white(`"${u.elementText.substring(0, 25)}"`) : '';
88
262
  console.log(` ${chalk.dim(String(i + 1).padStart(2, ' '))}. ` +
89
263
  `${chalk.cyan(u.elementId.padEnd(26))} ${text.padEnd(30)} ` +
90
- chalk.gray(`en: ${u.sourceScreen}`));
264
+ (options.assisted ? '' : chalk.gray(`en: ${u.sourceScreen}`)));
91
265
  });
92
266
  // ── Inquirer checkbox ───────────────────────────────────
93
267
  const { selected } = await inquirer.prompt([{
94
- type: 'checkbox',
268
+ type: options.assisted ? 'list' : 'checkbox', // List for step-by-step, checkbox for batch
95
269
  name: 'selected',
96
- message: '¿Qué quieres explorar? (Espacio = seleccionar, Enter = confirmar)',
97
- pageSize: Math.min(15, unexplored.length + 3),
270
+ message: options.assisted ? 'Selecciona el siguiente paso:' : '¿Qué quieres explorar?',
271
+ pageSize: Math.min(15, effectiveList.length + 3),
272
+ instructions: false,
98
273
  choices: [
99
- ...unexplored.map((u) => {
274
+ ...effectiveList.map((u) => {
100
275
  const label = chalk.cyan(u.elementId.padEnd(26)) +
101
276
  (u.elementText ? chalk.white(`"${u.elementText.substring(0, 22)}"`) : chalk.dim('(sin texto)')) +
102
- chalk.gray(` ← ${u.sourceScreen}`);
277
+ (options.assisted ? '' : chalk.gray(` ← ${u.sourceScreen}`));
103
278
  return { name: label, value: u };
104
279
  }),
105
280
  new inquirer.Separator(' ────────────────────────────────────────'),
106
281
  {
107
- name: chalk.green('✅ Listo — generar suite con lo explorado hasta ahora'),
282
+ name: chalk.green('✅ Finalizar — generar suite con lo explorado'),
108
283
  value: '__DONE__',
109
284
  },
110
285
  ],
111
286
  }]);
112
287
  // User chose "Done" or nothing
113
- if (!selected || selected.length === 0 || selected.includes('__DONE__')) {
288
+ if (!selected || (Array.isArray(selected) && selected.length === 0) || selected === '__DONE__' || (Array.isArray(selected) && selected.includes('__DONE__'))) {
114
289
  console.log(chalk.green('\n✅ Generando suite con evidencias actuales...'));
115
290
  return false;
116
291
  }
117
- // Filter out the sentinel (in case it was selected with others)
118
- const toExplore = selected.filter((s) => s !== '__DONE__');
292
+ // Normalize to array
293
+ const toExplore = Array.isArray(selected) ? selected : [selected];
119
294
  // ── Explore each selected element ───────────────────────
120
- console.log(chalk.blue(`\n🔭 Explorando ${toExplore.length} elemento(s)...\n`));
295
+ if (!options.assisted) {
296
+ console.log(chalk.blue(`\n🔭 Explorando ${toExplore.length} elemento(s)...\n`));
297
+ }
121
298
  for (const element of toExplore) {
122
299
  const label = element.elementText
123
300
  ? `${element.elementId} ("${element.elementText.substring(0, 20)}")`
@@ -126,11 +303,15 @@ export function discoverCommand() {
126
303
  const newScreens = await discoveryEngine.exploreElement(element, {
127
304
  url,
128
305
  framework: 'maestro',
306
+ projectId,
307
+ entityId: options.entity,
129
308
  username: options.username || process.env.FLOWSPECQA_APP_USERNAME,
130
309
  password: options.password || process.env.FLOWSPECQA_APP_PASSWORD,
131
310
  deviceId,
132
311
  onProgress,
133
- }, evidence);
312
+ onFormDetected,
313
+ onRetryFailed,
314
+ }, evidence, discoveryCorpus);
134
315
  if (newScreens.length > 0) {
135
316
  console.log(chalk.green(` ✅ +${newScreens.length} pantalla(s) nueva(s): ` +
136
317
  newScreens.map((s) => chalk.bold(s.name)).join(', ')));
@@ -139,30 +320,116 @@ export function discoverCommand() {
139
320
  return true; // continue loop — show updated unexplored list
140
321
  }
141
322
  : undefined;
142
- await discoveryEngine.run({
323
+ const runResult = await discoveryEngine.run({
143
324
  url,
144
325
  framework: options.mobile ? 'maestro' : 'playwright',
145
- projectId: options.project,
326
+ projectId: projectId,
146
327
  entityId: options.entity,
147
328
  username: options.username || process.env.FLOWSPECQA_APP_USERNAME,
148
329
  password: options.password || process.env.FLOWSPECQA_APP_PASSWORD,
149
330
  deviceId,
331
+ // Phase 11 — pass the validated mode to the engine.
332
+ // The engine consults the entity's baseline when mode='incremental'
333
+ // and skips screens whose fingerprint matches a verified baseline.
334
+ mode: mode,
150
335
  onProgress,
151
336
  onInteractiveLoop,
337
+ onFormDetected,
338
+ onRetryFailed,
152
339
  });
153
- console.log(chalk.green('\n✅ Discovery completado con evidencias.\n'));
154
- console.log(`${chalk.cyan('╔══════════════════════════════════════════════════════════════════════╗')}`);
155
- console.log(`${chalk.cyan('║')} ${chalk.bold('PRÓXIMOS PASOS')} ${chalk.cyan('║')}`);
156
- console.log(`${chalk.cyan('╠══════════════════════════════════════════════════════════════════════╣')}`);
157
- console.log(`${chalk.cyan('║')} ${chalk.bold('📋 Reporte de evidencias:')} ${chalk.cyan('║')}`);
158
- console.log(`${chalk.cyan('║')} ${chalk.green('specs/discovery_report.html')} ← Abre en tu browser ${chalk.cyan('║')}`);
159
- console.log(`${chalk.cyan('║')} ${chalk.cyan('║')}`);
160
- console.log(`${chalk.cyan('║')} ${chalk.bold('Ruta A — Portal SaaS:')} ${chalk.cyan('║')}`);
161
- console.log(`${chalk.cyan('║')} El plan ya está sincronizado. Ve a FlowSpecQA y genera tests. ${chalk.cyan('║')}`);
162
- console.log(`${chalk.cyan('║')} ${chalk.cyan('║')}`);
163
- console.log(`${chalk.cyan('║')} ${chalk.bold('Ruta B — CLI local:')} ${chalk.cyan('║')}`);
164
- console.log(`${chalk.cyan('║')} ${chalk.green('flowspecqa generate --from ./specs/discovery_plan.md')} ${chalk.cyan('║')}`);
165
- console.log(`${chalk.cyan('╚══════════════════════════════════════════════════════════════════════╝')}\n`);
340
+ // Store corpus reference so the interactive loop can extend it
341
+ discoveryCorpus = runResult.corpus;
342
+ // Compute absolute output path for display
343
+ const outputDir = path.resolve(options.output || 'specs');
344
+ console.log(chalk.green('\n✅ Discovery completado — generando artefactos desde evidencia disponible.\n'));
345
+ // ── Clasificación de evidencia (Spec § 5.3) ────────────────────
346
+ if (discoveryCorpus) {
347
+ const cls = classifyCorpus(discoveryCorpus);
348
+ const W = (n, color) => chalk[color](String(n).padStart(3, ' '));
349
+ console.log(chalk.bold(' Evidencia clasificada:'));
350
+ console.log(` ${W(cls.strict_count, 'green')} ${chalk.green('STRICT')} casos respaldados por evidencia suficiente`);
351
+ console.log(` ${W(cls.partial_count, 'yellow')} ${chalk.yellow('PARTIAL')} flujos incompletos que requieren revisión`);
352
+ console.log(` ${W(cls.reco_count, 'cyan')} ${chalk.cyan('RECO')} recomendaciones derivadas del corpus descubierto`);
353
+ console.log(` ${W(cls.gaps_count, 'red')} ${chalk.red('GAPS')} cobertura pendiente por explorar`);
354
+ // Show 1-2 PARTIAL items with recommendation
355
+ if (cls.details.partial.length > 0) {
356
+ console.log(chalk.dim('\n PARTIAL destacados:'));
357
+ cls.details.partial.slice(0, 2).forEach(p => {
358
+ const desc = p.description.length > 100 ? p.description.slice(0, 97) + '...' : p.description;
359
+ console.log(chalk.dim(` ⚠ ${p.evidenceId}: ${desc}`));
360
+ });
361
+ }
362
+ // Show top GAPS by priority (alta first)
363
+ if (cls.details.gaps.length > 0) {
364
+ const sortedGaps = [...cls.details.gaps].sort((a, b) => {
365
+ const order = { alta: 0, media: 1, baja: 2 };
366
+ return order[a.priority] - order[b.priority];
367
+ });
368
+ console.log(chalk.dim('\n GAPS destacados:'));
369
+ sortedGaps.slice(0, 3).forEach(g => {
370
+ const prio = g.priority === 'alta' ? chalk.red('●') : g.priority === 'media' ? chalk.yellow('●') : chalk.gray('●');
371
+ const action = g.action.length > 78 ? g.action.slice(0, 75) + '...' : g.action;
372
+ console.log(chalk.dim(` ${prio} ${action}`));
373
+ });
374
+ }
375
+ // Show top RECO by priority
376
+ if (cls.details.reco.length > 0) {
377
+ const sortedRecos = [...cls.details.reco].sort((a, b) => {
378
+ const order = { alta: 0, media: 1, baja: 2 };
379
+ return order[a.priority] - order[b.priority];
380
+ });
381
+ console.log(chalk.dim('\n RECO destacados:'));
382
+ sortedRecos.slice(0, 3).forEach(r => {
383
+ const prio = r.priority === 'alta' ? chalk.red('●') : r.priority === 'media' ? chalk.yellow('●') : chalk.gray('●');
384
+ const title = r.title.length > 78 ? r.title.slice(0, 75) + '...' : r.title;
385
+ console.log(chalk.dim(` ${prio} [${r.category}] ${title}`));
386
+ });
387
+ }
388
+ console.log('');
389
+ }
390
+ const reportFile = runResult.reportPath
391
+ ? path.resolve(runResult.reportPath)
392
+ : path.join(outputDir, 'discovery_report.html');
393
+ const stripAnsi = (str) => {
394
+ // eslint-disable-next-line no-control-regex
395
+ return str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{1,4})*)?[0-9A-ORZcf-nqry=><]/g, '');
396
+ };
397
+ // Renders a single box line, padding to fill the border width
398
+ const formatBoxLine = (content, totalWidth = 84) => {
399
+ const contentWidth = totalWidth - 6; // ║ (1) + 2 spaces + 2 spaces + ║ (1)
400
+ const visible = stripAnsi(content);
401
+ const padding = Math.max(0, contentWidth - visible.length);
402
+ return `${chalk.cyan('║')} ${content}${' '.repeat(padding)} ${chalk.cyan('║')}`;
403
+ };
404
+ // Renders a plain string that may be longer than contentWidth, wrapping across multiple lines
405
+ const formatBoxPath = (filePath, totalWidth = 84) => {
406
+ const contentWidth = totalWidth - 6;
407
+ const lines = [];
408
+ let remaining = filePath;
409
+ while (remaining.length > 0) {
410
+ lines.push(remaining.slice(0, contentWidth));
411
+ remaining = remaining.slice(contentWidth);
412
+ }
413
+ return lines.map(l => {
414
+ const padding = Math.max(0, contentWidth - l.length);
415
+ return `${chalk.cyan('║')} ${chalk.green(l)}${' '.repeat(padding)} ${chalk.cyan('║')}`;
416
+ }).join('\n');
417
+ };
418
+ console.log(`${chalk.cyan('╔══════════════════════════════════════════════════════════════════════════════════╗')}`);
419
+ console.log(formatBoxLine(chalk.bold('PRÓXIMOS PASOS')));
420
+ console.log(`${chalk.cyan('╠══════════════════════════════════════════════════════════════════════════════════╣')}`);
421
+ console.log(formatBoxLine(chalk.bold('📋 Reporte de evidencias (HTML):')));
422
+ console.log(formatBoxPath(reportFile));
423
+ console.log(formatBoxLine(''));
424
+ console.log(formatBoxLine(chalk.bold('Portal SaaS:')));
425
+ if (runResult.synced) {
426
+ console.log(formatBoxLine('El plan ya está sincronizado. Ve a FlowSpecQA y genera tests.'));
427
+ }
428
+ else {
429
+ console.log(formatBoxLine(chalk.red(`⚠️ El plan NO se sincronizó (${(runResult.syncError || 'error').slice(0, 50)}).`)));
430
+ console.log(formatBoxLine('Corrige la causa y repite flowspecqa discover.'));
431
+ }
432
+ console.log(`${chalk.cyan('╚══════════════════════════════════════════════════════════════════════════════════╝')}\n`);
166
433
  }
167
434
  catch (err) {
168
435
  console.error(chalk.red(`\n❌ Discovery fallido: ${err.message}`));