@flowspec-qa/runner-core 0.2.4 β†’ 0.3.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.
package/dist/discovery.js CHANGED
@@ -32,47 +32,50 @@ function resolveAdb() {
32
32
  * Uses Playwright and Maestro to extract real UI intelligence.
33
33
  */
34
34
  export const discoveryEngine = {
35
- async run(options) {
36
- console.log(chalk.blue(`\nπŸ” Starting autonomous high-fidelity discovery for: ${options.url}`));
37
- let result;
38
- if (options.framework === 'maestro') {
39
- result = await this.discoverMobile(options);
40
- }
41
- else {
42
- result = await this.discoverWeb(options);
35
+ // ── Progress helper ─────────────────────────────────────────────────────
36
+ _progress(opts, step, detail) {
37
+ if (opts.onProgress) {
38
+ opts.onProgress(step, detail);
43
39
  }
44
- // Persist locally
45
- const outputDir = options.outputDir || path.join(process.cwd(), 'specs');
46
- if (!fs.existsSync(outputDir))
47
- fs.mkdirSync(outputDir, { recursive: true });
48
- const planPath = path.join(outputDir, 'discovery_plan.md');
49
- fs.writeFileSync(planPath, result.planContent);
50
- console.log(chalk.green(`\nβœ… Local discovery plan saved: ${chalk.bold(planPath)}`));
51
- // Sync with SaaS
40
+ },
41
+ // ── ADB screenshot capture ───────────────────────────────────────────────
42
+ /**
43
+ * Captures a screenshot from the connected Android device via ADB and
44
+ * returns it as a base64-encoded PNG string.
45
+ * Returns null silently if ADB capture fails (non-fatal).
46
+ */
47
+ async _captureScreenshotMobile(adbS, tag) {
52
48
  try {
53
- console.log(chalk.yellow('πŸ“‘ Syncing rich intelligence with FlowSpecQA SaaS...'));
54
- await FlowSpecQAApi.syncDiscoveryPlan({
55
- url: options.url,
56
- plan_content: result.planContent,
57
- raw_scan_data: result.rawScanData,
58
- framework: options.framework,
59
- project_id: options.projectId,
60
- entity_id: options.entityId,
61
- });
62
- console.log(chalk.green('βœ… Sync successful! The AI generator is now "UI-Aware".'));
49
+ const remotePath = `/sdcard/fpqa_discovery_${tag}.png`;
50
+ const localPath = path.join(os.tmpdir(), `fpqa_discovery_${tag}_${Date.now()}.png`);
51
+ execSync(`${adbS} shell screencap -p "${remotePath}"`, { stdio: 'ignore', timeout: 6000 });
52
+ execSync(`${adbS} pull "${remotePath}" "${localPath}"`, { stdio: 'ignore', timeout: 8000 });
53
+ // Clean up remote file
54
+ try {
55
+ execSync(`${adbS} shell rm "${remotePath}"`, { stdio: 'ignore', timeout: 3000 });
56
+ }
57
+ catch { }
58
+ const buffer = fs.readFileSync(localPath);
59
+ try {
60
+ fs.unlinkSync(localPath);
61
+ }
62
+ catch { }
63
+ return buffer.toString('base64');
63
64
  }
64
- catch (error) {
65
- const errorMsg = error.response?.data?.detail || error.message || String(error);
66
- console.log(chalk.red(`⚠️ SaaS Sync skipped: ${errorMsg}`));
67
- console.log(chalk.gray(` Run: flowspecqa generate --from ${planPath}\n`));
65
+ catch {
66
+ return null;
68
67
  }
69
- return result;
70
68
  },
69
+ // ── Hierarchy helpers ────────────────────────────────────────────────────
71
70
  /** Capture maestro hierarchy from current screen and return parsed JSON */
72
- async _captureHierarchy(env) {
73
- const rawOutput = execSync('maestro hierarchy', {
71
+ async _captureHierarchy(env, deviceId) {
72
+ // --device is a GLOBAL flag in Maestro β€” must go before the subcommand.
73
+ // Without it, maestro hierarchy prompts interactively and hangs in non-TTY contexts.
74
+ // Redirect stderr to /dev/null to suppress verbose INFO/DEBUG logs.
75
+ const deviceFlag = deviceId ? `--device ${deviceId} ` : '';
76
+ const rawOutput = execSync(`maestro ${deviceFlag}hierarchy 2>/dev/null`, {
74
77
  encoding: 'utf8',
75
- stdio: ['ignore', 'pipe', 'pipe'],
78
+ maxBuffer: 20 * 1024 * 1024, // 20 MB β€” hierarchy JSON can be large
76
79
  env: env ?? process.env,
77
80
  });
78
81
  const lines = rawOutput.split('\n');
@@ -90,6 +93,7 @@ export const discoveryEngine = {
90
93
  encoding: 'utf8',
91
94
  timeout: 120000,
92
95
  stdio: ['ignore', 'pipe', 'pipe'],
96
+ maxBuffer: 20 * 1024 * 1024, // 20 MB β€” Maestro outputs verbose logs
93
97
  env: env ?? process.env,
94
98
  });
95
99
  fs.unlinkSync(tmpFile);
@@ -103,22 +107,131 @@ export const discoveryEngine = {
103
107
  return false;
104
108
  }
105
109
  },
110
+ // ── Text extraction from accessibility hierarchy ─────────────────────────
111
+ /**
112
+ * Extracts ALL visible text strings from a Maestro hierarchy JSON.
113
+ * Used for confidence scoring β€” any text returned here is "verified" (actually on screen).
114
+ */
115
+ extractAllTexts(node) {
116
+ const texts = new Set();
117
+ const traverse = (current) => {
118
+ if (!current || typeof current !== 'object')
119
+ return;
120
+ const attrs = current.attributes || {};
121
+ const text = (attrs['text'] || '').trim();
122
+ // Skip: too short, pure numbers, system strings, clock times (HH:MM), battery/signal indicators
123
+ const isNoise = !text ||
124
+ text.length < 3 ||
125
+ text.match(/^[\d.,\s%]+$/) || // pure numbers / percentages
126
+ text.match(/^\d{1,2}:\d{2}(:\d{2})?$/) || // clock times like "13:38"
127
+ text.startsWith('android') ||
128
+ text.match(/^[β–²β–Όβ—€β–Άβ¬†β¬‡β¬…βž‘]+$/); // navigation arrows / icons only
129
+ if (!isNoise) {
130
+ texts.add(text);
131
+ }
132
+ for (const child of (current.children || [])) {
133
+ traverse(child);
134
+ }
135
+ };
136
+ traverse(node);
137
+ return [...texts];
138
+ },
139
+ // ── Main entry point ─────────────────────────────────────────────────────
140
+ async run(options) {
141
+ console.log(chalk.blue(`\nπŸ” Iniciando Discovery autΓ³nomo para: ${options.url}`));
142
+ let result;
143
+ if (options.framework === 'maestro') {
144
+ result = await this.discoverMobile(options);
145
+ }
146
+ else {
147
+ result = await this.discoverWeb(options);
148
+ }
149
+ // ── Interactive exploration loop (mobile only) ────────────────────────
150
+ if (options.onInteractiveLoop && result.evidence) {
151
+ let continueLoop = true;
152
+ while (continueLoop) {
153
+ continueLoop = await options.onInteractiveLoop(result.evidence);
154
+ if (continueLoop && result.evidence) {
155
+ // After each exploration round, rebuild the plan from updated evidence
156
+ result.planContent = this.buildPlanFromEvidence(result.evidence, options.url);
157
+ result.metrics = result.evidence.metrics;
158
+ }
159
+ }
160
+ // Ensure final plan reflects all explorations
161
+ if (result.evidence) {
162
+ result.planContent = this.buildPlanFromEvidence(result.evidence, options.url);
163
+ }
164
+ }
165
+ // Persist plan locally
166
+ const outputDir = options.outputDir || path.join(process.cwd(), 'specs');
167
+ if (!fs.existsSync(outputDir))
168
+ fs.mkdirSync(outputDir, { recursive: true });
169
+ const planPath = path.join(outputDir, 'discovery_plan.md');
170
+ fs.writeFileSync(planPath, result.planContent);
171
+ console.log(chalk.green(`\nβœ… Plan de Discovery guardado: ${chalk.bold(planPath)}`));
172
+ // Generate HTML evidence report
173
+ try {
174
+ const { generateDiscoveryReport } = await import('./discovery-report.js');
175
+ const reportPath = generateDiscoveryReport(result, {
176
+ outputDir,
177
+ framework: options.framework,
178
+ url: options.url,
179
+ });
180
+ console.log(chalk.green(`πŸ“‹ Reporte de evidencias: ${chalk.bold(reportPath)}`));
181
+ }
182
+ catch (reportErr) {
183
+ console.log(chalk.yellow(`⚠️ Reporte no generado: ${reportErr.message}`));
184
+ }
185
+ // Sync with SaaS
186
+ try {
187
+ this._progress(options, 'sync', 'Sincronizando con FlowSpecQA SaaS...');
188
+ console.log(chalk.yellow('πŸ“‘ Sincronizando con FlowSpecQA SaaS...'));
189
+ await FlowSpecQAApi.syncDiscoveryPlan({
190
+ url: options.url,
191
+ plan_content: result.planContent,
192
+ raw_scan_data: result.rawScanData,
193
+ framework: options.framework,
194
+ project_id: options.projectId,
195
+ entity_id: options.entityId,
196
+ });
197
+ console.log(chalk.green('βœ… Sincronizado. El generador de IA ahora tiene contexto UI real.'));
198
+ }
199
+ catch (error) {
200
+ const errorMsg = error.response?.data?.detail || error.message || String(error);
201
+ console.log(chalk.red(`⚠️ Sync omitido: ${errorMsg}`));
202
+ console.log(chalk.gray(` Ejecuta: flowspecqa generate --from ${planPath}\n`));
203
+ }
204
+ return result;
205
+ },
206
+ // ── Mobile Discovery ─────────────────────────────────────────────────────
106
207
  async discoverMobile(options) {
107
208
  const appId = options.url;
108
209
  const username = options.username || '';
109
210
  const password = options.password || '';
110
211
  const adb = resolveAdb();
111
- // -s flag for device targeting when serial is provided
112
212
  const adbS = options.deviceId ? `"${adb}" -s ${options.deviceId}` : `"${adb}"`;
113
- // Maestro device env var
114
213
  const maestroEnv = options.deviceId
115
214
  ? { ...process.env, MAESTRO_DEVICE_ID: options.deviceId }
116
215
  : process.env;
117
- console.log(chalk.gray(`πŸ“± Starting multi-screen autonomous discovery${options.deviceId ? ` on device ${options.deviceId}` : ''}...`));
216
+ const startedAt = Date.now();
118
217
  const allScreens = [];
218
+ const navigationSteps = [];
219
+ this._progress(options, 'start', `Iniciando Discovery mobile: ${appId}`);
220
+ console.log(chalk.gray(`πŸ“± Discovery multi-pantalla${options.deviceId ? ` β€” dispositivo ${options.deviceId}` : ''}...`));
119
221
  try {
120
- // ── Reset app state ───────────────────────────────────────────────
121
- console.log(chalk.gray(' πŸ”„ Resetting app state...'));
222
+ // ── Wake up screen + reset app state ──────────────────────────────
223
+ this._progress(options, 'reset', 'Reseteando estado de la app...');
224
+ console.log(chalk.gray(' πŸ”„ Reseteando estado de la app...'));
225
+ // Wake the screen β€” Maestro hierarchy fails silently when screen is off/locked
226
+ try {
227
+ execSync(`${adbS} shell input keyevent KEYCODE_WAKEUP`, { stdio: 'ignore' });
228
+ }
229
+ catch { }
230
+ try {
231
+ execSync(`${adbS} shell wm dismiss-keyguard`, { stdio: 'ignore' });
232
+ }
233
+ catch { }
234
+ await sleep(800);
122
235
  try {
123
236
  execSync(`${adbS} shell am force-stop ${appId}`, { stdio: 'ignore' });
124
237
  }
@@ -128,60 +241,80 @@ export const discoveryEngine = {
128
241
  }
129
242
  catch { }
130
243
  await sleep(1000);
131
- // ── Screen 1: Launch & capture Login ─────────────────────────────
132
- console.log(chalk.gray(' πŸ“Έ Screen 1/3 β€” Login...'));
244
+ // ── Screen 1: Login ────────────────────────────────────────────────
245
+ this._progress(options, 'screen', 'Pantalla 1 β€” Login');
246
+ console.log(chalk.gray(' πŸ“Έ Pantalla 1 β€” Login...'));
133
247
  execSync(`${adbS} shell monkey -p ${appId} -c android.intent.category.LAUNCHER 1`, { stdio: 'ignore' });
134
- await sleep(2500);
135
- const loginHierarchy = await this._captureHierarchy(maestroEnv);
248
+ // After pm clear + cold launch, app needs more time to render (permissions reset, first run)
249
+ await sleep(4500);
250
+ const loginScreenshot = await this._captureScreenshotMobile(adbS, 'login');
251
+ const loginHierarchy = await this._captureHierarchy(maestroEnv, options.deviceId);
136
252
  const loginElements = this.extractMaestroSelectors(loginHierarchy);
137
- allScreens.push({ name: 'Login', elements: loginElements, hierarchy: loginHierarchy });
138
- console.log(chalk.green(` βœ… Login: ${loginElements.length} elements`));
139
- // ── Error state: Login β€” submit empty to reveal tv_error ─────────
140
- console.log(chalk.gray(' πŸ“Έ Screen 1 error state β€” empty submit...'));
253
+ const loginTexts = this.extractAllTexts(loginHierarchy);
254
+ allScreens.push({
255
+ name: 'Login',
256
+ isErrorState: false,
257
+ screenshot: loginScreenshot,
258
+ elements: loginElements,
259
+ allTexts: loginTexts,
260
+ });
261
+ navigationSteps.push({ from: 'Inicio', to: 'Login', action: 'Lanzar app' });
262
+ console.log(chalk.green(` βœ… Login: ${loginElements.length} elementos, ${loginScreenshot ? 'screenshot βœ“' : 'sin screenshot'}`));
263
+ // ── Error state: Login vacΓ­o ───────────────────────────────────────
264
+ this._progress(options, 'error_state', 'Login vacΓ­o β€” capturando mensajes de error reales...');
265
+ console.log(chalk.gray(' πŸ“Έ Error state: Login vacΓ­o β€” Submit sin datos...'));
141
266
  const emptyLoginOk = this._runMaestroFlow(appId, [
142
267
  `- tapOn:\n id: "btn_login"`,
143
268
  `- waitForAnimationToEnd:\n timeout: 1500`,
144
269
  ], maestroEnv);
145
270
  if (emptyLoginOk) {
146
- const loginErrorHierarchy = await this._captureHierarchy(maestroEnv);
147
- const loginErrorAll = this.extractMaestroSelectors(loginErrorHierarchy);
271
+ await sleep(1500); // wait for error UI to settle before screencap
272
+ const loginErrorScreenshot = await this._captureScreenshotMobile(adbS, 'login_error');
273
+ const loginErrorHierarchy = await this._captureHierarchy(maestroEnv, options.deviceId);
274
+ const loginErrorAllElems = this.extractMaestroSelectors(loginErrorHierarchy);
275
+ const loginErrorTexts = this.extractAllTexts(loginErrorHierarchy);
148
276
  const knownLoginIds = new Set(loginElements.map(e => e.id));
149
- const loginErrorNew = loginErrorAll.filter(e => !knownLoginIds.has(e.id));
150
- if (loginErrorNew.length > 0) {
151
- allScreens.push({ name: 'Login (Error State)', elements: loginErrorNew, hierarchy: loginErrorHierarchy });
152
- console.log(chalk.green(` βœ… Login error state: ${loginErrorNew.length} new elements (e.g. ${loginErrorNew.map(e => e.id).join(', ')})`));
153
- }
277
+ const loginErrorNew = loginErrorAllElems.filter(e => !knownLoginIds.has(e.id));
278
+ // New error texts = texts that weren't on the clean login screen
279
+ const loginNewTexts = loginErrorTexts.filter(t => !loginTexts.includes(t));
280
+ allScreens.push({
281
+ name: 'Login (Error β€” campos vacΓ­os)',
282
+ isErrorState: true,
283
+ screenshot: loginErrorScreenshot,
284
+ elements: loginErrorNew,
285
+ allTexts: loginNewTexts,
286
+ });
287
+ navigationSteps.push({ from: 'Login', to: 'Login (Error β€” campos vacΓ­os)', action: 'Submit vacΓ­o' });
288
+ const errList = loginNewTexts.slice(0, 3).map(t => `"${t}"`).join(', ');
289
+ console.log(chalk.green(` βœ… Login error state: ${loginErrorNew.length} elementos nuevos${errList ? ` | Textos: ${errList}` : ''}`));
154
290
  }
155
- // ── Navigate to Screen 2: Accounts (via login) ───────────────────
291
+ else {
292
+ console.log(chalk.yellow(' ⚠️ No se pudo provocar error de login vacío'));
293
+ }
294
+ // ── Navigate to Screen 2: Accounts ────────────────────────────────
156
295
  if (username && password) {
157
- console.log(chalk.gray(' πŸ” Logging in to discover authenticated screens...'));
158
- // Run login steps β€” no success assertion here (extendedWaitUntil is flaky).
159
- // We verify login success afterward by inspecting the hierarchy.
296
+ this._progress(options, 'login', 'Autenticando para descubrir pantallas protegidas...');
297
+ console.log(chalk.gray(' πŸ” Autenticando para explorar pantallas privadas...'));
160
298
  this._runMaestroFlow(appId, [
161
- // clearState must be a property of launchApp, not a standalone command
162
299
  `- launchApp:\n clearState: true`,
163
300
  `- waitForAnimationToEnd`,
164
301
  `- tapOn:\n id: "et_username"`,
165
302
  `- eraseText: 50`,
166
303
  `- inputText: "${username}"`,
167
304
  `- waitForAnimationToEnd`,
168
- // Dismiss keyboard so et_password is not covered on smaller screens
169
305
  `- hideKeyboard`,
170
306
  `- tapOn:\n id: "et_password"`,
171
307
  `- eraseText: 30`,
172
308
  `- inputText: "${password}"`,
173
309
  `- waitForAnimationToEnd`,
174
- // Dismiss keyboard so btn_login is not covered
175
310
  `- hideKeyboard`,
176
311
  `- tapOn:\n id: "btn_login"`,
177
312
  `- waitForAnimationToEnd`,
178
313
  ], maestroEnv);
179
- // Give the app extra time to complete the login network request & navigate
180
314
  await sleep(3000);
181
- // Verify login success by checking what screen we're on
182
315
  let postLoginHierarchy;
183
316
  try {
184
- postLoginHierarchy = await this._captureHierarchy(maestroEnv);
317
+ postLoginHierarchy = await this._captureHierarchy(maestroEnv, options.deviceId);
185
318
  }
186
319
  catch {
187
320
  postLoginHierarchy = null;
@@ -189,113 +322,161 @@ export const discoveryEngine = {
189
322
  const postLoginElements = postLoginHierarchy ? this.extractMaestroSelectors(postLoginHierarchy) : [];
190
323
  const loginSuccess = postLoginElements.some(e => e.id === 'tv_welcome' || e.id === 'tv_total_balance');
191
324
  if (loginSuccess) {
192
- console.log(chalk.gray(' πŸ“Έ Screen 2/3 β€” Accounts...'));
325
+ // ── Screen 2: Accounts ───────────────────────────────────────
326
+ this._progress(options, 'screen', 'Pantalla 2 β€” Cuentas (autenticado)');
327
+ console.log(chalk.gray(' πŸ“Έ Pantalla 2 β€” Cuentas...'));
193
328
  await sleep(1500);
194
- const accountsHierarchy = await this._captureHierarchy(maestroEnv);
329
+ const accountsScreenshot = await this._captureScreenshotMobile(adbS, 'accounts');
330
+ const accountsHierarchy = await this._captureHierarchy(maestroEnv, options.deviceId);
195
331
  const accountsElements = this.extractMaestroSelectors(accountsHierarchy);
196
- allScreens.push({ name: 'Accounts', elements: accountsElements, hierarchy: accountsHierarchy });
197
- console.log(chalk.green(` βœ… Accounts: ${accountsElements.length} elements`));
198
- // ── Navigate to Screen 3: Transfer ─────────────────────────
199
- console.log(chalk.gray(' πŸ“Έ Screen 3/3 β€” Transfer...'));
332
+ const accountsTexts = this.extractAllTexts(accountsHierarchy);
333
+ allScreens.push({
334
+ name: 'Cuentas (autenticado)',
335
+ isErrorState: false,
336
+ screenshot: accountsScreenshot,
337
+ elements: accountsElements,
338
+ allTexts: accountsTexts,
339
+ });
340
+ navigationSteps.push({ from: 'Login', to: 'Cuentas', action: 'Login con credenciales vΓ‘lidas' });
341
+ console.log(chalk.green(` βœ… Cuentas: ${accountsElements.length} elementos, ${accountsScreenshot ? 'screenshot βœ“' : 'sin screenshot'}`));
342
+ // ── Screen 3: Transfer ───────────────────────────────────────
343
+ this._progress(options, 'screen', 'Pantalla 3 β€” Transferencia');
344
+ console.log(chalk.gray(' πŸ“Έ Pantalla 3 β€” Transferencia...'));
200
345
  const navSuccess = this._runMaestroFlow(appId, [
201
346
  `- tapOn:\n id: "btn_transfer"`,
202
347
  `- waitForAnimationToEnd`,
203
- // No text assertion β€” Transfer screen title is unknown until discovery runs
204
348
  ], maestroEnv);
205
349
  if (navSuccess) {
206
350
  await sleep(1200);
207
- const transferHierarchy = await this._captureHierarchy(maestroEnv);
351
+ const transferScreenshot = await this._captureScreenshotMobile(adbS, 'transfer');
352
+ const transferHierarchy = await this._captureHierarchy(maestroEnv, options.deviceId);
208
353
  const transferElements = this.extractMaestroSelectors(transferHierarchy);
209
- allScreens.push({ name: 'Transfer', elements: transferElements, hierarchy: transferHierarchy });
210
- console.log(chalk.green(` βœ… Transfer: ${transferElements.length} elements`));
211
- // ── Error state: Transfer β€” submit empty amount ─────────
212
- console.log(chalk.gray(' πŸ“Έ Transfer error state β€” empty amount submit...'));
354
+ const transferTexts = this.extractAllTexts(transferHierarchy);
355
+ allScreens.push({
356
+ name: 'Transferencia',
357
+ isErrorState: false,
358
+ screenshot: transferScreenshot,
359
+ elements: transferElements,
360
+ allTexts: transferTexts,
361
+ });
362
+ navigationSteps.push({ from: 'Cuentas', to: 'Transferencia', action: 'Tap btn_transfer' });
363
+ console.log(chalk.green(` βœ… Transferencia: ${transferElements.length} elementos, ${transferScreenshot ? 'screenshot βœ“' : 'sin screenshot'}`));
364
+ // ── Error state: Transfer vacΓ­o ────────────────────────────
365
+ this._progress(options, 'error_state', 'Transfer vacΓ­o β€” capturando mensajes de error...');
366
+ console.log(chalk.gray(' πŸ“Έ Error state: Transfer vacΓ­o β€” Submit sin monto...'));
213
367
  const emptyTransferOk = this._runMaestroFlow(appId, [
214
368
  `- tapOn:\n id: "btn_confirm"`,
215
369
  `- waitForAnimationToEnd:\n timeout: 1500`,
216
370
  ], maestroEnv);
217
371
  if (emptyTransferOk) {
218
- const transferErrorHierarchy = await this._captureHierarchy(maestroEnv);
219
- const transferErrorAll = this.extractMaestroSelectors(transferErrorHierarchy);
372
+ await sleep(1500); // wait for error UI to settle before screencap
373
+ const transferErrorScreenshot = await this._captureScreenshotMobile(adbS, 'transfer_error');
374
+ const transferErrorHierarchy = await this._captureHierarchy(maestroEnv, options.deviceId);
375
+ const transferErrorAllElems = this.extractMaestroSelectors(transferErrorHierarchy);
376
+ const transferErrorTexts = this.extractAllTexts(transferErrorHierarchy);
220
377
  const knownTransferIds = new Set(transferElements.map(e => e.id));
221
- const transferErrorNew = transferErrorAll.filter(e => !knownTransferIds.has(e.id));
222
- if (transferErrorNew.length > 0) {
223
- allScreens.push({ name: 'Transfer (Error State)', elements: transferErrorNew, hierarchy: transferErrorHierarchy });
224
- console.log(chalk.green(` βœ… Transfer error state: ${transferErrorNew.length} new elements (e.g. ${transferErrorNew.map(e => e.id).join(', ')})`));
225
- }
378
+ const transferErrorNew = transferErrorAllElems.filter(e => !knownTransferIds.has(e.id));
379
+ const transferNewTexts = transferErrorTexts.filter(t => !transferTexts.includes(t));
380
+ allScreens.push({
381
+ name: 'Transferencia (Error β€” monto vacΓ­o)',
382
+ isErrorState: true,
383
+ screenshot: transferErrorScreenshot,
384
+ elements: transferErrorNew,
385
+ allTexts: transferNewTexts,
386
+ });
387
+ navigationSteps.push({ from: 'Transferencia', to: 'Transferencia (Error β€” monto vacΓ­o)', action: 'Submit vacΓ­o' });
388
+ const errList = transferNewTexts.slice(0, 3).map(t => `"${t}"`).join(', ');
389
+ console.log(chalk.green(` βœ… Transfer error state: ${transferErrorNew.length} elementos${errList ? ` | Textos: ${errList}` : ''}`));
390
+ }
391
+ else {
392
+ console.log(chalk.yellow(' ⚠️ No se pudo provocar error de transfer vacío'));
226
393
  }
227
394
  }
228
395
  else {
229
- console.log(chalk.yellow(' ⚠️ Transfer screen not reachable β€” skipping'));
396
+ console.log(chalk.yellow(' ⚠️ Pantalla de Transferencia no accesible β€” omitiendo'));
397
+ }
398
+ // ── Error state: Credenciales invΓ‘lidas ───────────────────────
399
+ this._progress(options, 'error_state', 'Credenciales invΓ‘lidas β€” capturando mensaje real...');
400
+ console.log(chalk.gray(' πŸ“Έ Error state: Credenciales invΓ‘lidas...'));
401
+ // Force a clean state via ADB before the Maestro flow β€” avoids capturing
402
+ // stale Transfer-screen elements if the previous error-state flow left the
403
+ // device on that screen and launchApp:clearState takes time.
404
+ try {
405
+ execSync(`${adbS} shell am force-stop ${appId}`, { stdio: 'ignore' });
406
+ execSync(`${adbS} shell pm clear ${appId}`, { stdio: 'ignore' });
407
+ }
408
+ catch { }
409
+ await sleep(1500);
410
+ this._runMaestroFlow(appId, [
411
+ `- launchApp`,
412
+ `- waitForAnimationToEnd:\n timeout: 3000`,
413
+ `- tapOn:\n id: "et_username"`,
414
+ `- inputText: "usuario_invalido_fpqa@test.com"`,
415
+ `- waitForAnimationToEnd`,
416
+ `- hideKeyboard`,
417
+ `- tapOn:\n id: "et_password"`,
418
+ `- inputText: "wrongpassword999"`,
419
+ `- waitForAnimationToEnd`,
420
+ `- hideKeyboard`,
421
+ `- tapOn:\n id: "btn_login"`,
422
+ `- waitForAnimationToEnd:\n timeout: 4000`,
423
+ ], maestroEnv);
424
+ await sleep(2500); // wait for the error toast / message to render
425
+ let invalidCredsHierarchy = null;
426
+ try {
427
+ invalidCredsHierarchy = await this._captureHierarchy(maestroEnv, options.deviceId);
428
+ }
429
+ catch { }
430
+ if (invalidCredsHierarchy) {
431
+ const invalidCredsScreenshot = await this._captureScreenshotMobile(adbS, 'invalid_creds');
432
+ const invalidCredsAllElems = this.extractMaestroSelectors(invalidCredsHierarchy);
433
+ const invalidCredsTexts = this.extractAllTexts(invalidCredsHierarchy);
434
+ const invalidCredsNewTexts = invalidCredsTexts.filter(t => !loginTexts.includes(t));
435
+ const knownLoginIds = new Set(loginElements.map(e => e.id));
436
+ const invalidCredsNewElems = invalidCredsAllElems.filter(e => !knownLoginIds.has(e.id));
437
+ if (invalidCredsNewTexts.length > 0) {
438
+ allScreens.push({
439
+ name: 'Login (Error β€” credenciales invΓ‘lidas)',
440
+ isErrorState: true,
441
+ screenshot: invalidCredsScreenshot,
442
+ elements: invalidCredsNewElems,
443
+ allTexts: invalidCredsNewTexts,
444
+ });
445
+ navigationSteps.push({ from: 'Login', to: 'Login (Error β€” credenciales invΓ‘lidas)', action: 'Credenciales invΓ‘lidas' });
446
+ const errList = invalidCredsNewTexts.slice(0, 3).map(t => `"${t}"`).join(', ');
447
+ console.log(chalk.green(` βœ… Creds invΓ‘lidas: textos reales encontrados: ${errList}`));
448
+ }
230
449
  }
231
450
  }
232
451
  else {
233
- console.log(chalk.yellow(' ⚠️ Login failed β€” only Login screen captured'));
452
+ console.log(chalk.yellow(' ⚠️ Login fallΓ³ β€” solo se capturΓ³ pantalla de Login'));
234
453
  }
235
454
  }
236
- // ── Build comprehensive discovery plan ────────────────────────────
455
+ // ── Build evidence package ─────────────────────────────────────────
456
+ const finishedAt = Date.now();
237
457
  const totalElements = allScreens.reduce((sum, s) => sum + s.elements.length, 0);
238
- const screenSections = allScreens.map(screen => `
239
- ### Screen: ${screen.name}
240
- | Element Type | Text/Content | testID / Identifier |
241
- |--------------|--------------|---------------------|
242
- ${screen.elements.map(e => `| ${e.type} | ${e.text} | \`${e.id}\` |`).join('\n') || '| β€” | No interactive elements found | β€” |'}
243
- `).join('\n');
244
- const planContent = `# Discovery Plan: Mobile App (${appId})
245
- Generated: ${new Date().toISOString()}
246
-
247
- ## App Overview
248
- - **App ID**: ${appId}
249
- - **Screens discovered**: ${allScreens.length}
250
- - **Total interactive elements**: ${totalElements}
251
- - **Framework**: Maestro (Android native)
252
- - **Device**: Physical device (ADB)
253
-
254
- ## Screen Intelligence
255
- ${screenSections}
256
-
257
- ## Suggested Test Flows
258
-
259
- ### Flow 1 β€” Login con credenciales vΓ‘lidas
260
- 1. Ingresar email en \`et_username\`
261
- 2. Ingresar contraseΓ±a en \`et_password\`
262
- 3. Tap \`btn_login\`
263
- 4. Verificar pantalla de cuentas visible
264
-
265
- ### Flow 2 β€” Login con credenciales invΓ‘lidas
266
- 1. Ingresar email incorrecto
267
- 2. Ingresar contraseΓ±a incorrecta
268
- 3. Tap \`btn_login\`
269
- 4. Verificar mensaje de error visible
270
-
271
- ### Flow 3 β€” Consulta de saldo
272
- 1. Login exitoso
273
- 2. Verificar \`tv_total_balance\` visible
274
- 3. Verificar \`card_checking\` y \`card_savings\` presentes
275
-
276
- ### Flow 4 β€” Transferencia exitosa
277
- 1. Login β†’ tap \`btn_transfer\`
278
- 2. Ingresar monto en \`et_amount\`
279
- 3. Ingresar destinatario en \`et_recipient\`
280
- 4. Tap \`btn_confirm\`
281
- 5. Verificar mensaje de Γ©xito
282
-
283
- ### Flow 5 β€” Transferencia con monto invΓ‘lido
284
- 1. Login β†’ tap \`btn_transfer\`
285
- 2. Dejar monto vacΓ­o
286
- 3. Tap \`btn_confirm\`
287
- 4. Verificar mensaje de error
288
-
289
- ### Flow 6 β€” Logout
290
- 1. Login exitoso
291
- 2. Tap \`btn_logout\`
292
- 3. Verificar redirecciΓ³n a Login screen
293
-
294
- ## UI Health
295
- - Total interactive nodes detected: ${totalElements}
296
- - Screens mapped: ${allScreens.map(s => s.name).join(', ')}
297
- - Screen structure complexity: ${totalElements > 15 ? 'High' : totalElements > 8 ? 'Medium' : 'Low'}
298
- `;
458
+ const errorStates = allScreens.filter(s => s.isErrorState).length;
459
+ // Collect all verified IDs and texts across all screens
460
+ const verifiedIds = [...new Set(allScreens.flatMap(s => s.elements.map(e => e.id)))];
461
+ const verifiedTexts = [...new Set(allScreens
462
+ .filter(s => s.isErrorState) // Only error states produce truly "verified" assertion texts
463
+ .flatMap(s => s.allTexts))];
464
+ const evidence = {
465
+ screens: allScreens,
466
+ metrics: {
467
+ startedAt,
468
+ finishedAt,
469
+ durationMs: finishedAt - startedAt,
470
+ screensDiscovered: allScreens.length,
471
+ errorStatesExplored: errorStates,
472
+ elementsFound: totalElements,
473
+ navigationSteps,
474
+ },
475
+ verifiedTexts,
476
+ verifiedIds,
477
+ };
478
+ // ── Build plan content from evidence (dynamic, includes all discovered flows) ─
479
+ const planContent = this.buildPlanFromEvidence(evidence, appId);
299
480
  return {
300
481
  planContent,
301
482
  rawScanData: {
@@ -304,23 +485,34 @@ ${screenSections}
304
485
  appId,
305
486
  framework: 'maestro',
306
487
  },
488
+ evidence,
307
489
  };
308
490
  }
309
491
  catch (error) {
310
- console.log(chalk.red(` ❌ Discovery error: ${error.message}`));
492
+ const msg = error.message || String(error);
493
+ const isMaestroHierarchy = msg.includes('maestro') && msg.includes('hierarchy');
494
+ console.log(chalk.red(`\n ❌ Error en Discovery: ${msg}`));
495
+ if (isMaestroHierarchy) {
496
+ console.log(chalk.yellow('\n πŸ’‘ Posibles causas:'));
497
+ console.log(chalk.dim(' β€’ La pantalla del dispositivo estaba apagada o bloqueada'));
498
+ console.log(chalk.dim(' β€’ Maestro perdiΓ³ conexiΓ³n con el driver del dispositivo'));
499
+ console.log(chalk.dim(` β€’ Prueba: adb -s ${options.deviceId ?? '<serial>'} shell input keyevent KEYCODE_WAKEUP`));
500
+ console.log(chalk.dim(' β€’ Luego ejecuta el comando de Discovery de nuevo\n'));
501
+ }
311
502
  return {
312
- planContent: `# Discovery Plan: Mobile App (${appId})\nStatus: FAIL\nError: ${error.message}\n`,
313
- rawScanData: { error: error.message },
503
+ planContent: `# Discovery Plan: Mobile App (${appId})\nEstado: FALLIDO\nError: ${msg}\n`,
504
+ rawScanData: { error: msg },
314
505
  };
315
506
  }
316
507
  },
508
+ // ── Web Discovery ────────────────────────────────────────────────────────
317
509
  async handleLogin(page, username, password) {
318
510
  try {
319
511
  const passwordField = page.locator('input[type="password"]').first();
320
512
  const count = await passwordField.count();
321
513
  if (count === 0)
322
514
  return false;
323
- console.log(chalk.gray('πŸ” Login form detected β€” filling credentials...'));
515
+ console.log(chalk.gray('πŸ” Formulario de login detectado β€” ingresando credenciales...'));
324
516
  const usernameField = page.locator('input[type="email"], input[name="email"], input[name="username"], input[name="user"], ' +
325
517
  'input[placeholder*="correo" i], input[placeholder*="email" i], input[placeholder*="usuario" i]').first();
326
518
  await usernameField.fill(username);
@@ -331,30 +523,34 @@ ${screenSections}
331
523
  await submitBtn.click();
332
524
  await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => { });
333
525
  await page.waitForTimeout(600);
334
- console.log(chalk.green('βœ… Login successful β€” continuing discovery on authenticated page...'));
526
+ console.log(chalk.green('βœ… Login exitoso β€” continuando discovery en pΓ‘gina autenticada...'));
335
527
  return true;
336
528
  }
337
529
  catch (err) {
338
- console.log(chalk.yellow(`⚠️ Login attempt failed: ${err.message}`));
530
+ console.log(chalk.yellow(`⚠️ Login fallido: ${err.message}`));
339
531
  return false;
340
532
  }
341
533
  },
342
534
  async discoverWeb(options) {
343
535
  const { chromium } = await import('playwright');
344
- console.log(chalk.gray('🌐 Launching Autonomous Playwright Crawler...'));
536
+ const startedAt = Date.now();
537
+ this._progress(options, 'start', 'Iniciando crawler Playwright...');
538
+ console.log(chalk.gray('🌐 Iniciando Playwright Crawler autónomo...'));
345
539
  const browser = await chromium.launch({ headless: true });
346
- const context = await browser.newContext({
347
- viewport: { width: 1440, height: 900 },
348
- });
540
+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
349
541
  const page = await context.newPage();
542
+ const webScreens = [];
350
543
  try {
544
+ this._progress(options, 'navigate', `Navegando a ${options.url}...`);
351
545
  await page.goto(options.url, { waitUntil: 'networkidle' });
352
- // ── Handle login if credentials provided ────────────────────────
546
+ // Handle login if credentials provided
353
547
  if (options.username && options.password) {
548
+ this._progress(options, 'login', 'Intentando autenticaciΓ³n...');
354
549
  await this.handleLogin(page, options.username, options.password);
355
550
  }
356
551
  const title = await page.title();
357
- // ── Phase 1: Extract DOM elements ────────────────────────────────
552
+ this._progress(options, 'dom', 'Extrayendo elementos del DOM...');
553
+ // Phase 1: Extract DOM elements
358
554
  const elements = await page.evaluate(() => {
359
555
  // @ts-ignore β€” runs in browser context
360
556
  const interactive = Array.from(document.querySelectorAll('button, a, input, select, textarea, [role="button"], [role="link"], [role="menuitem"]'));
@@ -376,33 +572,46 @@ ${screenSections}
376
572
  };
377
573
  }).filter((e) => e.visible);
378
574
  });
379
- // ── Phase 2: Take screenshots (viewport + scrolled sections) ─────
380
- console.log(chalk.gray('πŸ“Έ Capturing page screenshots for Vision AI analysis...'));
575
+ // Phase 2: Screenshots
576
+ this._progress(options, 'screenshot', 'Capturando screenshots de la pΓ‘gina...');
577
+ console.log(chalk.gray('πŸ“Έ Capturando screenshots para anΓ‘lisis Vision AI...'));
381
578
  const screenshots = [];
382
- // Full-page screenshot
383
579
  const fullPageBuffer = await page.screenshot({ fullPage: true, type: 'png' });
384
580
  screenshots.push(fullPageBuffer.toString('base64'));
385
- // Viewport sections (scroll through page)
386
- // @ts-ignore β€” runs in browser context
581
+ // @ts-ignore
387
582
  const pageHeight = await page.evaluate(() => document.body.scrollHeight);
388
583
  const viewportHeight = 900;
389
584
  const sections = Math.min(Math.ceil(pageHeight / viewportHeight), 4);
390
585
  for (let i = 1; i < sections; i++) {
391
- // @ts-ignore β€” runs in browser context
586
+ // @ts-ignore
392
587
  await page.evaluate((scrollY) => window.scrollTo(0, scrollY), i * viewportHeight);
393
588
  await page.waitForTimeout(400);
394
589
  const sectionBuffer = await page.screenshot({ type: 'png' });
395
590
  screenshots.push(sectionBuffer.toString('base64'));
396
591
  }
397
- // @ts-ignore β€” runs in browser context
592
+ // @ts-ignore
398
593
  await page.evaluate(() => window.scrollTo(0, 0));
594
+ // Store web screenshots in evidence
595
+ webScreens.push({
596
+ name: title || options.url,
597
+ isErrorState: false,
598
+ screenshot: screenshots[0] || null,
599
+ elements: elements.slice(0, 30).map(e => ({
600
+ type: e.tag,
601
+ text: e.text || e.placeholder || e.ariaLabel || 'N/A',
602
+ id: e.testId || e.id || e.name || '',
603
+ })),
604
+ allTexts: [],
605
+ });
399
606
  await browser.close();
400
- console.log(chalk.gray(` Captured ${screenshots.length} screenshots, ${elements.length} DOM elements`));
401
- // ── Phase 3: Vision AI Analysis (if project/entity provided) ─────
607
+ console.log(chalk.gray(` ${screenshots.length} screenshots, ${elements.length} elementos DOM`));
608
+ const finishedAt = Date.now();
609
+ // Phase 3: Vision AI Analysis
402
610
  let planContent;
611
+ this._progress(options, 'vision', 'Enviando a Vision AI para anΓ‘lisis semΓ‘ntico...');
403
612
  if (options.projectId && options.entityId) {
404
613
  try {
405
- console.log(chalk.gray('🧠 Sending to Vision AI for semantic analysis...'));
614
+ console.log(chalk.gray('🧠 Enviando a Vision AI para anÑlisis semÑntico...'));
406
615
  const visionResult = await FlowSpecQAApi.analyzeVision({
407
616
  url: options.url,
408
617
  entity_id: options.entityId,
@@ -412,21 +621,39 @@ ${screenSections}
412
621
  page_title: title,
413
622
  });
414
623
  planContent = visionResult.plan_content;
415
- console.log(chalk.gray(` Vision analysis: ${visionResult.analysis_chars} chars, ` +
416
- `${visionResult.screenshots_analyzed} screenshots processed`));
624
+ console.log(chalk.gray(` Vision: ${visionResult.analysis_chars} chars, ` +
625
+ `${visionResult.screenshots_analyzed} screenshots procesados`));
417
626
  }
418
627
  catch (visionErr) {
419
- console.log(chalk.yellow(`⚠️ Vision AI unavailable (${visionErr.message}), falling back to DOM plan...`));
628
+ console.log(chalk.yellow(`⚠️ Vision AI no disponible (${visionErr.message}), usando plan DOM...`));
420
629
  planContent = this._buildDomPlan(title, options.url, elements);
421
630
  }
422
631
  }
423
632
  else {
424
- // No project/entity β†’ DOM plan only (local use)
425
633
  planContent = this._buildDomPlan(title, options.url, elements);
426
634
  }
635
+ const verifiedIds = [...new Set(elements
636
+ .filter(e => e.testId || e.id || e.name)
637
+ .map(e => e.testId || e.id || e.name)
638
+ .filter(Boolean))];
639
+ const evidence = {
640
+ screens: webScreens,
641
+ metrics: {
642
+ startedAt,
643
+ finishedAt,
644
+ durationMs: finishedAt - startedAt,
645
+ screensDiscovered: 1,
646
+ errorStatesExplored: 0,
647
+ elementsFound: elements.length,
648
+ navigationSteps: [{ from: 'Inicio', to: title || options.url, action: 'NavegaciΓ³n directa' }],
649
+ },
650
+ verifiedTexts: [], // Web: texts come from Vision AI analysis
651
+ verifiedIds,
652
+ };
427
653
  return {
428
654
  planContent,
429
655
  rawScanData: { elements, url: options.url, framework: 'playwright', total: elements.length },
656
+ evidence,
430
657
  };
431
658
  }
432
659
  catch (error) {
@@ -438,14 +665,14 @@ ${screenSections}
438
665
  _buildDomPlan(title, url, elements) {
439
666
  return `# Discovery Plan: Web App (${title})
440
667
  URL: ${url}
441
- Generated: ${new Date().toISOString()}
668
+ Generado: ${new Date().toISOString()}
442
669
 
443
- ## Intelligence Summary
444
- Found **${elements.length}** interactive elements on the landing page.
670
+ ## Resumen
671
+ **${elements.length}** elementos interactivos encontrados.
445
672
 
446
- ### Primary UI Map
447
- | Tag | Description / Text | Suggested Selector | testID |
448
- |-----|--------------------|-------------------|--------|
673
+ ### Mapa de UI Principal
674
+ | Tag | DescripciΓ³n | Selector sugerido | testID |
675
+ |-----|-------------|-------------------|--------|
449
676
  ${elements.slice(0, 20).map((e) => {
450
677
  let selector = e.tag;
451
678
  if (e.testId)
@@ -461,12 +688,362 @@ ${elements.slice(0, 20).map((e) => {
461
688
  return `| ${e.tag} | ${e.text || e.placeholder || e.ariaLabel || '-'} | \`${selector}\` | ${e.testId || '-'} |`;
462
689
  }).join('\n')}
463
690
 
464
- ## Structure
465
- - Detected ${elements.filter((e) => e.tag === 'button').length} buttons.
466
- - Detected ${elements.filter((e) => e.tag === 'a').length} links.
467
- - Detected ${elements.filter((e) => e.tag === 'input').length} inputs.
691
+ ## Estructura
692
+ - ${elements.filter((e) => e.tag === 'button').length} botones
693
+ - ${elements.filter((e) => e.tag === 'a').length} links
694
+ - ${elements.filter((e) => e.tag === 'input').length} inputs
468
695
  `;
469
696
  },
697
+ // ── Interactive Discovery helpers ────────────────────────────────────────
698
+ /**
699
+ * Inspect the current evidence and return elements that were seen on screen
700
+ * but never explicitly interacted with during Discovery.
701
+ * These become the candidates for the interactive exploration loop.
702
+ */
703
+ detectUnexplored(evidence) {
704
+ // Collect element IDs that were explicitly tapped in navigation
705
+ const exploredIds = new Set();
706
+ for (const step of evidence.metrics.navigationSteps) {
707
+ const tapMatch = step.action.match(/^Tap\s+(\S+)/i);
708
+ if (tapMatch)
709
+ exploredIds.add(tapMatch[1]);
710
+ }
711
+ // Elements handled by the hardcoded login / submit flows
712
+ const ALWAYS_HANDLED = new Set([
713
+ 'btn_login', 'btn_confirm', 'et_username', 'et_password',
714
+ 'btn_submit', 'btn_register', 'btn_back',
715
+ ]);
716
+ const unexplored = [];
717
+ const seenIds = new Set();
718
+ for (const screen of evidence.screens) {
719
+ if (screen.isErrorState)
720
+ continue; // don't suggest exploring error screens
721
+ for (const elem of screen.elements) {
722
+ if (!elem.id || elem.id === 'N/A')
723
+ continue;
724
+ if (seenIds.has(elem.id))
725
+ continue;
726
+ if (exploredIds.has(elem.id))
727
+ continue;
728
+ if (ALWAYS_HANDLED.has(elem.id))
729
+ continue;
730
+ // Only Button / ImageButton are worth suggesting for exploration.
731
+ // TextViews and FrameLayouts might be clickable but we can't tell from type alone β€”
732
+ // those that matter get picked up via the first tap anyway.
733
+ const isClickable = ['Button', 'ImageButton'].includes(elem.type);
734
+ if (!isClickable)
735
+ continue;
736
+ seenIds.add(elem.id);
737
+ unexplored.push({
738
+ elementId: elem.id,
739
+ elementText: elem.text === 'N/A' ? '' : elem.text,
740
+ sourceScreen: screen.name,
741
+ elementType: elem.type,
742
+ });
743
+ }
744
+ }
745
+ return unexplored;
746
+ },
747
+ /**
748
+ * Convert a navigation step action string into the Maestro YAML steps
749
+ * needed to perform that action.
750
+ */
751
+ _getActionYaml(action, creds) {
752
+ if (action === 'Lanzar app') {
753
+ return [
754
+ `- launchApp:\n clearState: true`,
755
+ `- waitForAnimationToEnd`,
756
+ ];
757
+ }
758
+ if (action === 'Login con credenciales vΓ‘lidas') {
759
+ return [
760
+ `- tapOn:\n id: "et_username"`,
761
+ `- eraseText: 50`,
762
+ `- inputText: "${creds.username}"`,
763
+ `- waitForAnimationToEnd`,
764
+ `- hideKeyboard`,
765
+ `- tapOn:\n id: "et_password"`,
766
+ `- eraseText: 30`,
767
+ `- inputText: "${creds.password}"`,
768
+ `- waitForAnimationToEnd`,
769
+ `- hideKeyboard`,
770
+ `- tapOn:\n id: "btn_login"`,
771
+ `- waitForAnimationToEnd`,
772
+ ];
773
+ }
774
+ const tapMatch = action.match(/^Tap\s+(\S+)/i);
775
+ if (tapMatch) {
776
+ return [
777
+ `- tapOn:\n id: "${tapMatch[1]}"`,
778
+ `- waitForAnimationToEnd`,
779
+ ];
780
+ }
781
+ return []; // unknown / error-state actions β€” skip
782
+ },
783
+ /**
784
+ * BFS the navigation graph to build and execute the Maestro flow that
785
+ * navigates from the app's initial state to `targetScreen`.
786
+ * Returns true if navigation succeeded, false otherwise.
787
+ */
788
+ async _navigateToScreen(targetScreen, evidence, creds, appId, maestroEnv) {
789
+ // Build adjacency list β€” skip edges that lead to error states
790
+ const graph = new Map();
791
+ for (const step of evidence.metrics.navigationSteps) {
792
+ const toScreen = evidence.screens.find(s => s.name === step.to);
793
+ if (toScreen?.isErrorState)
794
+ continue; // never route through error states
795
+ if (!graph.has(step.from))
796
+ graph.set(step.from, []);
797
+ graph.get(step.from).push({ to: step.to, action: step.action });
798
+ }
799
+ if (targetScreen === 'Inicio')
800
+ return true; // already at start
801
+ // BFS from 'Inicio'
802
+ const visited = new Set();
803
+ const queue = [
804
+ { screen: 'Inicio', actions: [] },
805
+ ];
806
+ while (queue.length > 0) {
807
+ const { screen, actions } = queue.shift();
808
+ if (screen === targetScreen) {
809
+ if (actions.length === 0)
810
+ return true;
811
+ return this._runMaestroFlow(appId, actions, maestroEnv);
812
+ }
813
+ if (visited.has(screen))
814
+ continue;
815
+ visited.add(screen);
816
+ for (const edge of (graph.get(screen) || [])) {
817
+ const stepYaml = this._getActionYaml(edge.action, creds);
818
+ queue.push({ screen: edge.to, actions: [...actions, ...stepYaml] });
819
+ }
820
+ }
821
+ return false; // path not found
822
+ },
823
+ /**
824
+ * Explore a single previously-unexplored element:
825
+ * 1. Navigate to its source screen
826
+ * 2. Tap the element
827
+ * 3. Capture hierarchy + screenshot of the resulting state
828
+ * 4. Attempt to trigger an error state on the new screen
829
+ * 5. Push findings into `evidence` in-place
830
+ *
831
+ * Returns the new ScreenEvidence entries that were added.
832
+ */
833
+ async exploreElement(element, options, evidence) {
834
+ const appId = options.url;
835
+ const adb = resolveAdb();
836
+ const adbS = options.deviceId ? `"${adb}" -s ${options.deviceId}` : `"${adb}"`;
837
+ const maestroEnv = options.deviceId
838
+ ? { ...process.env, MAESTRO_DEVICE_ID: options.deviceId }
839
+ : process.env;
840
+ const creds = { username: options.username || '', password: options.password || '' };
841
+ const added = [];
842
+ console.log(chalk.gray(` πŸ”­ Navegando a "${element.sourceScreen}"...`));
843
+ // 1. Navigate to the source screen from app start
844
+ const navOk = await this._navigateToScreen(element.sourceScreen, evidence, creds, appId, maestroEnv);
845
+ if (!navOk) {
846
+ console.log(chalk.yellow(` ⚠️ No se pudo navegar a "${element.sourceScreen}"`));
847
+ return [];
848
+ }
849
+ await sleep(2000); // wait for screen to settle
850
+ // 2. Tap the element
851
+ console.log(chalk.gray(` πŸ‘† Tap en ${element.elementId}...`));
852
+ const tapOk = this._runMaestroFlow(appId, [
853
+ `- tapOn:\n id: "${element.elementId}"`,
854
+ `- waitForAnimationToEnd:\n timeout: 3000`,
855
+ ], maestroEnv);
856
+ if (!tapOk) {
857
+ console.log(chalk.yellow(` ⚠️ Tap en ${element.elementId} falló`));
858
+ return [];
859
+ }
860
+ await sleep(2000); // wait for the new screen to render
861
+ // 3. Capture resulting state
862
+ let hierarchy;
863
+ try {
864
+ hierarchy = await this._captureHierarchy(maestroEnv, options.deviceId);
865
+ }
866
+ catch {
867
+ console.log(chalk.yellow(` ⚠️ No se pudo capturar jerarquía`));
868
+ return [];
869
+ }
870
+ const screenshot = await this._captureScreenshotMobile(adbS, `explore_${element.elementId}`);
871
+ const newElements = this.extractMaestroSelectors(hierarchy);
872
+ const newTexts = this.extractAllTexts(hierarchy);
873
+ // Decide if this looks like a new screen
874
+ const sourceScreenData = evidence.screens.find(s => s.name === element.sourceScreen);
875
+ const sourceIds = new Set((sourceScreenData?.elements || []).map(e => e.id));
876
+ const novelElements = newElements.filter(e => !sourceIds.has(e.id));
877
+ if (novelElements.length < 2 && !screenshot) {
878
+ console.log(chalk.yellow(` ⚠️ ${element.elementId} no abrió pantalla nueva (mismos elementos)`));
879
+ // Still mark as explored by recording a navigation step with no destination screen
880
+ evidence.metrics.navigationSteps.push({
881
+ from: element.sourceScreen,
882
+ to: `${element.sourceScreen} (sin cambio)`,
883
+ action: `Tap ${element.elementId}`,
884
+ });
885
+ return [];
886
+ }
887
+ // 4. Register new screen
888
+ const screenName = novelElements.length > 0
889
+ ? `${element.elementId} (desde ${element.sourceScreen})`
890
+ : `${element.sourceScreen} β€” ${element.elementText || element.elementId}`;
891
+ const newScreen = {
892
+ name: screenName,
893
+ isErrorState: false,
894
+ screenshot,
895
+ elements: newElements,
896
+ allTexts: newTexts,
897
+ };
898
+ added.push(newScreen);
899
+ evidence.screens.push(newScreen);
900
+ evidence.metrics.navigationSteps.push({
901
+ from: element.sourceScreen,
902
+ to: screenName,
903
+ action: `Tap ${element.elementId}`,
904
+ });
905
+ evidence.metrics.screensDiscovered++;
906
+ evidence.metrics.elementsFound += novelElements.length;
907
+ // Track verified IDs from the new screen
908
+ for (const e of newElements) {
909
+ if (e.id && !evidence.verifiedIds.includes(e.id))
910
+ evidence.verifiedIds.push(e.id);
911
+ }
912
+ console.log(chalk.green(` βœ… Nueva pantalla: "${screenName}" | ${novelElements.length} elementos nuevos${screenshot ? ' | screenshot βœ“' : ''}`));
913
+ // 5. Try to trigger error state on new screen (tap first submit-like button without filling fields)
914
+ const submitBtn = newElements.find(e => ['btn_confirm', 'btn_submit', 'btn_pay', 'btn_send', 'btn_continue', 'btn_accept'].includes(e.id) ||
915
+ (e.type === 'Button' && e.id !== element.elementId));
916
+ if (submitBtn) {
917
+ console.log(chalk.gray(` πŸ“Έ Intentando error state (${submitBtn.id})...`));
918
+ const errorOk = this._runMaestroFlow(appId, [
919
+ `- tapOn:\n id: "${submitBtn.id}"`,
920
+ `- waitForAnimationToEnd:\n timeout: 1500`,
921
+ ], maestroEnv);
922
+ if (errorOk) {
923
+ await sleep(1500);
924
+ try {
925
+ const errHierarchy = await this._captureHierarchy(maestroEnv, options.deviceId);
926
+ const errScreenshot = await this._captureScreenshotMobile(adbS, `explore_${element.elementId}_err`);
927
+ const errElements = this.extractMaestroSelectors(errHierarchy);
928
+ const errTexts = this.extractAllTexts(errHierarchy);
929
+ const knownIds = new Set(newElements.map(e => e.id));
930
+ const errNewElems = errElements.filter(e => !knownIds.has(e.id));
931
+ const errNewTexts = errTexts.filter(t => !newTexts.includes(t));
932
+ if (errNewTexts.length > 0 || errNewElems.length > 0) {
933
+ const errScreenName = `${screenName} (Error)`;
934
+ const errScreen = {
935
+ name: errScreenName,
936
+ isErrorState: true,
937
+ screenshot: errScreenshot,
938
+ elements: errNewElems,
939
+ allTexts: errNewTexts,
940
+ };
941
+ added.push(errScreen);
942
+ evidence.screens.push(errScreen);
943
+ evidence.metrics.navigationSteps.push({
944
+ from: screenName,
945
+ to: errScreenName,
946
+ action: `Submit vacΓ­o (${submitBtn.id})`,
947
+ });
948
+ evidence.metrics.errorStatesExplored++;
949
+ for (const t of errNewTexts) {
950
+ if (!evidence.verifiedTexts.includes(t))
951
+ evidence.verifiedTexts.push(t);
952
+ }
953
+ const errList = errNewTexts.slice(0, 3).map(t => `"${t}"`).join(', ');
954
+ console.log(chalk.green(` βœ… Error state: ${errList || 'capturado'}`));
955
+ }
956
+ }
957
+ catch { /* non-fatal */ }
958
+ }
959
+ }
960
+ return added;
961
+ },
962
+ /**
963
+ * Build the full discovery plan markdown from an evidence package.
964
+ * Called after each interactive exploration round to keep the plan current.
965
+ * Also used by discoverMobile() for the initial plan generation.
966
+ */
967
+ buildPlanFromEvidence(evidence, appId) {
968
+ const { screens, metrics, verifiedTexts, verifiedIds } = evidence;
969
+ // ── Screen sections ───────────────────────────────────────────────────
970
+ const screenSections = screens.map(screen => `
971
+ ### Pantalla: ${screen.name}${screen.isErrorState ? ' ⚠️' : ''}
972
+ | Tipo | Texto | ID |
973
+ |------|-------|-----|
974
+ ${screen.elements.map(e => `| ${e.type} | ${e.text} | \`${e.id}\` |`).join('\n') || '| β€” | Sin elementos interactivos | β€” |'}
975
+ ${screen.allTexts.length > 0 ? `\n**Textos verificados en pantalla:** ${screen.allTexts.slice(0, 10).map(t => `"${t}"`).join(', ')}` : ''}
976
+ `).join('\n');
977
+ // ── Confidence map ────────────────────────────────────────────────────
978
+ const confidenceSection = `
979
+ ## 🎯 Mapa de Confianza
980
+
981
+ ### IDs verificados (confianza ALTA β€” elemento visto en dispositivo real)
982
+ ${verifiedIds.length > 0 ? verifiedIds.map(id => `- \`${id}\``).join('\n') : '- Ninguno'}
983
+
984
+ ### Textos verificados en error states (confianza ALTA β€” texto real de la app)
985
+ ${verifiedTexts.length > 0 ? verifiedTexts.map(t => `- "${t}"`).join('\n') : '- Ninguno β€” revisar manualmente (Discovery Fase 2 los capturarΓ‘)'}
986
+
987
+ ### ⚠️ Textos NO verificados = Confianza BAJA
988
+ Los assertVisible con textos que NO aparezcan arriba fueron inferidos por la IA.
989
+ Son los candidatos mΓ‘s probables a fallar en la primera ejecuciΓ³n.
990
+ `;
991
+ // ── Flows β€” generated dynamically from navigation graph ───────────────
992
+ const flows = [];
993
+ let flowNum = 1;
994
+ // Non-error navigation flows
995
+ for (const step of metrics.navigationSteps) {
996
+ const toScreen = screens.find(s => s.name === step.to);
997
+ if (!toScreen || toScreen.isErrorState)
998
+ continue;
999
+ if (step.to.includes('sin cambio'))
1000
+ continue; // skip no-op taps
1001
+ const verifyElems = toScreen.elements.slice(0, 2).map(e => `\`${e.id}\``).join(', ');
1002
+ flows.push(`### Flujo ${flowNum++} β€” ${step.to} βœ…\n` +
1003
+ `**AcciΓ³n:** ${step.action}\n` +
1004
+ `**Verificar:** elementos visibles${verifyElems ? ` (${verifyElems})` : ''}`);
1005
+ }
1006
+ // Error state flows
1007
+ for (const screen of screens.filter(s => s.isErrorState)) {
1008
+ const step = metrics.navigationSteps.find(ns => ns.to === screen.name);
1009
+ if (!step)
1010
+ continue;
1011
+ const errorTexts = screen.allTexts.slice(0, 3).map(t => `"${t}"`).join(', ');
1012
+ flows.push(`### Flujo ${flowNum++} β€” ${screen.name} πŸ”΄\n` +
1013
+ `**AcciΓ³n:** ${step.action} (desde ${step.from})\n` +
1014
+ `**Verificar:** ${errorTexts || 'mensaje de error visible'}`);
1015
+ }
1016
+ const totalElements = screens.reduce((sum, s) => sum + s.elements.length, 0);
1017
+ const errorStates = screens.filter(s => s.isErrorState).length;
1018
+ return `# Discovery Plan: Mobile App (${appId})
1019
+ Generado: ${new Date().toISOString()}
1020
+ DuraciΓ³n: ${Math.round(metrics.durationMs / 1000)}s
1021
+
1022
+ ## Resumen del App
1023
+ - **App ID**: ${appId}
1024
+ - **Pantallas descubiertas**: ${screens.length}
1025
+ - **Error states explorados**: ${errorStates}
1026
+ - **Elementos interactivos totales**: ${totalElements}
1027
+ - **Textos de error verificados**: ${verifiedTexts.length}
1028
+ - **Framework**: Maestro (Android native)
1029
+ - **Dispositivo**: Dispositivo fΓ­sico (ADB)
1030
+
1031
+ ## Mapa de Pantallas
1032
+ ${screenSections}
1033
+
1034
+ ${confidenceSection}
1035
+
1036
+ ## Flujos de Prueba Sugeridos
1037
+
1038
+ ${flows.join('\n\n')}
1039
+
1040
+ ## UI Health
1041
+ - Total de nodos interactivos detectados: ${totalElements}
1042
+ - Pantallas mapeadas: ${screens.filter(s => !s.isErrorState).map(s => s.name).join(', ')}
1043
+ - Complejidad: ${totalElements > 15 ? 'Alta' : totalElements > 8 ? 'Media' : 'Baja'}
1044
+ `;
1045
+ },
1046
+ // ── Maestro element extractor ────────────────────────────────────────────
470
1047
  extractMaestroSelectors(node) {
471
1048
  const elements = [];
472
1049
  const INTERACTIVE_CLASSES = [
@@ -481,13 +1058,11 @@ ${elements.slice(0, 20).map((e) => {
481
1058
  const traverse = (current) => {
482
1059
  if (!current || typeof current !== 'object')
483
1060
  return;
484
- // maestro hierarchy JSON format: { attributes: {...}, children: [...] }
485
1061
  const attrs = current.attributes || {};
486
1062
  const resourceId = attrs['resource-id'] || '';
487
1063
  const text = attrs['text'] || attrs['accessibilityText'] || attrs['hintText'] || '';
488
1064
  const cls = attrs['class'] || '';
489
1065
  const clickable = attrs['clickable'] === 'true';
490
- // Only include app-specific elements (skip Android system UI)
491
1066
  const isAppElement = resourceId && !resourceId.startsWith('android:id/') && !resourceId.startsWith('com.android.');
492
1067
  const isInteractive = INTERACTIVE_CLASSES.includes(cls) || clickable;
493
1068
  if (isAppElement && isInteractive) {
@@ -497,14 +1072,11 @@ ${elements.slice(0, 20).map((e) => {
497
1072
  id: resourceId.includes('/') ? resourceId.split('/')[1] : resourceId,
498
1073
  });
499
1074
  }
500
- // Recurse into children
501
- const children = current.children || [];
502
- for (const child of children) {
1075
+ for (const child of (current.children || []))
503
1076
  traverse(child);
504
- }
505
1077
  };
506
1078
  traverse(node);
507
1079
  return elements.slice(0, 30);
508
- }
1080
+ },
509
1081
  };
510
1082
  //# sourceMappingURL=discovery.js.map