@validate.qa/runner 1.0.91 → 1.0.92

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 (3) hide show
  1. package/dist/cli.js +990 -148
  2. package/dist/cli.mjs +990 -148
  3. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -2043,7 +2043,8 @@ var init_project_key = __esm({
2043
2043
  "reviews",
2044
2044
  "admin",
2045
2045
  "login",
2046
- "admin-view"
2046
+ "admin-view",
2047
+ "mcp"
2047
2048
  ]);
2048
2049
  PROJECT_KEY_MIN_LENGTH = 2;
2049
2050
  PROJECT_KEY_MAX_LENGTH = 12;
@@ -3134,22 +3135,23 @@ function labelForTarget(target) {
3134
3135
  return nonEmpty2(target?.locatorBundle?.accessibilityId) ?? nonEmpty2(target?.locatorBundle?.text) ?? nonEmpty2(target?.locatorBundle?.contentDesc) ?? nonEmpty2(target?.primary);
3135
3136
  }
3136
3137
  function semanticTarget(label, platform3, base2) {
3137
- const primary = mobileTextXPath(label, platform3);
3138
+ const textXPath = mobileTextXPath(label, platform3);
3139
+ const primary = nonEmpty2(base2?.primary) ?? textXPath;
3138
3140
  return {
3139
3141
  primary,
3140
3142
  fallbacks: uniq([
3143
+ ...base2?.fallbacks ?? [],
3144
+ textXPath,
3141
3145
  `~${label}`,
3142
- label,
3143
- base2?.primary,
3144
- ...base2?.fallbacks ?? []
3146
+ label
3145
3147
  ]).filter((value) => value !== primary),
3146
3148
  screenName: base2?.screenName ?? "HealedAssertion",
3147
3149
  locatorBundle: {
3148
- accessibilityId: label,
3149
- xpath: primary,
3150
- className: "",
3151
- text: label,
3152
- contentDesc: label,
3150
+ accessibilityId: nonEmpty2(base2?.locatorBundle?.accessibilityId) ?? label,
3151
+ xpath: nonEmpty2(base2?.locatorBundle?.xpath) ?? textXPath,
3152
+ className: base2?.locatorBundle?.className ?? "",
3153
+ text: nonEmpty2(base2?.locatorBundle?.text) ?? label,
3154
+ contentDesc: nonEmpty2(base2?.locatorBundle?.contentDesc) ?? label,
3153
3155
  ...base2?.locatorBundle?.resourceId ? { resourceId: base2.locatorBundle.resourceId } : {}
3154
3156
  }
3155
3157
  };
@@ -3327,6 +3329,26 @@ var init_mobile_step_healer = __esm({
3327
3329
  });
3328
3330
 
3329
3331
  // ../shared/dist/mobile-cross-platform.js
3332
+ function androidActivityPackageOf(owner) {
3333
+ const lastDot = owner.lastIndexOf(".");
3334
+ if (lastDot <= 0)
3335
+ return null;
3336
+ return /^[A-Z]/.test(owner.slice(lastDot + 1)) ? owner.slice(0, lastDot) : null;
3337
+ }
3338
+ function mobileScreenOwnerBelongsToApp(owner, targetAppId) {
3339
+ const ownerId = owner.trim();
3340
+ const appId = targetAppId.trim();
3341
+ if (!ownerId || !appId)
3342
+ return false;
3343
+ if (ownerId === appId)
3344
+ return true;
3345
+ if (ownerId.startsWith(`${appId}.`))
3346
+ return true;
3347
+ const activityPackage = androidActivityPackageOf(ownerId);
3348
+ if (activityPackage && appId.startsWith(`${activityPackage}.`))
3349
+ return true;
3350
+ return false;
3351
+ }
3330
3352
  function isMobilePlatform(value) {
3331
3353
  return value === "IOS" || value === "ANDROID";
3332
3354
  }
@@ -6579,6 +6601,7 @@ __export(dist_exports, {
6579
6601
  mobileCredentialPlaceholder: () => mobileCredentialPlaceholder,
6580
6602
  mobileLocatorBundleHasIdentity: () => mobileLocatorBundleHasIdentity,
6581
6603
  mobilePlatformFromMedium: () => mobilePlatformFromMedium,
6604
+ mobileScreenOwnerBelongsToApp: () => mobileScreenOwnerBelongsToApp,
6582
6605
  mobileWanderTraceEnabled: () => mobileWanderTraceEnabled,
6583
6606
  normalizeControlName: () => normalizeControlName,
6584
6607
  normalizeTtsModel: () => normalizeTtsModel,
@@ -8588,7 +8611,7 @@ var require_credential_tools = __commonJS({
8588
8611
  type: "function",
8589
8612
  function: {
8590
8613
  name: "set_credential",
8591
- description: 'Persist a NEW value for a stored credential after a test has successfully rotated it (e.g. "change password" flow). Call this AFTER you have verified the change succeeded (e.g. the new password actually works for login, or the success toast is visible). The runner updates the project test variable, fires a CREDENTIAL_UPDATED notification, and the new value is used by all subsequent tests. Never call this on a negative test (one that verifies wrong-credential is rejected) and never call it speculatively before submit+verify. The new value you supply MUST be the value you typed into the page \u2014 the runner does not re-read it from the DOM. Only call for keys already present in the Test Credentials section.',
8614
+ description: 'Persist a NEW value for a stored credential after a test has successfully rotated it. REQUIRED after any successful password change OR forgot-password/reset of the STORED test user (the account whose email is TEST_USER_EMAIL) so Test Data stays in sync and later tests do not fail with stale credentials. Also use after in-session "change password" from settings. Call this AFTER you have verified the change succeeded (success toast, re-login with the new value, or confirmed post-reset state). The runner updates the project test variable, fires a CREDENTIAL_UPDATED notification, and the new value is used by all subsequent tests. Never call this on a negative test (one that verifies wrong-credential is rejected) and never call it speculatively before submit+verify. The new value you supply MUST be the value you typed into the page \u2014 the runner does not re-read it from the DOM. Only call for keys already present in the Test Credentials section.',
8592
8615
  parameters: {
8593
8616
  type: "object",
8594
8617
  properties: {
@@ -8602,7 +8625,7 @@ var require_credential_tools = __commonJS({
8602
8625
  },
8603
8626
  reason: {
8604
8627
  type: "string",
8605
- description: 'Short human-readable explanation of why the credential changed (e.g. "User changed password from settings page"). Surfaced in the notification.'
8628
+ description: 'Short human-readable explanation of why the credential changed (e.g. "User changed password from settings page" or "Password reset completed for stored test user"). Surfaced in the notification.'
8606
8629
  }
8607
8630
  },
8608
8631
  required: ["credentialKey", "newValue"]
@@ -8664,12 +8687,13 @@ SECURITY RULES:
8664
8687
  - NEVER include credential values in \`capture_page\` observations, \`record_journey\` steps, \`record_transition\` triggerLabel, or any summary text. (You can't \u2014 they're not in your context \u2014 but do not invent placeholder values either; describe the action as "Fill email with test credentials".)
8665
8688
  - Registration flows that need a UNIQUE email (e.g. \`testuser-\${Date.now()}@example.com\`) should still use \`browser_type\` with a synthetic value \u2014 \`fill_credential\` is only for stored login credentials.
8666
8689
  ${opts.canRotate ? `
8667
- CREDENTIAL ROTATION (rare \u2014 read this carefully):
8668
- - The ONLY time to call \`set_credential\` is when the test:
8669
- (1) logs in as the STORED test user (the one whose credential is in the list above \u2014 e.g. logged in via \`fill_credential\` with TEST_USER_EMAIL / TEST_USER_PASSWORD), AND
8670
- (2) successfully changes THAT SAME user's credential (password change from their settings page, admin resetting their own token, etc.), AND
8671
- (3) you have proof the change took effect (success toast visible, re-login with the new value works, etc.).
8672
- - DO NOT call \`set_credential\` if the test registered a fresh user (e.g. \`testuser-\${Date.now()}@example.com\`) and changed THAT user's password \u2014 the fresh user is throwaway and not tracked anywhere. The stored credential is unchanged in that case.
8690
+ CREDENTIAL ROTATION (required when the STORED user's secret changes \u2014 read carefully):
8691
+ - You MUST call \`set_credential\` when the test successfully changes a secret belonging to the STORED test user (the account whose keys are listed above \u2014 typically TEST_USER_EMAIL / TEST_USER_PASSWORD). Covered flows:
8692
+ (1) **In-session change password** \u2014 log in as the stored user, open settings \u2192 Change Password, submit a new password, verify success; OR
8693
+ (2) **Forgot-password / password-reset of the stored user** \u2014 request reset for the stored email (fill_credential with TEST_USER_EMAIL on the forgot-password form), complete the emailed link/code, set a NEW password on the reset form, and verify success. You do NOT need to log in with the old password first \u2014 a successful reset of the stored account still MUST write the new password back.
8694
+ - After either flow succeeds, call \`set_credential\` with credentialKey \`TEST_USER_PASSWORD\` (or the matching stored password key) and newValue = the new password you typed. This updates the Test Data page so every later test uses the correct credentials.
8695
+ - Proof required before calling: success toast / confirmed reset state / re-login with the new value works.
8696
+ - DO NOT call \`set_credential\` if the test registered a fresh throwaway user (e.g. \`testuser-\${Date.now()}@example.com\` or a provision_identity inbox used only for a one-off signup) and changed THAT user's password \u2014 the stored credential is untouched in that case.
8673
8697
  - DO NOT call \`set_credential\` on a negative test (one that verifies a bad/mismatched password is rejected, or a permission-denied case).
8674
8698
  - DO NOT call it before submit + verify \u2014 a partial failure would corrupt the stored credential.
8675
8699
  - Call it AT MOST ONCE per test, AFTER verification. The \`newValue\` is the value you just typed into the new-password / new-token field; the runner persists it server-side and never echoes it back.
@@ -75744,7 +75768,7 @@ Rules:
75744
75768
  - Register ONCE per run. If signup says the account ALREADY exists, log in with that email + the \`${opts.passwordKey}\` password instead of registering again.
75745
75769
  - Only call the verification tools AFTER submitting the signup form; pass the app as \`senderMatch\` (the inbox is shared).`;
75746
75770
  }
75747
- function buildSystemPrompt(mode, platform3, enableRecordJourney, maxIterations, appBrief, targetAppId, existingScreens, incremental) {
75771
+ function buildSystemPrompt(mode, platform3, enableRecordJourney, maxIterations, appBrief, targetAppId, existingScreens, incremental, knowledgeContext) {
75748
75772
  const platformLabel = platform3 === "IOS" ? "iOS" : "Android";
75749
75773
  const targetLine = targetAppId ? ` Target app package/bundle: ${targetAppId}.` : "";
75750
75774
  const surveyBody = `You are a mobile QA exploration agent driving a real ${platformLabel} app on a connected device. Your goal: MAP every reachable screen so downstream agents know what to test. You are NOT testing \u2014 you are building a complete screen map.
@@ -75789,12 +75813,18 @@ Max iterations: ${maxIterations}. You will be warned near the end.`;
75789
75813
  ## Application Brief
75790
75814
  ${appBrief}
75791
75815
  Use this to prioritize which screens and flows to cover.` : "";
75816
+ const facts = knowledgeContext?.trim();
75817
+ const knowledgeBlock = facts ? `
75818
+
75819
+ ## Known Facts (project documents \u2014 optional)
75820
+ ${facts.slice(0, 4e3)}
75821
+ Prioritize exploring surfaces related to these facts when visible. If absent, explore solely from live UI. Never invent screens from facts alone.` : "";
75792
75822
  const existingScreensBlock = mode === "survey" && incremental && existingScreens && existingScreens.length > 0 ? `
75793
75823
 
75794
75824
  ## ALREADY DISCOVERED SCREENS (skip these; find new)
75795
75825
  These screens were mapped in a previous survey. Do NOT re-map them \u2014 use your budget to find NEW screens and flows not listed here. If you land on one of these, move on to something new.
75796
75826
  ${existingScreens.slice(0, 100).map((s) => `- ${s.screenId}${s.name ? ` "${s.name}"` : ""}${s.screenType ? ` [${s.screenType}]` : ""}`).join("\n")}` : "";
75797
- return `${mode === "survey" ? surveyBody : deepBody}${briefBlock}${existingScreensBlock}`;
75827
+ return `${mode === "survey" ? surveyBody : deepBody}${briefBlock}${knowledgeBlock}${existingScreensBlock}`;
75798
75828
  }
75799
75829
  function buildKickoffMessage(mode) {
75800
75830
  return mode === "survey" ? "Start with mobile_snapshot on the launch screen. Driver observations are saved automatically; use capture_screen only to give important stable destinations useful names. Map the entire app: open every tab, menu, and one row per list. Record transitions as you go." : "Start by calling mobile_snapshot on the launch screen and capture_screen it. Then use the features: fill fields, submit forms, open menus, and observe outcomes. Capture each distinct screen and record journeys after meaningful flows.";
@@ -76194,7 +76224,7 @@ ${existingScreens.slice(0, 100).map((s) => `- ${s.screenId}${s.name ? ` "${s.nam
76194
76224
  if (authTracker.required) {
76195
76225
  log2(`Authenticated survey completion gate enabled (${ctx.target?.resetPolicy ?? "AUTO"}): the run must reach a structurally observed product surface before planning.`);
76196
76226
  }
76197
- const systemPrompt = buildSystemPrompt(mode, platform3, enableRecordJourney, maxIterations, ctx.appBrief, targetAppId, existingScreens, ctx.incremental) + (!registerRequested ? buildMobileCredentialPromptBlock(credentialSecrets) : "") + (inboxEnabled && inboxState ? buildMobileInboxPromptBlock({
76227
+ const systemPrompt = buildSystemPrompt(mode, platform3, enableRecordJourney, maxIterations, ctx.appBrief, targetAppId, existingScreens, ctx.incremental, ctx.knowledgeContext) + (!registerRequested ? buildMobileCredentialPromptBlock(credentialSecrets) : "") + (inboxEnabled && inboxState ? buildMobileInboxPromptBlock({
76198
76228
  email: inboxState.email,
76199
76229
  passwordKey: inboxState.passwordKey ?? "TEST_USER_PASSWORD",
76200
76230
  context: mode
@@ -80362,8 +80392,10 @@ var require_scenario_taxonomy = __commonJS({
80362
80392
  exports.inferScenarioKind = inferScenarioKind;
80363
80393
  exports.inferScenarioKinds = inferScenarioKinds;
80364
80394
  exports.isStrongOracleKind = isStrongOracleKind;
80395
+ exports.kindRequiresStateDelta = kindRequiresStateDelta;
80365
80396
  exports.formatRequiredScenarioKindsPrompt = formatRequiredScenarioKindsPrompt;
80366
80397
  exports.formatCoverageGapLog = formatCoverageGapLog;
80398
+ exports.synthesizeScenariosForMissingKinds = synthesizeScenariosForMissingKinds;
80367
80399
  exports.ALL_SCENARIO_KINDS = [
80368
80400
  "smoke_nav",
80369
80401
  "happy_submit",
@@ -80374,7 +80406,9 @@ var require_scenario_taxonomy = __commonJS({
80374
80406
  "auth_session",
80375
80407
  "navigation_integrity",
80376
80408
  "permission_system",
80377
- "double_submit"
80409
+ "double_submit",
80410
+ "search_filter",
80411
+ "list_refresh"
80378
80412
  ];
80379
80413
  var DELETE_RE = /\b(delete|remove|archive|trash)\b/i;
80380
80414
  var EMAIL_RE = /\b(e-?mail|email address)\b/i;
@@ -80386,7 +80420,12 @@ var require_scenario_taxonomy = __commonJS({
80386
80420
  var BADGE_LABEL_RE = /\b(badge|count|open invoices|unread|notifications?)\b/i;
80387
80421
  var PERMISSION_RE = /\b(camera|microphone|location|photos?|permission|allow access|not now)\b/i;
80388
80422
  var SETTINGS_RE = /\b(settings|preferences|profile|account)\b/i;
80389
- var TAB_RE = /\b(tab|home|catalog|forms|edges|inbox|feed|dashboard)\b/i;
80423
+ var TAB_RE = /\b(tab|home|inbox|feed|dashboard)\b/i;
80424
+ var SEARCH_RE = /\b(search|filter|find|query)\b/i;
80425
+ var EMPTY_STATE_RE = /\b(no items|nothing here|empty|get started|add first|create first|no results)\b/i;
80426
+ var EMPTY_CTA_RE = /\b(add first|create first|get started|add item|new item)\b/i;
80427
+ var REFRESH_RE = /\b(pull to refresh|pull-to-refresh|refresh|updated:)\b/i;
80428
+ var FAVORITE_RE = /\b(favorite|favourite|heart|bookmark|star|like)\b/i;
80390
80429
  function elementText(el) {
80391
80430
  return [
80392
80431
  el.label ?? "",
@@ -80424,6 +80463,10 @@ var require_scenario_taxonomy = __commonJS({
80424
80463
  let hasPrimarySubmit = false;
80425
80464
  let hasTabOrDrawerNav = false;
80426
80465
  let hasPermissionCopy = false;
80466
+ let hasSearchField = false;
80467
+ let hasEmptyStateCta = false;
80468
+ let hasPullToRefresh = false;
80469
+ let hasFavoriteToggle = false;
80427
80470
  for (const state2 of screens) {
80428
80471
  const labels = state2.elements.map(elementText);
80429
80472
  const blob = [state2.screenName ?? "", state2.screenType ?? "", ...state2.observations ?? [], ...labels].join(" ");
@@ -80455,6 +80498,17 @@ var require_scenario_taxonomy = __commonJS({
80455
80498
  }
80456
80499
  if (PERMISSION_RE.test(blob) || state2.screenType === "PERMISSION")
80457
80500
  hasPermissionCopy = true;
80501
+ if (SEARCH_RE.test(blob) || state2.elements.some((el) => isEditable(el) && SEARCH_RE.test(elementText(el))) || state2.elements.some((el) => el.role === "searchbox" || /SearchView|SearchBar/i.test(el.role ?? ""))) {
80502
+ hasSearchField = true;
80503
+ }
80504
+ if (EMPTY_STATE_RE.test(blob) && (EMPTY_CTA_RE.test(blob) || labels.some((t) => EMPTY_CTA_RE.test(t)))) {
80505
+ hasEmptyStateCta = true;
80506
+ }
80507
+ if (REFRESH_RE.test(blob))
80508
+ hasPullToRefresh = true;
80509
+ if (FAVORITE_RE.test(blob) || state2.elements.some((el) => FAVORITE_RE.test(elementText(el)) && el.actionable !== false)) {
80510
+ hasFavoriteToggle = true;
80511
+ }
80458
80512
  }
80459
80513
  return {
80460
80514
  hasListWithRowActions,
@@ -80466,7 +80520,11 @@ var require_scenario_taxonomy = __commonJS({
80466
80520
  hasDestructiveConfirm,
80467
80521
  hasPrimarySubmit,
80468
80522
  hasTabOrDrawerNav,
80469
- hasPermissionCopy
80523
+ hasPermissionCopy,
80524
+ hasSearchField,
80525
+ hasEmptyStateCta,
80526
+ hasPullToRefresh,
80527
+ hasFavoriteToggle
80470
80528
  };
80471
80529
  }
80472
80530
  function requiredScenarioKinds(signals) {
@@ -80483,13 +80541,13 @@ var require_scenario_taxonomy = __commonJS({
80483
80541
  if (signals.hasNumericBadge) {
80484
80542
  kinds.add("count_delta");
80485
80543
  }
80486
- if (signals.hasSettingsToggles) {
80544
+ if (signals.hasSettingsToggles || signals.hasFavoriteToggle) {
80487
80545
  kinds.add("persistence_roundtrip");
80488
80546
  }
80489
80547
  if (signals.hasSignOut) {
80490
80548
  kinds.add("auth_session");
80491
80549
  }
80492
- if (signals.hasTabOrDrawerNav) {
80550
+ if (signals.hasTabOrDrawerNav || signals.hasEmptyStateCta) {
80493
80551
  kinds.add("navigation_integrity");
80494
80552
  }
80495
80553
  if (signals.hasPermissionCopy) {
@@ -80498,6 +80556,12 @@ var require_scenario_taxonomy = __commonJS({
80498
80556
  if (signals.hasPrimarySubmit && signals.hasFormFields) {
80499
80557
  kinds.add("double_submit");
80500
80558
  }
80559
+ if (signals.hasSearchField) {
80560
+ kinds.add("search_filter");
80561
+ }
80562
+ if (signals.hasPullToRefresh) {
80563
+ kinds.add("list_refresh");
80564
+ }
80501
80565
  return exports.ALL_SCENARIO_KINDS.filter((k) => kinds.has(k));
80502
80566
  }
80503
80567
  function coverageGaps(signals, plannedKinds) {
@@ -80512,6 +80576,12 @@ var require_scenario_taxonomy = __commonJS({
80512
80576
  if (/\b(delete|remove|wrong row|entity|archive)\b/.test(text) && /\b(list|row|item|record)\b/.test(text)) {
80513
80577
  return "crud_identity";
80514
80578
  }
80579
+ if (/\b(pull.?to.?refresh|refresh list|list refresh|after refresh)\b/.test(text)) {
80580
+ return "list_refresh";
80581
+ }
80582
+ if (/\b(search|filter results|query)\b/.test(text)) {
80583
+ return "search_filter";
80584
+ }
80515
80585
  if (/\b(badge|count|unread|open invoices|\+\d|increment|decrement)\b/.test(text)) {
80516
80586
  return "count_delta";
80517
80587
  }
@@ -80521,7 +80591,7 @@ var require_scenario_taxonomy = __commonJS({
80521
80591
  if (/\b(sign\s*out|log\s*out|session|sign\s*in|remember me|auth)\b/.test(text) || scenario.type === "HAPPY_PATH" && /\b(login|sign in)\b/.test(text)) {
80522
80592
  return "auth_session";
80523
80593
  }
80524
- if (/\b(tab|navigate|navigation|back|deep link|empty.?state)\b/.test(text)) {
80594
+ if (/\b(tab|navigate|navigation|back|deep link|empty.?state|empty cta|dead route)\b/.test(text)) {
80525
80595
  return "navigation_integrity";
80526
80596
  }
80527
80597
  if (/\b(permission|camera|microphone|location|allow)\b/.test(text)) {
@@ -80544,6 +80614,9 @@ var require_scenario_taxonomy = __commonJS({
80544
80614
  function isStrongOracleKind(kind) {
80545
80615
  return kind !== "smoke_nav" && kind !== "navigation_integrity";
80546
80616
  }
80617
+ function kindRequiresStateDelta(kind) {
80618
+ return kind === "crud_identity" || kind === "count_delta" || kind === "persistence_roundtrip" || kind === "double_submit" || kind === "list_refresh" || kind === "search_filter";
80619
+ }
80547
80620
  function formatRequiredScenarioKindsPrompt(signals) {
80548
80621
  const required = requiredScenarioKinds(signals);
80549
80622
  if (required.length === 0)
@@ -80570,17 +80643,280 @@ var require_scenario_taxonomy = __commonJS({
80570
80643
  return "- permission_system: permission prompt or settings path behaves honestly (allow/deny/settings)";
80571
80644
  case "double_submit":
80572
80645
  return "- double_submit: single user intent must not double-create (assert count +1 not +2, or single confirmation)";
80646
+ case "search_filter":
80647
+ return "- search_filter: type a distinctive query observed on-device, assert the result set filters (row count/labels change); empty query restores or shows empty-state honestly";
80648
+ case "list_refresh":
80649
+ return "- list_refresh: capture list ids/count, pull-to-refresh or tap Refresh, assert list still coherent (not permanently wiped) OR honest empty + recoverable";
80573
80650
  default:
80574
80651
  return `- ${kind}`;
80575
80652
  }
80576
80653
  });
80577
- return "## Required scenario kinds (from observed UI \u2014 fill each or explain impossibility in reasoning)\nThese kinds are derived ONLY from controls/screens the explorer saw. Plan at least one scenario per kind when evidence supports it.\n" + lines.join("\n");
80654
+ return "## Required scenario kinds (from observed UI \u2014 fill each or explain impossibility in reasoning)\nThese kinds are derived ONLY from controls/screens the explorer saw. Plan at least one scenario per kind when evidence supports it.\nCap pure smoke_nav to ONE scenario per feature. Prefer strong kinds when signals require them.\nAuth credential validation (empty/wrong/malformed login) belongs ONLY on Authentication/Sign-in features \u2014 elsewhere login is setup, not a scenario.\nIf a scenario name claims delete/count/persist/refresh, expectedOutcomes MUST require before/after state proof (capture + delta), not tab chrome.\n" + lines.join("\n");
80578
80655
  }
80579
80656
  function formatCoverageGapLog(gaps) {
80580
80657
  if (gaps.length === 0)
80581
80658
  return "Scenario taxonomy: all required kinds covered by plan";
80582
80659
  return `Scenario taxonomy coverage gaps (required but not planned): ${gaps.join(", ")}`;
80583
80660
  }
80661
+ function synthesizeScenariosForMissingKinds(input) {
80662
+ const feature = input.featureName.trim() || "Feature";
80663
+ const used = input.existingNames ?? /* @__PURE__ */ new Set();
80664
+ const maxNew = Math.max(1, input.maxNew ?? 6);
80665
+ const pages = input.targetPages.length > 0 ? input.targetPages : [input.entryRoute];
80666
+ const entry = input.entryRoute || pages[0] || "";
80667
+ const out = [];
80668
+ for (const kind of input.gaps) {
80669
+ if (out.length >= maxNew)
80670
+ break;
80671
+ if (kind === "smoke_nav")
80672
+ continue;
80673
+ const draft = scenarioStubForKind(kind, feature, entry, pages);
80674
+ if (!draft)
80675
+ continue;
80676
+ let name = draft.name;
80677
+ let n = 2;
80678
+ while (used.has(name.toLowerCase())) {
80679
+ name = `${draft.name} (${n})`;
80680
+ n += 1;
80681
+ if (n > 20)
80682
+ break;
80683
+ }
80684
+ if (used.has(name.toLowerCase()))
80685
+ continue;
80686
+ used.add(name.toLowerCase());
80687
+ out.push({ ...draft, name });
80688
+ }
80689
+ return out;
80690
+ }
80691
+ function scenarioStubForKind(kind, feature, entryRoute, targetPages) {
80692
+ const base2 = {
80693
+ featureGroup: feature,
80694
+ entryRoute,
80695
+ startFromLanding: true,
80696
+ targetPages: [...targetPages],
80697
+ evidence: {
80698
+ observedLocators: [],
80699
+ observedTransitions: []
80700
+ },
80701
+ prerequisites: [],
80702
+ isAISuggested: false
80703
+ };
80704
+ const step = (action, target) => ({ action, target });
80705
+ const outcome = (type, description) => ({ type, description, reliability: "medium" });
80706
+ switch (kind) {
80707
+ case "crud_identity":
80708
+ return {
80709
+ ...base2,
80710
+ name: `${feature} - Delete entity proves identity removed`,
80711
+ type: "HAPPY_PATH",
80712
+ priority: 1,
80713
+ variant: "happy",
80714
+ goal: "Capture list/entity identity, delete or remove that entity, prove the identity set changed (not merely that the list screen is still visible)",
80715
+ steps: [
80716
+ step("Launch the app and sign in if the product requires a session", entryRoute),
80717
+ step(`Navigate to the ${feature} list or collection screen`),
80718
+ step("Capture visible row/entity identifiers into a state bag before mutation"),
80719
+ step("Perform delete/remove/archive on one specific observed entity"),
80720
+ step("Assert state delta: that entity identity is gone or the wrong neighbor was not removed")
80721
+ ],
80722
+ expectedOutcomes: [
80723
+ outcome("element-hidden", "Target entity identity no longer present in the list"),
80724
+ outcome("element-visible", "List or collection still reachable after mutation")
80725
+ ]
80726
+ };
80727
+ case "count_delta":
80728
+ return {
80729
+ ...base2,
80730
+ name: `${feature} - Count or badge changes after action`,
80731
+ type: "HAPPY_PATH",
80732
+ priority: 1,
80733
+ variant: "happy",
80734
+ goal: "Capture a numeric badge or count, perform a product action, assert the number changed as expected",
80735
+ steps: [
80736
+ step("Launch the app and sign in if needed", entryRoute),
80737
+ step(`Navigate to the ${feature} surface showing a count or badge`),
80738
+ step("Capture the numeric count/badge into a state bag"),
80739
+ step("Perform an action that should change the count (add, remove, mark read, complete)"),
80740
+ step("Assert state delta: count increased or decreased as expected")
80741
+ ],
80742
+ expectedOutcomes: [
80743
+ outcome("element-visible", "Count or badge reflects the post-action value")
80744
+ ]
80745
+ };
80746
+ case "persistence_roundtrip":
80747
+ return {
80748
+ ...base2,
80749
+ name: `${feature} - Change persists after leave and return`,
80750
+ type: "HAPPY_PATH",
80751
+ priority: 1,
80752
+ variant: "happy",
80753
+ goal: "Change a setting, toggle, or favorite; leave the screen; return; prove the value persisted or honestly reset",
80754
+ steps: [
80755
+ step("Launch the app and sign in if needed", entryRoute),
80756
+ step(`Navigate to the ${feature} settings or toggle surface`),
80757
+ step("Capture current field/toggle/favorite state"),
80758
+ step("Change a durable control (toggle, text field, favorite) and save if required"),
80759
+ step("Navigate away to another tab or parent screen"),
80760
+ step("Return to the same surface"),
80761
+ step("Assert state delta: value persisted (or product honestly shows it did not)")
80762
+ ],
80763
+ expectedOutcomes: [
80764
+ outcome("element-visible", "Changed value is still reflected after round-trip")
80765
+ ]
80766
+ };
80767
+ case "negative_validation":
80768
+ return {
80769
+ ...base2,
80770
+ name: `${feature} - Invalid or empty input is rejected`,
80771
+ type: "EDGE_CASE",
80772
+ priority: 2,
80773
+ variant: "validation",
80774
+ goal: "Submit empty or malformed input and assert error feedback or blocked submit \u2014 never invent success",
80775
+ steps: [
80776
+ step("Launch the app and sign in if needed", entryRoute),
80777
+ step(`Navigate to the ${feature} form`),
80778
+ step("Leave required fields empty or type structurally invalid input (e.g. email-like field without a domain)"),
80779
+ step("Attempt submit"),
80780
+ step("Assert validation error is visible OR submit remains blocked on the form")
80781
+ ],
80782
+ expectedOutcomes: [
80783
+ outcome("element-visible", "Validation error or blocked submit state is visible")
80784
+ ]
80785
+ };
80786
+ case "happy_submit":
80787
+ return {
80788
+ ...base2,
80789
+ name: `${feature} - Happy path durable submit`,
80790
+ type: "HAPPY_PATH",
80791
+ priority: 1,
80792
+ variant: "happy",
80793
+ goal: "Complete the primary form/action and assert a durable product result (new row, saved state, confirmation that outlives a toast)",
80794
+ steps: [
80795
+ step("Launch the app and sign in if needed", entryRoute),
80796
+ step(`Navigate to the ${feature} form or primary action`),
80797
+ step("Fill required fields with run-scoped values"),
80798
+ step("Submit or save"),
80799
+ step("Assert durable outcome (new row, success state, or persisted values)")
80800
+ ],
80801
+ expectedOutcomes: [
80802
+ outcome("element-visible", "Durable success result is visible")
80803
+ ]
80804
+ };
80805
+ case "auth_session":
80806
+ return {
80807
+ ...base2,
80808
+ name: `${feature} - Session proof after sign-in or sign-out`,
80809
+ type: "HAPPY_PATH",
80810
+ priority: 1,
80811
+ variant: "happy",
80812
+ goal: "Prove authenticated session (profile/sign-out) or that sign-out leaves only logged-out chrome",
80813
+ steps: [
80814
+ step("Launch the app", entryRoute),
80815
+ step("Sign in with test credentials if not already authenticated"),
80816
+ step("Open account/profile or use a signed-in-only control"),
80817
+ step("Assert Sign out / profile identity is available, or complete sign-out and assert login chrome")
80818
+ ],
80819
+ expectedOutcomes: [
80820
+ outcome("element-visible", "Signed-in or signed-out durable chrome matches the action")
80821
+ ]
80822
+ };
80823
+ case "navigation_integrity":
80824
+ return {
80825
+ ...base2,
80826
+ name: `${feature} - Navigation reaches intended destination`,
80827
+ type: "USER_JOURNEY",
80828
+ priority: 2,
80829
+ variant: "happy",
80830
+ goal: "Follow in-app navigation (tab, back, empty-state CTA, overflow) and assert the intended product destination \u2014 not hub chrome after wandering",
80831
+ steps: [
80832
+ step("Launch the app and sign in if needed", entryRoute),
80833
+ step(`Navigate into ${feature} via the observed entry path`),
80834
+ step("If an empty-state CTA is present, tap it and assert the destination form/error"),
80835
+ step("Use back/up if nested and assert the parent screen family")
80836
+ ],
80837
+ expectedOutcomes: [
80838
+ outcome("screen-visible", "Intended destination screen family is visible")
80839
+ ]
80840
+ };
80841
+ case "permission_system":
80842
+ return {
80843
+ ...base2,
80844
+ name: `${feature} - Permission prompt behaves honestly`,
80845
+ type: "EDGE_CASE",
80846
+ priority: 2,
80847
+ variant: "happy",
80848
+ goal: "Trigger permission flow and assert allow/deny/settings path is honest",
80849
+ steps: [
80850
+ step("Launch the app and sign in if needed", entryRoute),
80851
+ step(`Navigate to the ${feature} permission-related surface`),
80852
+ step("Trigger the permission request"),
80853
+ step("Assert system or in-app permission UI appears and deny/allow path is reachable")
80854
+ ],
80855
+ expectedOutcomes: [
80856
+ outcome("element-visible", "Permission or settings path is visible")
80857
+ ]
80858
+ };
80859
+ case "double_submit":
80860
+ return {
80861
+ ...base2,
80862
+ name: `${feature} - Single submit does not double-create`,
80863
+ type: "EDGE_CASE",
80864
+ priority: 2,
80865
+ variant: "bug",
80866
+ goal: "Submit once and assert count +1 (not +2) or a single confirmation",
80867
+ steps: [
80868
+ step("Launch the app and sign in if needed", entryRoute),
80869
+ step(`Navigate to the ${feature} submit flow`),
80870
+ step("Capture pre-submit count or confirmation state"),
80871
+ step("Tap primary submit only once"),
80872
+ step("Assert state delta: single creation (count +1 or one confirmation id)")
80873
+ ],
80874
+ expectedOutcomes: [
80875
+ outcome("element-visible", "Exactly one durable result from a single submit")
80876
+ ]
80877
+ };
80878
+ case "search_filter":
80879
+ return {
80880
+ ...base2,
80881
+ name: `${feature} - Search filters the visible result set`,
80882
+ type: "HAPPY_PATH",
80883
+ priority: 1,
80884
+ variant: "happy",
80885
+ goal: "Type a distinctive query and assert the result set filters; clear/empty query restores or shows honest empty state",
80886
+ steps: [
80887
+ step("Launch the app and sign in if needed", entryRoute),
80888
+ step(`Navigate to the ${feature} search/filter surface`),
80889
+ step("Capture the unfiltered list identifiers"),
80890
+ step("Type a distinctive query into the search field"),
80891
+ step("Assert state delta: visible results changed (filtered or empty-state)")
80892
+ ],
80893
+ expectedOutcomes: [
80894
+ outcome("element-visible", "Filtered results or empty-state copy matches the query")
80895
+ ]
80896
+ };
80897
+ case "list_refresh":
80898
+ return {
80899
+ ...base2,
80900
+ name: `${feature} - Pull to refresh keeps list coherent`,
80901
+ type: "HAPPY_PATH",
80902
+ priority: 1,
80903
+ variant: "happy",
80904
+ goal: "Capture list state, pull-to-refresh or tap Refresh, assert list remains coherent (not permanently wiped) or honest empty",
80905
+ steps: [
80906
+ step("Launch the app and sign in if needed", entryRoute),
80907
+ step(`Navigate to the ${feature} list with refresh`),
80908
+ step("Capture list identifiers before refresh"),
80909
+ step("Pull to refresh or activate Refresh"),
80910
+ step("Assert state delta: list still has coherent content or an honest empty state")
80911
+ ],
80912
+ expectedOutcomes: [
80913
+ outcome("element-visible", "List after refresh is coherent (not permanently destroyed without recovery)")
80914
+ ]
80915
+ };
80916
+ default:
80917
+ return null;
80918
+ }
80919
+ }
80584
80920
  }
80585
80921
  });
80586
80922
 
@@ -80669,10 +81005,15 @@ var require_mobile_discovery_prompts = __commonJS({
80669
81005
  var mobile_observation_js_1 = require_mobile_observation();
80670
81006
  var scenario_taxonomy_js_1 = require_scenario_taxonomy();
80671
81007
  var coverage_map_js_1 = require_coverage_map();
81008
+ var shared_1 = (init_dist(), __toCommonJS(dist_exports));
80672
81009
  function isTargetAppScreenId(screenId, appId) {
80673
81010
  if (!appId)
80674
81011
  return true;
80675
- return screenId === appId || screenId.startsWith(`${appId}#`) || screenId.startsWith(`${appId}.`);
81012
+ const hashIndex = screenId.indexOf("#");
81013
+ const owner = (hashIndex >= 0 ? screenId.slice(0, hashIndex) : screenId).trim();
81014
+ if (!owner)
81015
+ return false;
81016
+ return (0, shared_1.mobileScreenOwnerBelongsToApp)(owner, appId);
80676
81017
  }
80677
81018
  function targetAppScreens(graph, appId) {
80678
81019
  return [...graph.screens.values()].filter((state2) => isTargetAppScreenId(state2.screenId, appId));
@@ -80814,12 +81155,19 @@ Return ONLY one valid JSON object matching the schema below. Do NOT include <thi
80814
81155
  Citing observed labels / accessibility-ids in \`expectedOutcomes\` (per Rule 12) is fine \u2014 that's asserting on stable product signals, not implementation specifics.
80815
81156
 
80816
81157
  ## Coverage Strategy
80817
- - For every form: at least 1 HAPPY_PATH (submit valid data AND verify durable result per rule 12) + 1 EDGE_CASE (empty/invalid submission)
80818
- - For auth flows: sign-in happy path (verify the target screen AND a concrete signed-in/session signal per rule 13) + validation (wrong password, empty fields)
81158
+ - For every form: at least 1 HAPPY_PATH (submit valid data AND verify durable result per rule 12) + 1 EDGE_CASE (empty/invalid submission). When email-like fields exist, include ONE weak/malformed value case (structurally invalid input such as missing domain) and assert reject OR honest accept \u2014 never invent error copy not seen in evidence.
81159
+ - For auth flows: sign-in happy path (verify the target screen AND a concrete signed-in/session signal per rule 13) + validation (wrong password, empty fields) **only when this deep feature is Authentication / Sign-in / Onboarding / Account**. For every other feature, credentials are setup steps inside product scenarios \u2014 do NOT emit standalone "Sign In - Empty Credentials" / "Wrong Password" scenarios under Home, Inbox, Settings, etc.
80819
81160
  - For credential sign-in flows: only plan credential scenarios when evidence shows the credential path itself \u2014 an email/username field, a password field, and a native Sign In/Login/Submit control on the target screen, or an Explorer-Recorded Journey that typed those fields and submitted them. Do NOT treat Google/Apple/Facebook/SSO buttons, magic-link entry, logout menus, profile menus, or already-signed-in screens as evidence for credential sign-in. If the explorer only observed signed-in menu/logout/session surfaces, plan session/logout scenarios only; surface missing credential coverage as a gap instead of inventing credential sign-in variants.
80820
- - For CRUD: each scenario MUST own the entity it operates on. Read/search/update/delete/cancel-on-existing/view-existing scenarios MUST include a create step earlier in the same scenario (or declare an immutable seed fixture by name). Never assume a record from prior runs or sibling tests exists. When create/delete are tightly coupled, bundle into a single USER_JOURNEY: create \u2192 verify \u2192 delete \u2192 verify removal.
81161
+ - For CRUD: each scenario MUST own the entity it operates on. Read/search/update/delete/cancel-on-existing/view-existing scenarios MUST include a create step earlier in the same scenario (or declare an immutable seed fixture by name). Never assume a record from prior runs or sibling tests exists. When create/delete are tightly coupled, bundle into a single USER_JOURNEY: create \u2192 verify \u2192 delete \u2192 verify removal. Delete scenarios MUST capture entity identity BEFORE delete and assert that identity is gone or the wrong neighbor remains (list chrome still visible is NOT enough).
81162
+ - For list counts / badges: plan before/after count or badge checks when those numbers were observed \u2014 not "Navigate up is visible".
81163
+ - For search/filter fields: plan a filter scenario with a distinctive query and assert the visible result set changes.
81164
+ - For pull-to-refresh / Refresh: capture list state, refresh, assert list remains coherent (not permanently wiped) or honest empty.
81165
+ - For empty-state CTAs ("Add first\u2026", "Create first\u2026"): tap the CTA and assert the DESTINATION product surface (form, detail, or honest error) \u2014 not hub tab chrome after wandering.
81166
+ - For settings/toggles/favorites: change value, leave screen (navigate away), return, assert value persisted or honestly reset.
80821
81167
  - For AI/async features (Generate, Analyze, Process, Import, Sync): happy path MUST complete the flow per rule 12 - never stop at "button tapped" or "sheet opened"
80822
81168
  - For navigation: multi-screen user journeys within the feature scope (do NOT drift into unrelated features)
81169
+ - **Smoke budget:** at most ONE pure smoke/navigation-only scenario per feature. Prefer required strong kinds when UI signals support them.
81170
+ - **Name = proof:** if the scenario name claims delete/count/persist/refresh/empty-CTA destination, expectedOutcomes and steps must prove that claim. Never name a test after a failure mode the steps do not exercise.
80823
81171
 
80824
81172
  ## Output JSON Schema
80825
81173
  {
@@ -81110,6 +81458,13 @@ Each entry is exactly one of:
81110
81458
  if (context.appBrief) {
81111
81459
  sections.push(`## Application Brief
81112
81460
  ${context.appBrief.slice(0, 500)}`);
81461
+ }
81462
+ const knownFacts = context.knowledgeContext?.trim();
81463
+ if (knownFacts) {
81464
+ sections.push(`## Known Facts
81465
+ ${knownFacts.slice(0, 8e3)}
81466
+
81467
+ These facts come from project documents / knowledge. Prefer scenarios that verify them when the explorer observed related UI. If a fact conflicts with live UI evidence, prefer live evidence. When this section is absent, rely only on explorer evidence.`);
81113
81468
  }
81114
81469
  const targetBits = [];
81115
81470
  if (context.platform)
@@ -81548,14 +81903,46 @@ ${constraints.join("\n")}`);
81548
81903
  }
81549
81904
  return normalized;
81550
81905
  }
81906
+ function buildMobileTaxonomyScenarios(input, gaps) {
81907
+ const orderedScreens = plannableTargetAppScreens(input.graph, input.appId).filter((state2) => state2.visited || state2.firstSeenIteration === 0).sort((a, b) => a.firstSeenIteration - b.firstSeenIteration);
81908
+ if (orderedScreens.length === 0)
81909
+ return [];
81910
+ const entryScreenId = orderedScreens[0].screenId;
81911
+ const targetPages = orderedScreens.slice(0, 8).map((s) => s.screenId);
81912
+ const featureName = input.featureName?.trim() || nonGenericScreenName(orderedScreens[0], input.appId) || inferMobileFeatureGroupName(orderedScreens.slice(0, 3), input.appId) || "App";
81913
+ const signals = (0, scenario_taxonomy_js_1.extractUiSignals)(input.graph, input.appId);
81914
+ const missing = gaps && gaps.length > 0 ? gaps : (0, scenario_taxonomy_js_1.requiredScenarioKinds)(signals).filter((k) => k !== "smoke_nav");
81915
+ if (missing.length === 0) {
81916
+ return (0, scenario_taxonomy_js_1.synthesizeScenariosForMissingKinds)({
81917
+ gaps: ["navigation_integrity", "happy_submit"],
81918
+ featureName,
81919
+ entryRoute: entryScreenId,
81920
+ targetPages,
81921
+ existingNames: new Set((input.existingTestNames ?? []).map((n) => n.toLowerCase())),
81922
+ maxNew: Math.min(3, Math.max(1, input.testBudget || 3))
81923
+ });
81924
+ }
81925
+ return (0, scenario_taxonomy_js_1.synthesizeScenariosForMissingKinds)({
81926
+ gaps: missing,
81927
+ featureName,
81928
+ entryRoute: entryScreenId,
81929
+ targetPages,
81930
+ existingNames: new Set((input.existingTestNames ?? []).map((n) => n.toLowerCase())),
81931
+ maxNew: Math.min(6, Math.max(2, input.testBudget || 6))
81932
+ });
81933
+ }
81551
81934
  function buildMobileFallbackScenarios(input) {
81552
81935
  if (input.mode === "survey")
81553
81936
  return [];
81554
- if (input.featureName?.trim())
81555
- return [];
81937
+ if (input.featureName?.trim()) {
81938
+ return buildMobileTaxonomyScenarios(input);
81939
+ }
81556
81940
  const orderedScreens = plannableTargetAppScreens(input.graph, input.appId).filter((state2) => state2.visited || state2.firstSeenIteration === 0).sort((a, b) => a.firstSeenIteration - b.firstSeenIteration);
81557
81941
  if (orderedScreens.length === 0)
81558
81942
  return [];
81943
+ const taxonomy = buildMobileTaxonomyScenarios(input);
81944
+ if (taxonomy.length > 0)
81945
+ return taxonomy;
81559
81946
  const entryScreenId = orderedScreens[0].screenId;
81560
81947
  const usedNames = new Set((input.existingTestNames ?? []).map((name) => name.toLowerCase()));
81561
81948
  const scenarios = [];
@@ -81848,6 +82235,7 @@ ${constraints.join("\n")}`);
81848
82235
  userPromptOverride: formatMobileEvidenceForPlanner(input.graph, {
81849
82236
  mode: input.mode,
81850
82237
  appBrief: input.appBrief,
82238
+ knowledgeContext: input.knowledgeContext,
81851
82239
  appId: input.appId,
81852
82240
  platform: input.platform,
81853
82241
  featureName: input.featureName,
@@ -81880,44 +82268,65 @@ ${constraints.join("\n")}`);
81880
82268
  if (guestWallFilter.dropped > 0) {
81881
82269
  mobileAdaptationLogs.push(`Dropped ${guestWallFilter.dropped} guest-wall scenario(s) \u2014 explore session was authenticated; re-exec would not see sign-in gates`);
81882
82270
  }
81883
- const plannedScenarios = guestWallFilter.scenarios;
82271
+ let plannedScenarios = guestWallFilter.scenarios;
81884
82272
  let taxonomyGapLogs = [];
81885
82273
  let taxonomyCoverageGaps = result.coverageGaps ?? [];
81886
- if (input.mode !== "survey" && plannedScenarios.length > 0) {
82274
+ if (input.mode !== "survey" && input.graph.screens.size > 0) {
81887
82275
  const signals = (0, scenario_taxonomy_js_1.extractUiSignals)(input.graph, input.appId);
81888
82276
  const plannedKinds = (0, scenario_taxonomy_js_1.inferScenarioKinds)(plannedScenarios);
81889
- const gaps = (0, scenario_taxonomy_js_1.coverageGaps)(signals, plannedKinds);
81890
- const coverageMap = (0, coverage_map_js_1.buildMobileCoverageMap)({
81891
- graph: input.graph,
81892
- appId: input.appId,
81893
- plannedScenarios
81894
- });
81895
- taxonomyGapLogs = [(0, scenario_taxonomy_js_1.formatCoverageGapLog)(gaps), coverageMap.summary];
81896
- if (coverageMap.warnings.length > 0) {
81897
- taxonomyGapLogs.push(...coverageMap.warnings.slice(0, 12));
82277
+ let gaps = (0, scenario_taxonomy_js_1.coverageGaps)(signals, plannedKinds);
82278
+ if (plannedScenarios.length === 0) {
82279
+ gaps = (0, scenario_taxonomy_js_1.requiredScenarioKinds)(signals).filter((k) => k !== "smoke_nav");
81898
82280
  }
81899
82281
  if (gaps.length > 0) {
81900
- taxonomyGapLogs.push(`UI signals: listRowActions=${signals.hasListWithRowActions} forms=${signals.hasFormFields} email=${signals.hasEmailField} badge=${signals.hasNumericBadge} toggles=${signals.hasSettingsToggles} signOut=${signals.hasSignOut} tabs=${signals.hasTabOrDrawerNav}`);
81901
- const detectedAt = (/* @__PURE__ */ new Date()).toISOString();
81902
- taxonomyCoverageGaps = [
81903
- ...taxonomyCoverageGaps,
81904
- ...gaps.map((kind) => ({
81905
- scenarioName: `[taxonomy] ${kind}`,
81906
- reason: `Required scenario kind "${kind}" not represented in the planned set`,
81907
- suggestion: `Add a ${kind} scenario backed by observed controls, or document impossibility`,
81908
- unmetPrerequisites: [],
81909
- detectedAt
81910
- })),
81911
- ...coverageMap.warnings.filter((w) => /smoke-only|no strong-oracle/i.test(w)).map((w) => ({
81912
- scenarioName: "[coverage-map] strong-oracle gap",
81913
- reason: w,
81914
- suggestion: "Author durable assertStateDelta/assertText outcomes for this kind",
81915
- unmetPrerequisites: [],
81916
- detectedAt
81917
- }))
81918
- ];
82282
+ const synthesized = buildMobileTaxonomyScenarios(input, gaps);
82283
+ if (synthesized.length > 0) {
82284
+ const before = plannedScenarios.length;
82285
+ plannedScenarios = [...plannedScenarios, ...synthesized];
82286
+ mobileAdaptationLogs.push(`Taxonomy synthesis: added ${synthesized.length} scenario(s) for missing kinds [${gaps.join(", ")}] (plan had ${before})`);
82287
+ gaps = (0, scenario_taxonomy_js_1.coverageGaps)(signals, (0, scenario_taxonomy_js_1.inferScenarioKinds)(plannedScenarios));
82288
+ }
82289
+ }
82290
+ if (plannedScenarios.length > 0) {
82291
+ const coverageMap = (0, coverage_map_js_1.buildMobileCoverageMap)({
82292
+ graph: input.graph,
82293
+ appId: input.appId,
82294
+ plannedScenarios
82295
+ });
82296
+ taxonomyGapLogs = [(0, scenario_taxonomy_js_1.formatCoverageGapLog)(gaps), coverageMap.summary];
82297
+ if (coverageMap.warnings.length > 0) {
82298
+ taxonomyGapLogs.push(...coverageMap.warnings.slice(0, 12));
82299
+ }
82300
+ if (gaps.length > 0 || coverageMap.warnings.length > 0) {
82301
+ taxonomyGapLogs.push(`UI signals: listRowActions=${signals.hasListWithRowActions} forms=${signals.hasFormFields} email=${signals.hasEmailField} badge=${signals.hasNumericBadge} toggles=${signals.hasSettingsToggles} signOut=${signals.hasSignOut} tabs=${signals.hasTabOrDrawerNav} search=${signals.hasSearchField} refresh=${signals.hasPullToRefresh} emptyCta=${signals.hasEmptyStateCta}`);
82302
+ const detectedAt = (/* @__PURE__ */ new Date()).toISOString();
82303
+ taxonomyCoverageGaps = [
82304
+ ...taxonomyCoverageGaps,
82305
+ ...gaps.map((kind) => ({
82306
+ scenarioName: `[taxonomy] ${kind}`,
82307
+ reason: `Required scenario kind "${kind}" not represented in the planned set`,
82308
+ suggestion: `Add a ${kind} scenario backed by observed controls, or document impossibility`,
82309
+ unmetPrerequisites: [],
82310
+ detectedAt
82311
+ })),
82312
+ ...coverageMap.warnings.filter((w) => /smoke-only|no strong-oracle/i.test(w)).map((w) => ({
82313
+ scenarioName: "[coverage-map] strong-oracle gap",
82314
+ reason: w,
82315
+ suggestion: "Author durable assertStateDelta/assertText outcomes for this kind",
82316
+ unmetPrerequisites: [],
82317
+ detectedAt
82318
+ }))
82319
+ ];
82320
+ }
81919
82321
  }
81920
82322
  }
82323
+ if (input.mode !== "survey" && input.featureName?.trim()) {
82324
+ const deepFeature = input.featureName.trim();
82325
+ plannedScenarios = plannedScenarios.map((s) => ({
82326
+ ...s,
82327
+ featureGroup: s.featureGroup?.trim() || deepFeature
82328
+ }));
82329
+ }
81921
82330
  if (input.mode !== "survey" && plannedScenarios.length === 0 && input.graph.screens.size > 0) {
81922
82331
  const fallbackScenarios = buildMobileFallbackScenarios(input);
81923
82332
  if (fallbackScenarios.length > 0) {
@@ -81928,7 +82337,7 @@ ${constraints.join("\n")}`);
81928
82337
  logs: [
81929
82338
  ...result.logs,
81930
82339
  ...mobileAdaptationLogs,
81931
- `Mobile fallback: synthesized ${fallbackScenarios.length} screen-reachability scenario(s) from the native screen graph`
82340
+ `Mobile fallback: synthesized ${fallbackScenarios.length} taxonomy/bug-capture scenario(s) from native UI signals`
81932
82341
  ],
81933
82342
  fallbackUsed: true,
81934
82343
  fallbackReason: result.fallbackReason ?? "Mobile planner produced no scenarios"
@@ -81972,6 +82381,25 @@ ${constraints.join("\n")}`);
81972
82381
  fallbackReason: result.fallbackReason ?? plannerGroupSelection.reason ?? `Planner omitted ${supplementedSurveyRouteCount} plannable mobile screen(s)`
81973
82382
  };
81974
82383
  }
82384
+ if (mobileFeatureGroups.length === 0 && input.graph.screens.size > 0) {
82385
+ const appId = input.appId?.trim();
82386
+ const owners = [...new Set([...input.graph.screens.values()].map((state2) => {
82387
+ const hashIndex = state2.screenId.indexOf("#");
82388
+ return (hashIndex >= 0 ? state2.screenId.slice(0, hashIndex) : state2.screenId).trim();
82389
+ }).filter(Boolean))];
82390
+ const inAppOwners = appId ? owners.filter((owner) => (0, shared_1.mobileScreenOwnerBelongsToApp)(owner, appId)) : owners;
82391
+ const reason = inAppOwners.length === 0 && appId ? `Mapped ${input.graph.screens.size} screen(s) but none were attributed to app "${appId}" (screen owners seen: ${owners.slice(0, 4).join(", ")}). No features could be created.` : `Mapped ${input.graph.screens.size} screen(s) but none could be grouped into a feature (too few actionable elements, or every screen was filtered as generic/system).`;
82392
+ return {
82393
+ ...result,
82394
+ scenarios: plannedScenarios,
82395
+ featureGroups: mobileFeatureGroups,
82396
+ coverageGaps: taxonomyCoverageGaps.length > 0 ? taxonomyCoverageGaps : result.coverageGaps,
82397
+ logs: [...result.logs, ...mobileAdaptationLogs, ...taxonomyGapLogs, `\u26A0 ${reason}`],
82398
+ warning: result.warning ?? reason,
82399
+ fallbackUsed: true,
82400
+ fallbackReason: result.fallbackReason ?? reason
82401
+ };
82402
+ }
81975
82403
  return {
81976
82404
  ...result,
81977
82405
  scenarios: plannedScenarios,
@@ -82040,6 +82468,7 @@ var require_anr_env = __commonJS({
82040
82468
  exports.isAnrOrSystemUiEnvironmentFailure = isAnrOrSystemUiEnvironmentFailure;
82041
82469
  exports.stepLooksLikeAnrChromeAssert = stepLooksLikeAnrChromeAssert;
82042
82470
  var ANR_TEXT_RE = /system\s*ui\s*isn['’]?t\s*responding|app\s*isn['’]?t\s*responding|application\s*not\s*responding|\banr\b|close\s*app|wait\s*and\s*see|isn['’]?t\s*responding/i;
82471
+ var SYSTEM_FREEZE_RE = /system\s*ui\s*isn['’]?t\s*responding|\bsystem\s*ui\b[^.\n]{0,40}\b(froze|frozen|hung|unresponsive|not\s*responding)\b|\b(device|emulator|simulator)\b[^.\n]{0,40}\b(froze|frozen|hung|unresponsive)\b/i;
82043
82472
  function textLooksLikeAnrOrSystemUi(text) {
82044
82473
  if (!text || typeof text !== "string")
82045
82474
  return false;
@@ -82048,7 +82477,7 @@ var require_anr_env = __commonJS({
82048
82477
  function isAnrOrSystemUiEnvironmentFailure(error2, logs2) {
82049
82478
  const blob = `${error2 ?? ""}
82050
82479
  ${logs2 ?? ""}`;
82051
- if (textLooksLikeAnrOrSystemUi(blob))
82480
+ if (SYSTEM_FREEZE_RE.test(blob))
82052
82481
  return true;
82053
82482
  if (/\bcold-boot\b/i.test(blob) && /\b(froze|hang|anr|unresponsive)\b/i.test(blob))
82054
82483
  return true;
@@ -82070,13 +82499,48 @@ var require_oracle_quality = __commonJS({
82070
82499
  "../runner-core/dist/services/mobile/oracle-quality.js"(exports) {
82071
82500
  "use strict";
82072
82501
  Object.defineProperty(exports, "__esModule", { value: true });
82502
+ exports.isToastOrAckOutcomeText = isToastOrAckOutcomeText;
82503
+ exports.isAuthPrimaryFeatureName = isAuthPrimaryFeatureName;
82504
+ exports.isStandaloneAuthValidationScenario = isStandaloneAuthValidationScenario;
82505
+ exports.textLooksLikeProductOutcome = textLooksLikeProductOutcome;
82506
+ exports.textLooksLikeChromeSurface = textLooksLikeChromeSurface;
82073
82507
  exports.assessStrongOracleQuality = assessStrongOracleQuality;
82508
+ exports.assessScenarioClaimCoherence = assessScenarioClaimCoherence;
82074
82509
  var anr_env_js_1 = require_anr_env();
82510
+ var scenario_taxonomy_js_1 = require_scenario_taxonomy();
82075
82511
  var CHROME_ONLY_RE = /\b(tab|home tab|catalog tab|forms tab|account tab|back|menu|navigation|nav bar|bottom nav|status bar|query|search field)\b/i;
82076
82512
  var PRODUCT_OUTCOME_TEXT_RE = /\b(error|invalid|required|must|cannot|failed|denied|blocked|empty|missing|deleted|removed|saved|success|created|updated|signed?\s*out|logged?\s*out|wrong|incorrect)\b/i;
82513
+ var TOAST_ACK_EXACT_RE = /^(saved!?|success!?|successfully (saved|deleted|updated|created)!?|deleted!?|removed!?|done!?|ok!?|updated!?|created!?)$/i;
82514
+ function isToastOrAckOutcomeText(text) {
82515
+ const t = text.trim();
82516
+ if (!t)
82517
+ return false;
82518
+ if (TOAST_ACK_EXACT_RE.test(t))
82519
+ return true;
82520
+ const parts = t.split(/\s+/).filter(Boolean);
82521
+ return parts.length > 0 && parts.every((part) => TOAST_ACK_EXACT_RE.test(part));
82522
+ }
82523
+ function isAuthPrimaryFeatureName(name) {
82524
+ const n = (name ?? "").trim();
82525
+ if (!n)
82526
+ return false;
82527
+ return /\b(auth|authentication|sign[\s-]*in|log[\s-]*in|login|session|onboarding|account)\b/i.test(n);
82528
+ }
82529
+ function isStandaloneAuthValidationScenario(scenario) {
82530
+ const text = `${scenario.name ?? ""} ${scenario.goal ?? ""} ${scenario.variant ?? ""}`.toLowerCase();
82531
+ if (!/\b(sign\s*in|log\s*in|login|credentials?|password|email)\b/.test(text))
82532
+ return false;
82533
+ return /\b(empty|invalid|wrong password|malformed|required|validation|reject|blocked)\b/.test(text) || scenario.variant === "validation";
82534
+ }
82077
82535
  function stepBlob(step) {
82078
82536
  return [step.description, step.assertion, step.value, step.target?.primary].filter(Boolean).join(" ");
82079
82537
  }
82538
+ function textLooksLikeProductOutcome(text) {
82539
+ return PRODUCT_OUTCOME_TEXT_RE.test(text);
82540
+ }
82541
+ function textLooksLikeChromeSurface(text) {
82542
+ return CHROME_ONLY_RE.test(text);
82543
+ }
82080
82544
  function isChromeOnlyVisible(step) {
82081
82545
  if (step.action !== "assertVisible")
82082
82546
  return false;
@@ -82113,6 +82577,8 @@ var require_oracle_quality = __commonJS({
82113
82577
  if (/^(email|password|username|name|query|search)$/i.test((s.assertion ?? "").trim())) {
82114
82578
  return false;
82115
82579
  }
82580
+ if (isToastOrAckOutcomeText(s.assertion ?? s.value ?? ""))
82581
+ return false;
82116
82582
  return blob.length >= 3;
82117
82583
  });
82118
82584
  const hasStrongValidationVisible = steps.some((s) => {
@@ -82120,7 +82586,12 @@ var require_oracle_quality = __commonJS({
82120
82586
  return false;
82121
82587
  if ((0, anr_env_js_1.stepLooksLikeAnrChromeAssert)(s) || isChromeOnlyVisible(s))
82122
82588
  return false;
82123
- return PRODUCT_OUTCOME_TEXT_RE.test(stepBlob(s));
82589
+ const blob = stepBlob(s);
82590
+ if (isToastOrAckOutcomeText(s.assertion ?? s.value ?? ""))
82591
+ return false;
82592
+ if (isToastOrAckOutcomeText(blob))
82593
+ return false;
82594
+ return PRODUCT_OUTCOME_TEXT_RE.test(blob);
82124
82595
  });
82125
82596
  const strong = hasStateDelta || hasStrongAssertText || hasStrongValidationVisible;
82126
82597
  let reason;
@@ -82145,6 +82616,70 @@ var require_oracle_quality = __commonJS({
82145
82616
  reason
82146
82617
  };
82147
82618
  }
82619
+ function assessScenarioClaimCoherence(scenario, steps) {
82620
+ const variant = scenario.variant === "happy" || scenario.variant === "validation" || scenario.variant === "bug" ? scenario.variant : void 0;
82621
+ const kind = (0, scenario_taxonomy_js_1.inferScenarioKind)({
82622
+ type: scenario.type || "HAPPY_PATH",
82623
+ variant,
82624
+ name: scenario.name ?? "",
82625
+ goal: scenario.goal ?? ""
82626
+ });
82627
+ const quality = assessStrongOracleQuality(steps);
82628
+ const text = `${scenario.name ?? ""} ${scenario.goal ?? ""}`.toLowerCase();
82629
+ const featureGroup = scenario.featureGroup ?? "";
82630
+ if (isStandaloneAuthValidationScenario(scenario) && featureGroup && !isAuthPrimaryFeatureName(featureGroup)) {
82631
+ return {
82632
+ coherent: false,
82633
+ kind,
82634
+ discard: true,
82635
+ reason: `auth credential validation scenario under non-auth feature "${featureGroup}" \u2014 login is setup only`
82636
+ };
82637
+ }
82638
+ if (quality.anrOnly) {
82639
+ return {
82640
+ coherent: false,
82641
+ kind,
82642
+ discard: true,
82643
+ reason: quality.reason
82644
+ };
82645
+ }
82646
+ if ((0, scenario_taxonomy_js_1.kindRequiresStateDelta)(kind) && !quality.hasStateDelta) {
82647
+ const namesStateClaim = /\b(count|delta|delete|removed|persist|roundtrip|wrong row|entity|double.?submit|fires?:?\s*2|refresh)\b/i.test(text);
82648
+ return {
82649
+ coherent: false,
82650
+ kind,
82651
+ // Discard when the name/kind clearly promised state proof; otherwise demote.
82652
+ discard: namesStateClaim || kind === "crud_identity" || kind === "count_delta" || kind === "list_refresh",
82653
+ reason: `scenario kind ${kind} claims durable state change but steps lack assertStateDelta (${quality.reason})`
82654
+ };
82655
+ }
82656
+ if (/\b(empty.?state|empty cta|dead route|404|not found|broken blank)\b/i.test(text)) {
82657
+ const hasProductDestination = steps.some((s) => {
82658
+ if (s.action !== "assertVisible" && s.action !== "assertText")
82659
+ return false;
82660
+ if ((0, anr_env_js_1.stepLooksLikeAnrChromeAssert)(s))
82661
+ return false;
82662
+ const blob = stepBlob(s);
82663
+ if (CHROME_ONLY_RE.test(blob) && !PRODUCT_OUTCOME_TEXT_RE.test(blob))
82664
+ return false;
82665
+ return PRODUCT_OUTCOME_TEXT_RE.test(blob) || /\b(404|not found|empty|no items|blank|error)\b/i.test(blob);
82666
+ });
82667
+ if (!hasProductDestination && !quality.hasStateDelta) {
82668
+ return {
82669
+ coherent: false,
82670
+ kind,
82671
+ discard: false,
82672
+ reason: "empty-state/dead-route claim without destination or empty-state product assertion"
82673
+ };
82674
+ }
82675
+ }
82676
+ return {
82677
+ coherent: true,
82678
+ kind,
82679
+ discard: false,
82680
+ reason: "scenario claim matches step oracles"
82681
+ };
82682
+ }
82148
82683
  }
82149
82684
  });
82150
82685
 
@@ -82662,7 +83197,18 @@ ${hybridSkeleton.join("\n")}`;
82662
83197
  function hasStableId(element) {
82663
83198
  return !!nonEmpty3(element.accessibilityId) || !!nonEmpty3(element.resourceId);
82664
83199
  }
82665
- function buildSystemPrompt(platform3, targetAppId, maxIterations = MAX_SCENARIO_ITERATIONS) {
83200
+ function buildKnownFactsPromptBlock(knowledgeContext) {
83201
+ const text = knowledgeContext?.trim();
83202
+ if (!text)
83203
+ return "";
83204
+ return `
83205
+
83206
+ ## Known Facts (project documents \u2014 optional)
83207
+ ${text.slice(0, 6e3)}
83208
+
83209
+ When facts are present, prefer assertions that prove them if the live UI supports it. If a fact conflicts with what you see on device, prefer live UI. Never invent requirements not in these facts and not visible on screen. When this section is absent, rely only on the scenario + live UI.`;
83210
+ }
83211
+ function buildSystemPrompt(platform3, targetAppId, maxIterations = MAX_SCENARIO_ITERATIONS, knowledgeContext) {
82666
83212
  const platformLabel = platform3 === "IOS" ? "iOS" : "Android";
82667
83213
  const targetLine = targetAppId ? ` Target app package/bundle: ${targetAppId}.` : "";
82668
83214
  return `You are an expert mobile QA agent generating ONE automated test by driving a real ${platformLabel} app on a connected device. The app has just been relaunched into a clean state.
@@ -82686,14 +83232,14 @@ The scenario name + goal + steps describe ONE product behavior from survey/disco
82686
83232
  - For list delete/create or count changes: mobile_capture_state({stateKey, kind}) BEFORE the mutation, then mobile_assert_state_delta({stateKey, expect}) AFTER \u2014 BOTH are required. captureState alone does NOT prove the outcome.
82687
83233
  - Negative validation: leave a required field EMPTY (or type clearly invalid email-like input), submit, assert the app BLOCKS success \u2014 error message / still on form / no navigation to Home. Do NOT fill a valid password-only path and call it "empty email".
82688
83234
  - After sign-in \u2192 signed-in product signal; after like \u2192 liked/unlike control or durable like state; after open Settings \u2192 a settings-specific control.
82689
- - Do NOT assert bottom-nav tab labels alone, notification badge counts ("N unread"), or one-time empty-state CTAs as the scenario outcome.
83235
+ - Do NOT assert bottom-nav tab labels alone or notification badge counts ("N unread") as the scenario outcome.
82690
83236
  - NEVER assert system freeze chrome ("System UI isn't responding", ANR dialogs, Wait/Close app). If the app freezes, finish_generate with verified:false (environment) \u2014 do NOT write a test whose only proof is the ANR dialog.
82691
83237
  5. Call finish_generate with verified:true ONLY if you completed the goal AND asserted a matching durable outcome. If the app cannot complete the goal, finish with verified:false and explain \u2014 never invent a green path from unrelated screens.
82692
83238
 
82693
83239
  ## Rules
82694
83240
  - Re-snapshot before every assertion so the ref is fresh.
82695
83241
  - Assert the OUTCOME of the flow (the new screen / new content), not the control you just tapped.
82696
- - Assert only DURABLE elements \u2014 screen chrome that exists on every visit (tab labels, headers, nav bars, the entity you just created). NEVER assert one-time / data-dependent UI: empty-state CTAs, first-run or onboarding prompts, or counters \u2014 they vanish as soon as the account has data, and the test then fails forever on a healthy app.
83242
+ - Assert only DURABLE product outcomes. Prefer entity identity, form values, validation copy, destination screens after navigation. For empty-state CTA scenarios: tap the CTA and assert the DESTINATION (form, detail, or honest error) \u2014 do NOT treat the CTA label alone as success, and do NOT use empty-state CTAs as proof for unrelated happy paths.
82697
83243
  - Do NOT trigger irreversible or destructive side effects \u2014 real payments; sending messages to others; and ESPECIALLY account/data deletion, deactivation, or any "type DELETE to confirm" gate (the runner hard-blocks destructive taps and confirmation keystrokes). Note them and assert what you safely can.
82698
83244
  - STATE OWNERSHIP for mutation scenarios (edit / rename / archive / remove): CREATE the record first in this same recording, then act on the row YOU created \u2014 never mutate pre-existing data (it may not exist on a clean install, so the replay fails forever, and another test may depend on it). If the app offers no way to create one, do NOT act on someone else's data: assert what you can safely prove and finish with verified:false, explaining why in the description.
82699
83245
  - If the APP itself misbehaves (product error screen, broken validation, wrong entity deleted), assert the product failure and call finish_generate with suspectedBug:true and a concrete bugDescription. If the device shows ANR / "System UI isn't responding" / freeze dialogs, that is ENVIRONMENT \u2014 finish with verified:false and do NOT assert the freeze dialog as the test outcome.
@@ -82706,7 +83252,7 @@ The scenario name + goal + steps describe ONE product behavior from survey/disco
82706
83252
  - Each action must make NEW progress toward the goal. If an action leaves the screen unchanged, do NOT repeat it \u2014 pick a different element or move on.
82707
83253
  - Finish promptly once the outcome is proven: the instant the expected outcome is visible, assert it and call finish_generate. Do not keep exploring after the goal is proven.
82708
83254
 
82709
- Max iterations: ${maxIterations}. You will be warned near the end.`;
83255
+ Max iterations: ${maxIterations}. You will be warned near the end.` + buildKnownFactsPromptBlock(knowledgeContext);
82710
83256
  }
82711
83257
  function buildGenerateCredentialPromptBlock(secrets) {
82712
83258
  const keys = Object.keys(secrets).filter((k) => secrets[k] && secrets[k].length > 0);
@@ -82796,7 +83342,7 @@ Start by calling mobile_snapshot, then execute ONLY the steps needed for this go
82796
83342
  }
82797
83343
  }
82798
83344
  async function runScenarioLoop(args) {
82799
- const { scenario, driver, platform: platform3, maxIterations, agentModel, provider, aiClient, auditGroupId, onAICall, onScreenshot, targetAppId, credentials, redactionCredentials, log: emitLog, allowRelaunch } = args;
83345
+ const { scenario, driver, platform: platform3, maxIterations, agentModel, provider, aiClient, auditGroupId, onAICall, onScreenshot, targetAppId, credentials, redactionCredentials, log: emitLog, allowRelaunch, knowledgeContext } = args;
82800
83346
  const log2 = (line) => emitLog(redactCredentialValues(line, redactionCredentials));
82801
83347
  const actions = [];
82802
83348
  const stateBag = /* @__PURE__ */ new Map();
@@ -83174,7 +83720,7 @@ ${lines.join("\n")}`
83174
83720
  (0, mobile_driver_errors_js_1.rethrowIfTerminalMobileDriverError)(err);
83175
83721
  log2(` seed snapshot failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
83176
83722
  }
83177
- const systemPrompt = buildSystemPrompt(platform3, targetAppId, maxIterations) + buildGenerateCredentialPromptBlock(credentials);
83723
+ const systemPrompt = buildSystemPrompt(platform3, targetAppId, maxIterations, knowledgeContext) + buildGenerateCredentialPromptBlock(credentials);
83178
83724
  const kickoff = buildScenarioKickoff(scenario);
83179
83725
  const recentExchanges = [];
83180
83726
  const hasStoredCredentials = Object.values(credentials).some((v) => typeof v === "string" && v.length > 0);
@@ -85123,6 +85669,8 @@ ${statePacket}`, redactionCredentials) },
85123
85669
  const t = text.trim();
85124
85670
  if (!t)
85125
85671
  return false;
85672
+ if ((0, oracle_quality_js_1.isToastOrAckOutcomeText)(t))
85673
+ return true;
85126
85674
  if (/\b\d+\s*(s|sec|secs|second|seconds|m|min|mins|minute|minutes|h|hr|hrs|hour|hours|d|day|days|w|wk|wks|week|weeks|mo|mos|month|months|y|yr|yrs|year|years)\s+ago\b/i.test(t)) {
85127
85675
  return true;
85128
85676
  }
@@ -85228,6 +85776,30 @@ ${statePacket}`, redactionCredentials) },
85228
85776
  }
85229
85777
  const ephemeral = modelAsserts.filter((a) => isEphemeralContentAssertText(assertIdentityText(a)));
85230
85778
  const durable = modelAsserts.filter((a) => !isEphemeralContentAssertText(assertIdentityText(a)));
85779
+ const chromeOnlyVisible = (a) => {
85780
+ if (a.type !== "ASSERT_VISIBLE")
85781
+ return false;
85782
+ const blob = assertIdentityText(a);
85783
+ if ((0, oracle_quality_js_1.isToastOrAckOutcomeText)(blob))
85784
+ return true;
85785
+ return /\b(tab|home|settings|back|menu|navigation|nav bar|bottom nav|status bar)\b/i.test(blob) && !/\b(error|invalid|required|failed|deleted|removed|created)\b/i.test(blob);
85786
+ };
85787
+ if (durable.length > 0 && durable.every(chromeOnlyVisible) && !actions.some((a) => a.type === "ASSERT_STATE_DELTA")) {
85788
+ return {
85789
+ ok: false,
85790
+ severity: "downgrade",
85791
+ reason: "only landing/chrome visibility after interaction \u2014 not a durable product outcome",
85792
+ signals: {
85793
+ apiTest: false,
85794
+ interacted: actions.some((a) => a.type === "TAP" || a.type === "TYPE"),
85795
+ mutated: actions.some((a) => a.type === "TYPE" || a.type === "CLEAR" || a.type === "TAP"),
85796
+ navOnly: false,
85797
+ hasOutcomeProof: false,
85798
+ errorBanner: false,
85799
+ terminal: null
85800
+ }
85801
+ };
85802
+ }
85231
85803
  if (ephemeral.length > 0 && durable.length === 0) {
85232
85804
  return {
85233
85805
  ok: false,
@@ -85322,10 +85894,11 @@ ${statePacket}`, redactionCredentials) },
85322
85894
  }
85323
85895
  const baseStrengthVerdict = evaluateMobileAssertionStrength(actions);
85324
85896
  const bugDescription = recording.finish?.bugDescription?.trim() ?? "";
85897
+ const bugWitnessEnabled = (0, shared_1.parseBoolFlag)(process.env.DISCOVERY_BUG_WITNESS_ENABLED, true);
85325
85898
  const bugLooksLikeAnr = (0, anr_env_js_1.textLooksLikeAnrOrSystemUi)(bugDescription);
85326
- const bugWitnessHonored = process.env.DISCOVERY_BUG_WITNESS_ENABLED === "true" && recording.finish?.suspectedBug === true && bugDescription.length >= 12 && recording.assertCount > 0 && !bugLooksLikeAnr;
85899
+ const bugWitnessHonored = bugWitnessEnabled && recording.finish?.suspectedBug === true && bugDescription.length >= 12 && recording.assertCount > 0 && !bugLooksLikeAnr;
85327
85900
  if (recording.finish?.suspectedBug === true && !bugWitnessHonored) {
85328
- log2(" suspectedBug declared but NOT honored: " + (bugLooksLikeAnr ? "ANR/System UI freeze is environment noise, not a product bug-witness." : process.env.DISCOVERY_BUG_WITNESS_ENABLED !== "true" ? "bug-witness channel disabled (DISCOVERY_BUG_WITNESS_ENABLED)." : bugDescription.length < 12 ? "bugDescription too short." : "no honored assert backs the observation."));
85901
+ log2(" suspectedBug declared but NOT honored: " + (bugLooksLikeAnr ? "ANR/System UI freeze is environment noise, not a product bug-witness." : !bugWitnessEnabled ? "bug-witness channel disabled (DISCOVERY_BUG_WITNESS_ENABLED)." : bugDescription.length < 12 ? "bugDescription too short." : "no honored assert backs the observation."));
85329
85902
  }
85330
85903
  const strengthVerdict = bugWitnessHonored ? {
85331
85904
  ...baseStrengthVerdict,
@@ -85355,30 +85928,48 @@ ${statePacket}`, redactionCredentials) },
85355
85928
  if (selectorLintEnforced && verified) {
85356
85929
  log2(` selector-quality lint (enforce): ${selectorQuality.summary.high} high-severity locator issue(s) \u2014 tagging @needs-review.`);
85357
85930
  }
85358
- const reviewTag = verified && !selectorLintEnforced ? "@verified" : "@needs-review";
85931
+ const strengthBlocked = !strengthVerdict.ok || strengthVerdict.severity === "block" || strengthVerdict.severity === "route-bug" || !verified || coldResetUnavailable;
85932
+ const claimCoherence = (0, oracle_quality_js_1.assessScenarioClaimCoherence)({
85933
+ name: scenario.name,
85934
+ goal: scenario.goal,
85935
+ type: scenario.type,
85936
+ variant: scenario.variant,
85937
+ featureGroup: scenario.featureGroup
85938
+ }, compiled.steps);
85939
+ const oracleQualityEarly = (0, oracle_quality_js_1.assessStrongOracleQuality)(compiled.steps);
85940
+ if (oracleQualityEarly.anrOnly || claimCoherence.discard) {
85941
+ log2(` discarding incoherent/ANR recording: ${claimCoherence.discard ? claimCoherence.reason : oracleQualityEarly.reason}`);
85942
+ return null;
85943
+ }
85944
+ const reviewTag = verified && !selectorLintEnforced && claimCoherence.coherent ? "@verified" : "@needs-review";
85359
85945
  const tags = ["@discovered", "@mobile", platformTag2, reviewTag];
85360
85946
  if (strengthVerdict.severity === "downgrade")
85361
85947
  tags.push("@smoke");
85948
+ if (strengthVerdict.severity === "route-bug" && !tags.includes("@bug-found")) {
85949
+ tags.push("@bug-found");
85950
+ }
85362
85951
  if (coldResetUnavailable)
85363
85952
  tags.push("@warm-state");
85364
- const strengthBlocked = !strengthVerdict.ok || strengthVerdict.severity === "block" || strengthVerdict.severity === "route-bug" || !verified || coldResetUnavailable;
85365
85953
  {
85366
85954
  const kind = (0, scenario_taxonomy_js_1.inferScenarioKind)(scenario);
85367
- const oracleQuality = (0, oracle_quality_js_1.assessStrongOracleQuality)(compiled.steps);
85368
- if (oracleQuality.anrOnly) {
85369
- log2(` discarding ANR-chrome-only recording: ${oracleQuality.reason}`);
85370
- return null;
85371
- }
85955
+ const oracleQuality = oracleQualityEarly;
85372
85956
  if (oracleQuality.unpairedCaptures > 0) {
85373
85957
  log2(` oracle quality: ${oracleQuality.reason}`);
85374
85958
  }
85375
- const strong = verified && !strengthBlocked && strengthVerdict.severity === "none" && oracleQuality.strong && ((0, scenario_taxonomy_js_1.isStrongOracleKind)(kind) || oracleQuality.hasStateDelta || oracleQuality.hasStrongAssertText);
85959
+ if (!claimCoherence.coherent) {
85960
+ log2(` scenario claim weak: ${claimCoherence.reason}`);
85961
+ if (!tags.includes("@smoke"))
85962
+ tags.push("@smoke");
85963
+ }
85964
+ const strong = claimCoherence.coherent && verified && !strengthBlocked && strengthVerdict.severity === "none" && oracleQuality.strong && ((0, scenario_taxonomy_js_1.isStrongOracleKind)(kind) || oracleQuality.hasStateDelta || oracleQuality.hasStrongAssertText);
85376
85965
  if (strong)
85377
85966
  tags.push("@strong-oracle");
85378
85967
  else if (!tags.includes("@smoke")) {
85379
85968
  tags.push("@smoke");
85380
85969
  if (!oracleQuality.strong) {
85381
85970
  log2(` tagged @smoke (not strong-oracle): ${oracleQuality.reason}`);
85971
+ } else if (!claimCoherence.coherent) {
85972
+ log2(` tagged @smoke (claim incoherent): ${claimCoherence.reason}`);
85382
85973
  }
85383
85974
  }
85384
85975
  }
@@ -85398,11 +85989,9 @@ ${statePacket}`, redactionCredentials) },
85398
85989
  playwrightCode: "",
85399
85990
  verified,
85400
85991
  tags,
85401
- // Per-test feature label → TestCase.suite. One deep run plans scenarios for
85402
- // MULTIPLE feature groups (the planner reuses survey feature names), so the
85403
- // run-level ctx.featureName fallback in /discovery-test would wrongly file
85404
- // every test under the deep-dived feature. The scenario's own group is the
85405
- // correct home; the runner forwards it as `suiteName`.
85992
+ // Per-test suite hint. Server deep mode overrides suite to ctx.featureName
85993
+ // so leaf features receive their own tests; full-mode multi-group still uses
85994
+ // featureGroup when present.
85406
85995
  ...scenario.featureGroup?.trim() ? { suiteName: scenario.featureGroup.trim() } : {},
85407
85996
  // Carry the planner scenario identity so incremental/resume can match an
85408
85997
  // already-generated scenario reliably (scenarioRef.name === the plan's
@@ -85569,7 +86158,8 @@ ${statePacket}`, redactionCredentials) },
85569
86158
  credentials: credentialSecrets,
85570
86159
  redactionCredentials: credentialValuesForRedaction,
85571
86160
  log: log2,
85572
- allowRelaunch: (ctx.target?.resetPolicy ?? "AUTO") !== "PRESERVE_APP_DATA"
86161
+ allowRelaunch: (ctx.target?.resetPolicy ?? "AUTO") !== "PRESERVE_APP_DATA",
86162
+ knowledgeContext: ctx.knowledgeContext
85573
86163
  });
85574
86164
  consecutiveInfraFailures = 0;
85575
86165
  const test = assembleTest({
@@ -85634,13 +86224,23 @@ var require_failure_triage = __commonJS({
85634
86224
  "../runner-core/dist/services/mobile/failure-triage.js"(exports) {
85635
86225
  "use strict";
85636
86226
  Object.defineProperty(exports, "__esModule", { value: true });
86227
+ exports.isOracleStep = isOracleStep;
85637
86228
  exports.hasStrongMobileOracle = hasStrongMobileOracle;
85638
86229
  exports.isStrongOracleStep = isStrongOracleStep;
85639
86230
  exports.listStrongOracleKinds = listStrongOracleKinds;
85640
86231
  exports.triageMobileFailure = triageMobileFailure;
85641
86232
  exports.triageToHealTerminal = triageToHealTerminal;
85642
86233
  var anr_env_js_1 = require_anr_env();
85643
- var STRONG_ACTIONS = /* @__PURE__ */ new Set(["assertStateDelta", "assertText", "captureState"]);
86234
+ var oracle_quality_js_1 = require_oracle_quality();
86235
+ var STRONG_ACTIONS = /* @__PURE__ */ new Set(["assertStateDelta", "assertText"]);
86236
+ var ORACLE_ACTIONS = /* @__PURE__ */ new Set([
86237
+ "assertVisible",
86238
+ "assertText",
86239
+ "assertStateDelta"
86240
+ ]);
86241
+ function isOracleStep(step) {
86242
+ return ORACLE_ACTIONS.has(step.action);
86243
+ }
85644
86244
  var CHROME_VISIBLE_RE = /\b(tab|home|settings|back|menu|navigation|nav bar|bottom nav|status bar)\b/i;
85645
86245
  function hasStrongMobileOracle(steps) {
85646
86246
  return steps.some(isStrongOracleStep);
@@ -85656,23 +86256,31 @@ var require_failure_triage = __commonJS({
85656
86256
  step.target?.primary ?? "",
85657
86257
  ...step.target?.fallbacks ?? []
85658
86258
  ].join(" ");
85659
- if (/\b(error|invalid|required|must|cannot|failed|denied|blocked|empty|missing|deleted|removed|saved|success|created|updated)\b/i.test(blob)) {
86259
+ if ((0, anr_env_js_1.stepLooksLikeAnrChromeAssert)(step))
86260
+ return false;
86261
+ if ((0, oracle_quality_js_1.isToastOrAckOutcomeText)(step.assertion ?? step.value ?? ""))
86262
+ return false;
86263
+ if ((0, oracle_quality_js_1.textLooksLikeProductOutcome)(blob))
85660
86264
  return true;
85661
- }
85662
- if (CHROME_VISIBLE_RE.test(blob) && blob.length < 80)
86265
+ const anchor = [step.target?.primary ?? "", ...step.target?.fallbacks ?? []].join(" ").trim();
86266
+ if (!anchor)
85663
86267
  return false;
85664
- return false;
86268
+ if (CHROME_VISIBLE_RE.test(blob) || (0, oracle_quality_js_1.textLooksLikeChromeSurface)(blob))
86269
+ return false;
86270
+ return blob.trim().length >= 3;
85665
86271
  }
85666
86272
  function listStrongOracleKinds(steps) {
85667
86273
  const kinds = /* @__PURE__ */ new Set();
86274
+ const hasDelta = steps.some((s) => s.action === "assertStateDelta");
85668
86275
  for (const step of steps) {
85669
86276
  if (step.action === "assertStateDelta")
85670
86277
  kinds.add("assertStateDelta");
85671
86278
  else if (step.action === "assertText")
85672
86279
  kinds.add("assertText");
85673
- else if (step.action === "captureState")
85674
- kinds.add("captureState");
85675
- else if (isStrongOracleStep(step))
86280
+ else if (step.action === "captureState") {
86281
+ if (hasDelta)
86282
+ kinds.add("captureState");
86283
+ } else if (isStrongOracleStep(step))
85676
86284
  kinds.add(step.action);
85677
86285
  }
85678
86286
  return [...kinds];
@@ -85694,6 +86302,8 @@ ${logs2 ?? ""}`.trim();
85694
86302
  return true;
85695
86303
  if (/Missing mobile test variable/i.test(text))
85696
86304
  return true;
86305
+ if (/entry.?screen drift|screen drift|started on an unexpected screen/i.test(text))
86306
+ return true;
85697
86307
  if (/\b(quota|rate.?limit|429|lockout)\b/i.test(text))
85698
86308
  return true;
85699
86309
  if (/\b(device (?:offline|disconnected|not found)|session (?:not started|terminated|deleted))\b/i.test(text)) {
@@ -85714,7 +86324,10 @@ ${logs2 ?? ""}`.trim();
85714
86324
  return /not found|no such element|No identity locator|unable to locate/i.test(text);
85715
86325
  }
85716
86326
  function looksLikeOracleFailure(text) {
85717
- return /assertStateDelta/i.test(text) || /expected state/i.test(text) || /expected (?:["'].+["'] )?(?:to be |text|visible|removed|count)/i.test(text) || /assertion failed|Assert .+ (?:visible|shows|contains)/i.test(text);
86327
+ return /assertStateDelta/i.test(text) || /expected state/i.test(text) || /expected (?:["'].+["'] )?(?:to be |text|visible|removed|count)/i.test(text) || /assertion failed|Assert .+ (?:visible|shows|contains)/i.test(text) || /found but not visible/i.test(text);
86328
+ }
86329
+ function looksLikeUnpairedStateDelta(text) {
86330
+ return /assertStateDelta[^\n]*no prior captureState/i.test(text);
85718
86331
  }
85719
86332
  function triageMobileFailure(input) {
85720
86333
  const failureCount = Math.max(1, input.failureCount ?? 1);
@@ -85723,11 +86336,20 @@ ${logs2 ?? ""}`.trim();
85723
86336
  const prefix = leadingPrefix(input.error);
85724
86337
  const strongKinds = listStrongOracleKinds(input.steps);
85725
86338
  const hasStrong = strongKinds.length > 0 || tags.some((t) => t === "@strong-oracle" || t === "strong-oracle");
86339
+ const failureText = (input.error ?? "").trim() || text;
86340
+ const failedStep = typeof input.failedStepOrder === "number" ? input.steps.find((s) => s.order === input.failedStepOrder) : void 0;
86341
+ const failedStepIsOracle = !!failedStep && isOracleStep(failedStep);
86342
+ const postHeal = input.postHeal === true;
86343
+ const locatorDrift = looksLikeLocatorMiss(failureText) && !failedStepIsOracle;
86344
+ const explicitOracleFailure = looksLikeOracleFailure(failureText);
86345
+ const missingOutcome = failedStepIsOracle && looksLikeLocatorMiss(failureText);
85726
86346
  const evidence = {
85727
86347
  hasStrongOracle: hasStrong,
85728
86348
  strongOracleKinds: strongKinds,
85729
86349
  failureCount,
85730
- errorPrefix: prefix
86350
+ errorPrefix: prefix,
86351
+ ...failedStep ? { failedStepAction: failedStep.action } : {},
86352
+ ...failedStep ? { failedOnOracleStep: failedStepIsOracle } : {}
85731
86353
  };
85732
86354
  if ((0, anr_env_js_1.isAnrOrSystemUiEnvironmentFailure)(input.error, input.logs)) {
85733
86355
  return {
@@ -85792,11 +86414,47 @@ ${logs2 ?? ""}`.trim();
85792
86414
  evidence
85793
86415
  };
85794
86416
  }
85795
- if (hasStrong && failureCount >= 2 && (looksLikeOracleFailure(text) || !looksLikeLocatorMiss(text))) {
85796
- if (looksLikeLocatorMiss(text) && failureCount < 3) {
86417
+ if (looksLikeUnpairedStateDelta(failureText)) {
86418
+ return {
86419
+ verdict: "test_invalid",
86420
+ reason: "assertStateDelta has no prior captureState for its key \u2014 the test cannot prove a delta",
86421
+ shouldHeal: false,
86422
+ healVerdict: "test_invalid",
86423
+ evidence
86424
+ };
86425
+ }
86426
+ if (hasStrong && strongKinds.includes("assertStateDelta") && /assertStateDelta/i.test(failureText) && explicitOracleFailure && !locatorDrift) {
86427
+ return {
86428
+ verdict: "app_bug_candidate",
86429
+ reason: "assertStateDelta oracle failed \u2014 durable product state did not match expected outcome",
86430
+ shouldHeal: false,
86431
+ healVerdict: "app_bug",
86432
+ evidence
86433
+ };
86434
+ }
86435
+ if (hasStrong && (strongKinds.includes("assertText") || strongKinds.includes("assertVisible")) && explicitOracleFailure && !locatorDrift) {
86436
+ return {
86437
+ verdict: "app_bug_candidate",
86438
+ reason: `Strong oracle (${strongKinds.join(", ") || "tagged"}) failed with product-shaped error`,
86439
+ shouldHeal: false,
86440
+ healVerdict: "app_bug",
86441
+ evidence
86442
+ };
86443
+ }
86444
+ if (hasStrong && missingOutcome && postHeal) {
86445
+ return {
86446
+ verdict: "app_bug_candidate",
86447
+ reason: `Strong oracle (${strongKinds.join(", ") || "tagged"}) outcome never appeared and heal could not locate it`,
86448
+ shouldHeal: false,
86449
+ healVerdict: "app_bug",
86450
+ evidence
86451
+ };
86452
+ }
86453
+ if (hasStrong && failureCount >= 2) {
86454
+ if ((locatorDrift || missingOutcome) && !postHeal) {
85797
86455
  return {
85798
86456
  verdict: "needs_heal",
85799
- reason: "Strong oracle present but error looks like a locator miss \u2014 attempt heal",
86457
+ reason: "Strong oracle present but the element was not found \u2014 attempt heal first",
85800
86458
  shouldHeal: true,
85801
86459
  evidence
85802
86460
  };
@@ -85943,7 +86601,7 @@ var require_oracle_protection = __commonJS({
85943
86601
  return `heal patch dropped assertText outcome proof (${before.assertTexts.length} \u2192 ${after.assertTexts.length})`;
85944
86602
  }
85945
86603
  if (lost.length > 0) {
85946
- const softKept = lost.every((t) => after.assertTexts.some((a) => a.includes(t) || t.includes(a)));
86604
+ const softKept = lost.every((t) => after.assertTexts.some((a) => a === t || a.includes(t)));
85947
86605
  if (!softKept) {
85948
86606
  return `heal patch replaced assertText expectations (${lost.slice(0, 2).join("; ")}) \u2014 outcome must stay`;
85949
86607
  }
@@ -85969,6 +86627,23 @@ var require_oracle_protection = __commonJS({
85969
86627
  return `heal patch downgraded strong oracle "${key.slice(0, 60)}" to assertVisible`;
85970
86628
  }
85971
86629
  }
86630
+ const OUTCOME_LANG = /\b(error|invalid|required|empty|saved|success|created|updated|deleted|removed|failed|missing)\b/i;
86631
+ const CHROME_TARGET = /\b(tab|home|settings|back|menu|navigation|nav bar|bottom nav|status bar)\b/i;
86632
+ for (const orig of original) {
86633
+ if (orig.action !== "assertVisible" || !(0, failure_triage_js_1.isStrongOracleStep)(orig))
86634
+ continue;
86635
+ const origBlob = [orig.assertion, orig.description, orig.target?.primary].filter(Boolean).join(" ");
86636
+ if (!OUTCOME_LANG.test(origBlob))
86637
+ continue;
86638
+ const key = normalizeText(orig.description ?? orig.assertion ?? "");
86639
+ const match = patched.find((p) => p.action === "assertVisible" && normalizeText(p.description ?? p.assertion ?? "") === key);
86640
+ if (!match)
86641
+ continue;
86642
+ const newTarget = match.target?.primary ?? "";
86643
+ if (CHROME_TARGET.test(newTarget) && !OUTCOME_LANG.test(newTarget)) {
86644
+ return `heal patch retargeted outcome assert "${key.slice(0, 60)}" onto chrome`;
86645
+ }
86646
+ }
85972
86647
  return null;
85973
86648
  }
85974
86649
  function oraclesPreserved(original, patched) {
@@ -86059,14 +86734,14 @@ var require_mobile_heal_postprocess = __commonJS({
86059
86734
  isVerifiedFix = false;
86060
86735
  const anrEnv = (0, anr_env_js_1.isAnrOrSystemUiEnvironmentFailure)(heal.healReason ?? args.finalError ?? args.reproduceError, typeof args.finalError === "string" ? args.finalError : void 0);
86061
86736
  const isConfigIssue = heal.verdict === "config_issue" || heal.verdict === "app_bug" && anrEnv;
86062
- const isAppBug = !anrEnv && (heal.verdict === "app_bug" || Boolean(oracleWeakening && heal.passed));
86737
+ const isAppBug = !anrEnv && heal.verdict === "app_bug";
86063
86738
  const extraTags = new Set((heal.extraTags ?? []).filter((t) => typeof t === "string" && t.length > 0));
86064
86739
  if (secretLeak)
86065
86740
  extraTags.add("@needs-review");
86066
- if (oracleWeakening && !anrEnv) {
86067
- extraTags.add("@needs-review");
86741
+ if (isAppBug)
86068
86742
  extraTags.add("@bug-found");
86069
- }
86743
+ if (oracleWeakening && !anrEnv)
86744
+ extraTags.add("@needs-review");
86070
86745
  if (anrEnv) {
86071
86746
  extraTags.delete("@bug-found");
86072
86747
  extraTags.add("@needs-review");
@@ -86090,7 +86765,7 @@ var require_mobile_heal_postprocess = __commonJS({
86090
86765
  } else if (secretLeak) {
86091
86766
  error2 = `HEAL_SECRET_LEAK: healed steps contained a literal secret (${secretLeak}); patch dropped, tagged @needs-review`;
86092
86767
  } else if (oracleWeakening && !anrEnv) {
86093
- error2 = `APP_BUG: heal attempted to drop strong oracle (${oracleWeakening}); patch refused`;
86768
+ error2 = `HEAL_ORACLE_REFUSED: heal attempted to weaken a strong oracle (${oracleWeakening}); patch refused, tagged @needs-review`;
86094
86769
  } else if (isConfigIssue) {
86095
86770
  const reason = heal.healReason ?? args.finalError ?? args.reproduceError ?? "environment/rate-limit blocker";
86096
86771
  error2 = anrEnv ? `CONFIG_ISSUE: ANR / System UI freeze (not a product assertion failure) \u2014 ${reason}` : `CONFIG_ISSUE: ${reason}`;
@@ -86547,7 +87222,7 @@ Reason over steps + error + tree + registry and return working healed steps. Do
86547
87222
  1. ERROR: which step failed, on what locator/assertion? "element not found"/"no such element" almost always means a WRONG LOCATOR on a screen that DOES exist \u2014 pick a stronger IDENTITY locator that is actually present in the captured tree: a resource-id, an accessibility-id/content-desc, or an EXACT @text= predicate (never a loose contains()). Do NOT declare a feature absent from one failed locator.
86548
87223
  2. STEP RESULTS: which steps passed before the failure.
86549
87224
  3. TREE: does the current screen match what the failed step expects?
86550
- 3b. STALE EMPTY-STATE ASSERT: a failing assert on one-time / data-dependent UI (empty-state CTAs, first-run prompts, onboarding banners) is NOT a locator problem \u2014 the element is gone because the account now has data. REPLACE the assertion with a durable landing-screen anchor (tab label, header, nav bar) that proves the same outcome (verdict fix).
87225
+ 3b. MISSING PRODUCT OUTCOME: a failing assert on empty-state CTAs, confirmation copy, a created/deleted row, or validation text is a PRODUCT oracle, not a locator problem. If that outcome is absent from a healthy screen, return verdict "app_bug". Do NOT replace outcome asserts with tab / header / nav chrome. Only retarget a locator when the SAME outcome copy is present in the tree.
86551
87226
  3c. ANR / "System UI isn't responding" / freeze dialogs: this is ENVIRONMENT (config_issue), NOT app_bug. Do not quarantine product bugs for device freezes.
86552
87227
  4. EXTERNAL AUTH HANDOFF: if the failure says the foreground app changed outside the target app after a Login / Sign In tap, and the steps never enter email/password credentials, do NOT heal by choosing Google/Apple/Facebook/SSO or another external app. If the test later expects Logout/session state, return test_invalid or prereq_unmet: the recorded test lacks a real credential setup.
86553
87228
  5. ENTRY-SCREEN DRIFT ("unexpected screen"/"screen drift"): the app started on a DIFFERENT screen than recorded; the fix is usually a MISSING NAVIGATION step (e.g. tap the onboarding/welcome CTA present in the tree before the recorded first step). Author it from the tree if you can (verdict fix); if a single static tree is insufficient, return needs_device.
@@ -86798,6 +87473,14 @@ For a fix, return the COMPLETE steps array (not a diff).
86798
87473
  function isIdentityEqualityXpath(value) {
86799
87474
  return /@[A-Za-z_:][-A-Za-z0-9_:.]*\s*=/.test(value) && !/(?:contains|starts-with)\s*\(/i.test(value);
86800
87475
  }
87476
+ var STEP_ACTIONS_NEEDING_ELEMENT = /* @__PURE__ */ new Set([
87477
+ "tap",
87478
+ "type",
87479
+ "clear",
87480
+ "waitForElement",
87481
+ "assertVisible",
87482
+ "assertText"
87483
+ ]);
86801
87484
  function stepLacksIdentityAnchor(step) {
86802
87485
  const metadata = step.metadata;
86803
87486
  if (metadata && (metadata.appContext === "WEBVIEW" || typeof metadata.webCss === "string"))
@@ -86838,7 +87521,7 @@ For a fix, return the COMPLETE steps array (not a diff).
86838
87521
  async function tryIdentityGateStaticRepair(steps, target, ctx, options) {
86839
87522
  if (!ctx.error || !IDENTITY_GATE_ERROR_RE.test(ctx.error))
86840
87523
  return null;
86841
- const identityless = steps.filter(stepLacksIdentityAnchor);
87524
+ const identityless = steps.filter((step) => STEP_ACTIONS_NEEDING_ELEMENT.has(step.action) && stepLacksIdentityAnchor(step));
86842
87525
  if (identityless.length === 0)
86843
87526
  return null;
86844
87527
  const isAssert = (step) => /^assert/i.test(step.action);
@@ -86849,7 +87532,8 @@ For a fix, return the COMPLETE steps array (not a diff).
86849
87532
  healReason: "identity gate: an action step carries no identity locator (accessibility id / resource id / text); the recording lacks the anchors replay requires \u2014 re-record the step"
86850
87533
  };
86851
87534
  }
86852
- const pruned = steps.filter((step) => !stepLacksIdentityAnchor(step));
87535
+ const identitylessOrders = new Set(identityless.map((step) => step.order));
87536
+ const pruned = steps.filter((step) => !identitylessOrders.has(step.order));
86853
87537
  if (pruned.length === 0 || !pruned.some(isAssert) || !options.runNativeTest) {
86854
87538
  return {
86855
87539
  passed: false,
@@ -86857,6 +87541,14 @@ For a fix, return the COMPLETE steps array (not a diff).
86857
87541
  healReason: "identity gate: the only assertion(s) carry no identity locator, so the test cannot prove its outcome as recorded \u2014 re-record with an identifiable anchor"
86858
87542
  };
86859
87543
  }
87544
+ const identityOracleRejection = (0, oracle_protection_js_1.rejectOracleWeakeningPatch)(steps, pruned);
87545
+ if (identityOracleRejection) {
87546
+ return {
87547
+ passed: false,
87548
+ verdict: "app_bug",
87549
+ healReason: `identity gate: pruning identity-less asserts would drop product oracles (${identityOracleRejection})`
87550
+ };
87551
+ }
86860
87552
  const reindexed = pruned.map((step, order) => ({ ...step, order }));
86861
87553
  try {
86862
87554
  const verify = await options.runNativeTest({ steps: reindexed, target, testVariables: ctx.testVariables });
@@ -87113,7 +87805,12 @@ ${safeLastError}`);
87113
87805
  ${args.directive}`);
87114
87806
  return parts.join("\n\n");
87115
87807
  }
87116
- function findFailingStepIndex(steps, error2) {
87808
+ function findFailingStepIndex(steps, error2, failedStepOrder) {
87809
+ if (typeof failedStepOrder === "number") {
87810
+ const exact = steps.findIndex((step) => step.order === failedStepOrder);
87811
+ if (exact >= 0)
87812
+ return exact;
87813
+ }
87117
87814
  const withTarget = steps.map((step, index) => ({ step, index })).filter((entry) => Boolean(entry.step.target?.primary));
87118
87815
  if (withTarget.length === 0)
87119
87816
  return -1;
@@ -87149,9 +87846,13 @@ ${args.directive}`);
87149
87846
  if (!runNativeTest || !options.selectorRegistryContext || !ctx.error)
87150
87847
  return null;
87151
87848
  const candidates = (0, selector_registry_context_js_1.collectMobileRegistryCandidates)(options.selectorRegistryContext);
87152
- const failingIndex = findFailingStepIndex(steps, ctx.error);
87849
+ const failingIndex = findFailingStepIndex(steps, ctx.error, ctx.failedStepOrder);
87153
87850
  if (failingIndex < 0)
87154
87851
  return null;
87852
+ if ((0, failure_triage_js_1.isOracleStep)(steps[failingIndex])) {
87853
+ options.onProgress?.(`Registry preflight skipped: step ${steps[failingIndex].order} is an oracle (${steps[failingIndex].action}) \u2014 a registry selector cannot stand in for a product outcome`);
87854
+ return null;
87855
+ }
87155
87856
  let tried = 0;
87156
87857
  for (const candidate of candidates) {
87157
87858
  if (tried >= REGISTRY_PREFLIGHT_MAX_CANDIDATES)
@@ -87161,6 +87862,8 @@ ${args.directive}`);
87161
87862
  continue;
87162
87863
  tried += 1;
87163
87864
  const healedSteps = substituteStepTarget(steps, failingIndex, candidate, mapped.locatorBundle);
87865
+ if ((0, oracle_protection_js_1.rejectOracleWeakeningPatch)(steps, healedSteps))
87866
+ continue;
87164
87867
  let verify;
87165
87868
  try {
87166
87869
  verify = await runNativeTest({ steps: healedSteps, target, testVariables: ctx.testVariables });
@@ -87486,6 +88189,41 @@ ${args.directive}`);
87486
88189
  async function executeMobileTestWithHealing2(steps, target, ctx, options) {
87487
88190
  return timed("total", "heal-total", options.onProgress, () => executeMobileTestWithHealingImpl(steps, target, ctx, options));
87488
88191
  }
88192
+ var TERMINAL_HEAL_VERDICTS = /* @__PURE__ */ new Set([
88193
+ "app_bug",
88194
+ "config_issue",
88195
+ "prereq_unmet",
88196
+ "state_stale",
88197
+ "test_invalid",
88198
+ "unhealable_dynamic"
88199
+ ]);
88200
+ function escalateFailedHealToTriage(steps, ctx, lastError) {
88201
+ const post = (0, failure_triage_js_1.triageMobileFailure)({
88202
+ steps,
88203
+ error: lastError ?? ctx.error,
88204
+ logs: ctx.logs,
88205
+ tags: ctx.tags,
88206
+ // Heal already ran and failed. Bump past the locator-miss heal window
88207
+ // so a remaining strong-oracle fail becomes APP_BUG, not silent FAILED.
88208
+ failureCount: Math.max(3, (ctx.failureCount ?? 1) + 1),
88209
+ failedStepOrder: ctx.failedStepOrder,
88210
+ // Heal ran and failed: a still-missing element is no longer "maybe drift".
88211
+ postHeal: true,
88212
+ uiSuccessWithFailedWriteApi: (0, network_oracle_js_1.uiSuccessWithFailedWriteApi)({
88213
+ apiCalls: ctx.apiCalls,
88214
+ uiPathSucceeded: ctx.uiPathSucceeded
88215
+ })
88216
+ });
88217
+ const term = (0, failure_triage_js_1.triageToHealTerminal)(post);
88218
+ if (!term)
88219
+ return null;
88220
+ return {
88221
+ passed: false,
88222
+ verdict: term.verdict,
88223
+ healReason: term.healReason,
88224
+ extraTags: term.extraTags
88225
+ };
88226
+ }
87489
88227
  async function executeMobileTestWithHealingImpl(steps, target, ctx, options) {
87490
88228
  const invalidAuthSetup = detectInvalidMobileAuthSetup(steps, ctx.error);
87491
88229
  if (invalidAuthSetup) {
@@ -87501,6 +88239,7 @@ ${args.directive}`);
87501
88239
  logs: ctx.logs,
87502
88240
  tags: ctx.tags,
87503
88241
  failureCount: ctx.failureCount,
88242
+ failedStepOrder: ctx.failedStepOrder,
87504
88243
  uiSuccessWithFailedWriteApi: networkBug
87505
88244
  });
87506
88245
  options.onProgress?.(`Pre-heal triage: ${triage.verdict} \u2014 ${triage.reason}`);
@@ -87558,6 +88297,17 @@ ${args.directive}`);
87558
88297
  if (live.providerUnavailable) {
87559
88298
  return await tryDeterministicProviderFallback({ steps, target, ctx, options }) ?? live;
87560
88299
  }
88300
+ if (!live.passed && !TERMINAL_HEAL_VERDICTS.has(live.verdict)) {
88301
+ const escalated = escalateFailedHealToTriage(steps, ctx, live.healReason ?? ctx.error);
88302
+ if (escalated) {
88303
+ return {
88304
+ ...live,
88305
+ ...escalated,
88306
+ healedSteps: live.healedSteps,
88307
+ healedAppiumCode: live.healedAppiumCode
88308
+ };
88309
+ }
88310
+ }
87561
88311
  return live;
87562
88312
  } catch {
87563
88313
  return {
@@ -87569,6 +88319,21 @@ ${args.directive}`);
87569
88319
  };
87570
88320
  }
87571
88321
  }
88322
+ if (!script.passed && !TERMINAL_HEAL_VERDICTS.has(script.verdict)) {
88323
+ const escalated = escalateFailedHealToTriage(steps, ctx, script.lastError ?? script.healReason ?? ctx.error);
88324
+ if (escalated) {
88325
+ return {
88326
+ passed: false,
88327
+ verdict: escalated.verdict,
88328
+ healedSteps: script.healedSteps,
88329
+ healedAppiumCode: script.healedAppiumCode,
88330
+ healReason: escalated.healReason,
88331
+ extraTags: escalated.extraTags,
88332
+ confidence: script.confidence,
88333
+ removeTags: script.removeTags
88334
+ };
88335
+ }
88336
+ }
87572
88337
  return {
87573
88338
  passed: script.passed,
87574
88339
  healedSteps: script.healedSteps,
@@ -87589,7 +88354,12 @@ The recorded flow may have expected a DIFFERENT starting screen than the one sho
87589
88354
  1. Compare the recorded first step's expected screen to the LIVE tree.
87590
88355
  2. If they differ, PREPEND the missing navigation step(s), authored from IDENTITY locators (resource-id, accessibility-id, or EXACT @text=) that are PRESENT in the LIVE tree \u2014 never a loose contains().
87591
88356
  3. If a locator is simply wrong, swap it for a stronger identity locator present in the LIVE tree.
87592
- 3b. If the failing step ASSERTS one-time / data-dependent UI (an empty-state CTA or first-run prompt) that is absent from the LIVE tree while the screen is otherwise correct, the assert is STALE \u2014 replace it with a durable element of the same screen (tab label, header, nav bar) and keep the rest.
88357
+ 3b. If the failing step ASSERTS a product outcome (empty-state CTA, confirmation, created/deleted row, validation text) that is absent from a healthy LIVE tree, return verdict "app_bug". Do NOT replace that assert with tab / header / nav chrome. Only retarget a locator when the SAME outcome copy is present in the live tree.
88358
+ ## Strong oracle protection (non-negotiable)
88359
+ - NEVER remove or downgrade assertStateDelta, captureState, or assertText outcome proof to go green.
88360
+ - NEVER replace a durable outcome assert with mere assertVisible of a tab/header.
88361
+ - You MAY fix locators, waits, and navigation around those oracles.
88362
+ - If the app truly violates the oracle on a healthy UI, return verdict "app_bug" instead of stripping the assert.
87593
88363
  4. If the prior failure says the foreground app changed outside the target app after a Login / Sign In tap, and the steps never enter email/password credentials, do NOT observe/tap Google/Apple/Facebook/SSO. For logout/session tests, return test_invalid or prereq_unmet because the recorded test lacks a real credential setup.
87594
88364
  5. If you cannot yet SEE the screen you need, use "observe" to advance ONE step, then you will be re-shown the new live screen.
87595
88365
  ## Response \u2014 STRICT JSON, exactly one verdict:
@@ -87598,7 +88368,7 @@ The recorded flow may have expected a DIFFERENT starting screen than the one sho
87598
88368
  {"verdict":"observe","action":{"type":"back"}}
87599
88369
  {"verdict":"observe","action":{"type":"relaunch"}}
87600
88370
  {"verdict":"observe","action":{"type":"reset"}} \u2190 clears app data + cold-relaunches: use when the app is in the WRONG STATE for the recorded flow (e.g. signed in when the test expects the cleared first-launch screens, stale onboarding, poisoned local state)
87601
- {"verdict":"app_bug","reason":"app crashed/blank/5xx (NOT rate-limit)"}
88371
+ {"verdict":"app_bug","reason":"product defect with durable oracle evidence (wrong entity, validation bypass, wrong count, missing confirmation) \u2014 NOT ANR/System UI"}
87602
88372
  {"verdict":"config_issue","reason":"429/rate limit/lockout/quota"}
87603
88373
  {"verdict":"needs_device","reason":"cannot resolve even with live access"}
87604
88374
  {"verdict":"prereq_unmet","reason":"required entity/state absent for the account"}
@@ -91665,7 +92435,7 @@ var require_kill_tree = __commonJS({
91665
92435
  var node_child_process_1 = __require("child_process");
91666
92436
  var node_util_1 = __require("util");
91667
92437
  var node_fs_1 = __require("fs");
91668
- var execFileAsync4 = (0, node_util_1.promisify)(node_child_process_1.execFile);
92438
+ var execFileAsync5 = (0, node_util_1.promisify)(node_child_process_1.execFile);
91669
92439
  var PS_TIMEOUT_MS = 2e3;
91670
92440
  var PS_BUFFER = 1024 * 1024;
91671
92441
  async function gracefulCloseWithTreeKill(options) {
@@ -91719,7 +92489,7 @@ var require_kill_tree = __commonJS({
91719
92489
  timer.unref?.();
91720
92490
  let stdout;
91721
92491
  try {
91722
- const result = await execFileAsync4("ps", ["-A", "-o", "pid=,ppid=,command="], {
92492
+ const result = await execFileAsync5("ps", ["-A", "-o", "pid=,ppid=,command="], {
91723
92493
  maxBuffer: PS_BUFFER,
91724
92494
  signal: controller.signal
91725
92495
  });
@@ -91757,7 +92527,7 @@ var require_kill_tree = __commonJS({
91757
92527
  timer.unref?.();
91758
92528
  let stdout;
91759
92529
  try {
91760
- const result = await execFileAsync4("ps", ["-A", "-o", "pid=,ppid=,command="], {
92530
+ const result = await execFileAsync5("ps", ["-A", "-o", "pid=,ppid=,command="], {
91761
92531
  maxBuffer: PS_BUFFER,
91762
92532
  signal: controller.signal
91763
92533
  });
@@ -91834,7 +92604,7 @@ var require_kill_tree = __commonJS({
91834
92604
  timer.unref?.();
91835
92605
  let stdout;
91836
92606
  try {
91837
- const result = await execFileAsync4("ps", ["-A", "-o", "pid=,ppid="], {
92607
+ const result = await execFileAsync5("ps", ["-A", "-o", "pid=,ppid="], {
91838
92608
  maxBuffer: PS_BUFFER,
91839
92609
  signal: controller.signal
91840
92610
  });
@@ -101410,13 +102180,12 @@ Every assertion in the generated test must be proven live.
101410
102180
  **Frame**
101411
102181
  - \`import { test, expect } from '@playwright/test'\` with tags [${tagLiteral}].
101412
102182
  - Credentials: \`process.env.TEST_USER_EMAIL!\` / \`process.env.TEST_USER_PASSWORD!\` \u2014 never hardcode. ${emailVerifyArmed ? `Registration uses \`process.env.${test_inbox_broker_js_1.TEST_INBOX_EMAIL_ENV}!\` (the fresh real inbox address the runner mints per run \u2014 it RECEIVES the verification email; see the EMAIL VERIFICATION TEST section) with \`process.env.${test_inbox_broker_js_1.TEST_INBOX_PASSWORD_ENV}!\`. Do NOT register with an \`@example.com\` address \u2014 that domain receives no mail and email verification will hang.` : `Registration uses \`testuser-\${Date.now()}@example.com\`.`}
101413
- - **Credential rotation (rare \u2014 read carefully):** emit \`persistCredential\` ONLY when the scenario:
101414
- (a) logs in as the STORED test user (the test uses \`process.env.TEST_USER_PASSWORD\` to log in \u2014 i.e. the credential listed under the Browser Credentials section above), AND
101415
- (b) successfully rotates THAT SAME user's credential (e.g. user opens *their own* settings \u2192 Change Password \u2192 submits \u2192 success toast), AND
101416
- (c) the test has an assertion proving the change took effect.
101417
- When all three hold, generate a fresh value into a local const (\`const newPassword = \\\`Pw-\\\${Date.now()}-\\\${Math.random().toString(36).slice(2, 8)}!\\\`\`), fill it into the new-password / confirm fields, submit, verify success, THEN add: \`import { persistCredential } from '../setup/credentials';\` at the top and \`await persistCredential('TEST_USER_PASSWORD', newPassword, 'short reason');\` as the LAST statement in the test body. Also add the tag \`@mutates-credential:TEST_USER_PASSWORD\` to the test options array. Adjust the relative path of the import to match the spec's location (e.g. \`'../../setup/credentials'\` for deeply-nested specs).
101418
- - **Do NOT emit \`persistCredential\` when:** (i) the scenario registers a fresh user (${emailVerifyArmed ? `e.g. the runner-minted \`process.env.${test_inbox_broker_js_1.TEST_INBOX_EMAIL_ENV}!\` inbox account` : `e.g. \`testuser-\${Date.now()}@example.com\``}) and rotates THAT user's password \u2014 the fresh user is throwaway, the stored credential is untouched; (ii) the scenario is a negative test verifying a bad-password / mismatched-confirm / empty-field / permission-denied case; (iii) the scenario only fills form validation paths without a successful submit. In all these cases simply omit the call.
101419
- - **Restore-inline is FORBIDDEN for the stored user.** Never "change the stored user's password to a temp value, then change it back to the old one" as plain sequential statements. The change mutates the LIVE account immediately; if any later step (the second navigation, the restore submit, the success assertion) fails, the live password stays at the temp value while \`process.env.TEST_USER_PASSWORD\` still holds the old one \u2014 and every other auth test then fails to log in. The ONLY supported way to mutate the stored user's password is rotate-FORWARD via \`persistCredential\` (above): change it to a fresh value, verify success, and write that SAME final value back as the last statement. Do NOT restore the old password, and do NOT introduce a temp-then-revert sequence.
102183
+ - **Credential rotation (REQUIRED when the STORED user's password changes):** emit \`persistCredential\` whenever the scenario successfully changes the password (or other secret) of the STORED test user \u2014 the account identified by \`process.env.TEST_USER_EMAIL!\` / \`process.env.TEST_USER_PASSWORD!\` (the credentials listed under Browser Credentials above). This includes BOTH:
102184
+ (a) **In-session change password** \u2014 log in as the stored user, open *their own* settings \u2192 Change Password \u2192 submit \u2192 success assertion; AND
102185
+ (b) **Forgot-password / password-reset of the stored user** \u2014 request a reset for \`process.env.TEST_USER_EMAIL!\` (logged-out is fine), complete the emailed link/code, set a NEW password on the reset form, and assert success. You do NOT need a prior login with the old password \u2014 a successful reset of the stored account still MUST write the new password back so the Test Data page stays correct and later tests do not fail with stale credentials.
102186
+ When either case holds, generate a fresh value into a local const (\`const newPassword = \\\`Pw-\\\${Date.now()}-\\\${Math.random().toString(36).slice(2, 8)}!\\\`\`), fill it into the new-password / confirm fields, submit, verify success, THEN add: \`import { persistCredential } from '../setup/credentials';\` at the top and \`await persistCredential('TEST_USER_PASSWORD', newPassword, 'short reason');\` as the LAST statement in the test body (after the final assertion is fine only if the assertion does not depend on the write-back; prefer write-back immediately after the success proof). Also add the tag \`@mutates-credential:TEST_USER_PASSWORD\` to the test options array. Adjust the relative path of the import to match the spec's location (e.g. \`'../../setup/credentials'\` for deeply-nested specs).
102187
+ - **Do NOT emit \`persistCredential\` when:** (i) the scenario registers a fresh throwaway user (${emailVerifyArmed ? `e.g. the runner-minted \`process.env.${test_inbox_broker_js_1.TEST_INBOX_EMAIL_ENV}!\` inbox account` : `e.g. \`testuser-\${Date.now()}@example.com\``}) and rotates THAT user's password \u2014 the fresh user is throwaway, the stored credential is untouched; (ii) the scenario is a negative test verifying a bad-password / mismatched-confirm / empty-field / permission-denied case; (iii) the scenario only fills form validation paths without a successful submit; (iv) the scenario only requests a reset email without completing the reset and setting a new password. In all these cases simply omit the call.
102188
+ - **Restore-inline is FORBIDDEN for the stored user.** Never "change the stored user's password to a temp value, then change it back to the old one" as plain sequential statements. The change mutates the LIVE account immediately; if any later step (the second navigation, the restore submit, the success assertion) fails, the live password stays at the temp value while \`process.env.TEST_USER_PASSWORD\` still holds the old one \u2014 and every other auth test then fails to log in. The ONLY supported way to mutate the stored user's password is rotate-FORWARD via \`persistCredential\` (above): change it to a fresh value, verify success, and write that SAME final value back as the last write-back statement. Do NOT restore the old password, and do NOT introduce a temp-then-revert sequence.
101420
102189
  - **Start every test from \`${scenarioEntryRoute}\`.** ${hasVerifiedRecipe ? "Your first body line is the injected `await __vqaLogin(page);` \u2014 login is handled for you. After it, reach feature pages by clicking visible nav or a direct goto to the scenario route." : `First line: \`await page.goto('${scenarioEntryRoute}', { waitUntil: 'domcontentloaded' })\`. You are logged OUT; if the route redirects, that proves you must authenticate FIRST via the visible login flow \u2014 never \`waitForURL\` on a post-login route before submitting credentials.`} Do NOT deep-link to \`/login\` or \`/dashboard/...\` before login; reach feature pages by clicking visible nav (sidebar / topbar / link / button) like a user would.
101421
102190
  - ${hasVerifiedRecipe ? "Auth is proven inside `__vqaLogin` \u2014 do NOT add your own login or auth-proof assertion; focus your assertions on the feature outcome." : tags.includes("@needs-auth") ? "For `@needs-auth` scenarios, add one auth-proof assertion before feature steps: prefer Logout button, then avatar/menu, authenticated sidebar/nav, or a stable post-login heading. Never use user email, time-of-day greetings, display name text, personalized headings, or redirect alone." : "Use stable assertions tied to the current flow \u2014 avoid personalized or account-specific copy when a structural proof exists."}
101422
102191
  - Always \`await\` on \`expect()\`. Never use \`test.tags()\` as a method \u2014 tags go in the options object.
@@ -102030,7 +102799,7 @@ Fix EVERY flagged locator, keep every other line exactly as-is, then submit the
102030
102799
  }
102031
102800
  const verifyCallsSinceLastFinish = verifyCallCount - verifyCallsAtLastFinishGenerate;
102032
102801
  verifyCallsAtLastFinishGenerate = verifyCallCount;
102033
- const bugWitnessEnabled = (0, shared_1.parseBoolFlag)(process.env.DISCOVERY_BUG_WITNESS_ENABLED);
102802
+ const bugWitnessEnabled = (0, shared_1.parseBoolFlag)(process.env.DISCOVERY_BUG_WITNESS_ENABLED, true);
102034
102803
  const bugWitnessVerdict = bugWitnessEnabled ? resolveSuspectedBugVerdict(suspectedBugDeclared, bugDescription, verifyCallsSinceLastFinish, strengthVerdict?.signals) : null;
102035
102804
  if (bugWitnessVerdict) {
102036
102805
  strengthVerdict = bugWitnessVerdict;
@@ -338920,6 +339689,10 @@ Explore complete: ${explore.exploreStats.pagesDiscovered} screens, ${explore.exp
338920
339689
  appId,
338921
339690
  platform: platform3,
338922
339691
  appBrief: ctx.appBrief,
339692
+ // Optional project docs / knowledge facts — empty is valid; planner
339693
+ // relies on live explorer evidence when absent (bug capture does not
339694
+ // require documents).
339695
+ knowledgeContext: ctx.knowledgeContext,
338923
339696
  featureName: ctx.featureName,
338924
339697
  existingTestNames: ctx.existingTestNames,
338925
339698
  existingFeatureNames: ctx.existingFeatureNames,
@@ -349080,7 +349853,7 @@ var require_update = __commonJS({
349080
349853
  var require_opts_arg = __commonJS({
349081
349854
  "../../node_modules/tar/node_modules/mkdirp/lib/opts-arg.js"(exports, module) {
349082
349855
  "use strict";
349083
- var { promisify: promisify4 } = __require("util");
349856
+ var { promisify: promisify5 } = __require("util");
349084
349857
  var fs = __require("fs");
349085
349858
  var optsArg = (opts) => {
349086
349859
  if (!opts)
@@ -349094,9 +349867,9 @@ var require_opts_arg = __commonJS({
349094
349867
  else
349095
349868
  throw new TypeError("invalid options argument");
349096
349869
  opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir;
349097
- opts.mkdirAsync = promisify4(opts.mkdir);
349870
+ opts.mkdirAsync = promisify5(opts.mkdir);
349098
349871
  opts.stat = opts.stat || opts.fs.stat || fs.stat;
349099
- opts.statAsync = promisify4(opts.stat);
349872
+ opts.statAsync = promisify5(opts.stat);
349100
349873
  opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync;
349101
349874
  opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync;
349102
349875
  return opts;
@@ -353945,7 +354718,7 @@ var require_process_inventory = __commonJS({
353945
354718
  var node_child_process_1 = __require("child_process");
353946
354719
  var node_os_1 = __importDefault(__require("os"));
353947
354720
  var node_util_1 = __require("util");
353948
- var execFileAsync4 = (0, node_util_1.promisify)(node_child_process_1.execFile);
354721
+ var execFileAsync5 = (0, node_util_1.promisify)(node_child_process_1.execFile);
353949
354722
  var DEFAULT_LIMIT = 60;
353950
354723
  var DEFAULT_TIMEOUT_MS2 = 800;
353951
354724
  var MAX_COMMAND_LENGTH = 320;
@@ -354007,7 +354780,7 @@ var require_process_inventory = __commonJS({
354007
354780
  const timer = setTimeout(() => controller.abort(), timeoutMs);
354008
354781
  timer.unref?.();
354009
354782
  try {
354010
- const { stdout } = await execFileAsync4(command, args, {
354783
+ const { stdout } = await execFileAsync5(command, args, {
354011
354784
  maxBuffer: 1024 * 1024,
354012
354785
  signal: controller.signal
354013
354786
  });
@@ -355301,7 +356074,7 @@ var require_package4 = __commonJS({
355301
356074
  "package.json"(exports, module) {
355302
356075
  module.exports = {
355303
356076
  name: "@validate.qa/runner",
355304
- version: "1.0.91",
356077
+ version: "1.0.92",
355305
356078
  description: "validate local test runner - execute Playwright tests on your machine, connected to validate.qa cloud.",
355306
356079
  bin: {
355307
356080
  "validate-runner": "dist/cli.js"
@@ -356166,11 +356939,7 @@ var SYSTEM_UI_DISMISS_LABELS = [
356166
356939
  "OK",
356167
356940
  "Got it",
356168
356941
  "GOT IT",
356169
- "Continue",
356170
- "Close",
356171
356942
  "Dismiss",
356172
- "I understand",
356173
- "Accept",
356174
356943
  // Android 15+ / 16 KB page-size compatibility dialog primary action.
356175
356944
  "OK, got it"
356176
356945
  ];
@@ -360100,7 +360869,11 @@ async function executeAssertVisible(sessionId, step, platform3, isCrossPlatform
360100
360869
  tolerateAmbiguity: true
360101
360870
  });
360102
360871
  const result2 = await wdRequest(`${sessionPath}/element/${elementId2}/displayed`);
360103
- if (!result2?.value) throw new Error(`WEBVIEW element found but not visible: css=${css}`);
360872
+ if (!result2?.value) {
360873
+ throw new Error(
360874
+ `Assertion failed: expected "${css}" to be visible, but the WEBVIEW element resolved and is not displayed`
360875
+ );
360876
+ }
360104
360877
  });
360105
360878
  return;
360106
360879
  }
@@ -360112,7 +360885,9 @@ async function executeAssertVisible(sessionId, step, platform3, isCrossPlatform
360112
360885
  });
360113
360886
  const result = await wdRequest(`/session/${sessionId}/element/${elementId}/displayed`);
360114
360887
  if (!result?.value) {
360115
- throw new Error(`Element found but not visible: ${step.target?.primary ?? "unknown"}`);
360888
+ throw new Error(
360889
+ `Assertion failed: expected "${step.target?.primary ?? "element"}" to be visible, but it resolved and is not displayed`
360890
+ );
360116
360891
  }
360117
360892
  }
360118
360893
  async function executeAssertText(sessionId, step, platform3, isCrossPlatform = false) {
@@ -362641,6 +363416,26 @@ function getMirrorSessionId(deviceId) {
362641
363416
  // src/services/mobile/mobile-bridge-driver.ts
362642
363417
  var import_runner_core9 = __toESM(require_dist2());
362643
363418
  init_dist();
363419
+ import { execFile as execFile4 } from "child_process";
363420
+ import { promisify as promisify4 } from "util";
363421
+ var execFileAsync4 = promisify4(execFile4);
363422
+ async function clearAndroidAppDataViaAdb(deviceId, appId) {
363423
+ const serial = deviceId?.trim();
363424
+ const pkg2 = appId?.trim();
363425
+ if (!serial || !pkg2 || !serial.startsWith("emulator-")) return false;
363426
+ try {
363427
+ const { stdout, stderr } = await execFileAsync4(
363428
+ "adb",
363429
+ ["-s", serial, "shell", "pm", "clear", pkg2],
363430
+ { timeout: 2e4, maxBuffer: 64 * 1024 }
363431
+ );
363432
+ const out = `${stdout ?? ""}
363433
+ ${stderr ?? ""}`.toLowerCase();
363434
+ return out.includes("success");
363435
+ } catch {
363436
+ return false;
363437
+ }
363438
+ }
362644
363439
  var APPIUM_SESSION_ID_PATTERN2 = /^[a-f0-9-]{1,64}$/i;
362645
363440
  function isRecoverableAppiumSessionFailure(err) {
362646
363441
  if (isAppiumDriverDeadError(err)) return true;
@@ -363039,7 +363834,17 @@ var MobileBridgeDriver = class {
363039
363834
  throw new Error(`iOS simulator app-data reset failed: ${wiped.detail}`);
363040
363835
  }
363041
363836
  } else {
363042
- await this.executeScript("mobile: clearApp", [{ appId: this.appId }]);
363837
+ const adbFirst = await clearAndroidAppDataViaAdb(this.deviceId, this.appId);
363838
+ if (!adbFirst) {
363839
+ try {
363840
+ await this.executeScript("mobile: clearApp", [{ appId: this.appId }]);
363841
+ } catch (clearErr) {
363842
+ const adbCleared = await clearAndroidAppDataViaAdb(this.deviceId, this.appId);
363843
+ if (!adbCleared) {
363844
+ throw clearErr;
363845
+ }
363846
+ }
363847
+ }
363043
363848
  }
363044
363849
  await this.executeScript("mobile: activateApp", [this.appLifecycleArgs()]);
363045
363850
  try {
@@ -364271,10 +365076,28 @@ function truncateAuditRequestBody(body) {
364271
365076
  function isTerminalAuditStatus(status) {
364272
365077
  return status === 400 || status === 404 || status === 409 || status === 413;
364273
365078
  }
365079
+ var AuditDrainError = class extends Error {
365080
+ constructor(message, dropped) {
365081
+ super(message);
365082
+ this.dropped = dropped;
365083
+ this.name = "AuditDrainError";
365084
+ }
365085
+ };
365086
+ function auditDroppedFromDrainFailure(reason) {
365087
+ if (reason instanceof AuditDrainError) return reason.dropped;
365088
+ if (reason && typeof reason === "object" && "dropped" in reason) {
365089
+ const dropped = reason.dropped;
365090
+ if (typeof dropped === "number" && Number.isFinite(dropped)) {
365091
+ return Math.max(0, Math.floor(dropped));
365092
+ }
365093
+ }
365094
+ return 0;
365095
+ }
364274
365096
  function createAuditFlusher(url, headers) {
364275
365097
  const entries = [];
364276
365098
  let byteEstimate = 0;
364277
365099
  let flushInFlight = null;
365100
+ let droppedTotal = 0;
364278
365101
  const doFlush = () => {
364279
365102
  if (entries.length === 0) return Promise.resolve();
364280
365103
  if (flushInFlight) return flushInFlight;
@@ -364297,9 +365120,16 @@ function createAuditFlusher(url, headers) {
364297
365120
  body: JSON.stringify({ entries: toSend.map((e) => e.entry) }),
364298
365121
  signal: AbortSignal.timeout(3e4)
364299
365122
  });
364300
- if (res.ok) continue;
365123
+ if (res.ok) {
365124
+ const ack = await res.json().catch(() => null);
365125
+ if (typeof ack?.dropped === "number" && Number.isFinite(ack.dropped)) {
365126
+ droppedTotal += Math.max(0, Math.floor(ack.dropped));
365127
+ }
365128
+ continue;
365129
+ }
364301
365130
  if (isTerminalAuditStatus(res.status)) {
364302
365131
  console.warn(`[audit-flush] HTTP ${res.status} (terminal) - dropping ${toSend.length} audit entries`);
365132
+ droppedTotal += toSend.length;
364303
365133
  continue;
364304
365134
  }
364305
365135
  entries.unshift(...toSend);
@@ -364339,6 +365169,7 @@ function createAuditFlusher(url, headers) {
364339
365169
  droppedCount++;
364340
365170
  }
364341
365171
  console.warn(`[audit-flush] queue over ${AUDIT_QUEUE_MAX_BYTES} bytes - dropped ${droppedCount} oldest audit entries`);
365172
+ droppedTotal += droppedCount;
364342
365173
  }
364343
365174
  if (entries.length >= AUDIT_FLUSH_COUNT || byteEstimate >= AUDIT_FLUSH_BYTES) {
364344
365175
  void doFlush();
@@ -364347,16 +365178,20 @@ function createAuditFlusher(url, headers) {
364347
365178
  const drain = async () => {
364348
365179
  for (let attempt = 1; attempt <= AUDIT_DRAIN_ATTEMPTS; attempt++) {
364349
365180
  if (flushInFlight) await flushInFlight;
364350
- if (entries.length === 0) return;
365181
+ if (entries.length === 0) return { dropped: droppedTotal };
364351
365182
  await doFlush();
364352
- if (entries.length === 0) return;
365183
+ if (entries.length === 0) return { dropped: droppedTotal };
364353
365184
  if (attempt < AUDIT_DRAIN_ATTEMPTS) {
364354
365185
  await new Promise((resolve2) => setTimeout(resolve2, AUDIT_DRAIN_DELAY_MS * attempt));
364355
365186
  }
364356
365187
  }
364357
365188
  if (entries.length > 0) {
364358
- throw new Error(`audit drain failed after ${AUDIT_DRAIN_ATTEMPTS} attempts - ${entries.length} entries could not be flushed to ${url}`);
365189
+ throw new AuditDrainError(
365190
+ `audit drain failed after ${AUDIT_DRAIN_ATTEMPTS} attempts - ${entries.length} entries could not be flushed to ${url}`,
365191
+ droppedTotal + entries.length
365192
+ );
364359
365193
  }
365194
+ return { dropped: droppedTotal };
364360
365195
  };
364361
365196
  return { push, drain };
364362
365197
  }
@@ -365605,7 +366440,7 @@ ${finalVerifyResult.logs ?? ""}`;
365605
366440
  log.warn("[stream] discovery-plan failed after 3 attempts - plan checkpoint skipped");
365606
366441
  };
365607
366442
  let discoveryResult;
365608
- const buildFinalBody = (r, overrideError, auditWarning) => {
366443
+ const buildFinalBody = (r, overrideError, auditWarning, auditDroppedCount = 0) => {
365609
366444
  const isNativeDiscovery = ctx.medium === "IOS_NATIVE" || ctx.medium === "ANDROID_NATIVE";
365610
366445
  const { exploreFinalMessages: _exploreFinalMessages, ...rest } = r;
365611
366446
  void _exploreFinalMessages;
@@ -365618,6 +366453,7 @@ ${finalVerifyResult.logs ?? ""}`;
365618
366453
  summary: rest.summary,
365619
366454
  mode: rest.mode,
365620
366455
  error: overrideError ?? rest.error,
366456
+ auditDroppedCount,
365621
366457
  // Resumable-pause checkpoint: native deep generation tripped the AI-overload breaker.
365622
366458
  // Without forwarding these, the server's isDiscoveryPaused is false → the run finalizes
365623
366459
  // COMPLETED/FAILED instead of PAUSED → the Resume affordance never appears for
@@ -366003,12 +366839,13 @@ ${finalVerifyResult.logs ?? ""}`;
366003
366839
  discoveryAuditWarning = `[audit] ${drainErr instanceof Error ? drainErr.message : String(drainErr)}`;
366004
366840
  console.warn(`[runner] ${discoveryAuditWarning}`);
366005
366841
  }
366842
+ const auditDroppedCount = drainOutcome.status === "fulfilled" ? drainOutcome.value.dropped : auditDroppedFromDrainFailure(drainOutcome.reason);
366006
366843
  const harStatus = harOutcome.status === "fulfilled" ? harOutcome.value : null;
366007
366844
  harPosted = decideHarPosted(harStatus !== null ? { status: harStatus } : null);
366008
366845
  if (!harPosted) {
366009
366846
  log.warn("[runner] discovery-har POST failed - final /discovery-result will carry HAR fallback");
366010
366847
  }
366011
- const finalBody = buildFinalBody(discoveryResult, void 0, discoveryAuditWarning || void 0);
366848
+ const finalBody = buildFinalBody(discoveryResult, void 0, discoveryAuditWarning || void 0, auditDroppedCount);
366012
366849
  let postOk = false;
366013
366850
  for (let attempt = 0; attempt < 3; attempt++) {
366014
366851
  const timeoutMs = attempt === 0 ? 12e4 : 3e4;
@@ -366042,14 +366879,16 @@ ${finalVerifyResult.logs ?? ""}`;
366042
366879
  const msg = err instanceof Error ? err.message : String(err);
366043
366880
  log.fail(`Discovery FAILED: ${msg}`);
366044
366881
  let drainMsg = "";
366882
+ let auditDroppedCount = 0;
366045
366883
  try {
366046
- await drainAudit();
366884
+ auditDroppedCount = (await drainAudit()).dropped;
366047
366885
  } catch (drainErr) {
366886
+ auditDroppedCount = auditDroppedFromDrainFailure(drainErr);
366048
366887
  drainMsg = `
366049
366888
  [audit] ${drainErr instanceof Error ? drainErr.message : String(drainErr)}`;
366050
366889
  console.warn(`[runner]${drainMsg}`);
366051
366890
  }
366052
- const errorBody = discoveryResult ? buildFinalBody(discoveryResult, msg, drainMsg || void 0) : prepareDiscoveryResultForPost({
366891
+ const errorBody = discoveryResult ? buildFinalBody(discoveryResult, msg, drainMsg || void 0, auditDroppedCount) : prepareDiscoveryResultForPost({
366053
366892
  ...explorePosted ? {} : { collectedPages: [], collectedTransitions: [] },
366054
366893
  tests: [],
366055
366894
  logs: `Fatal error: ${msg}${drainMsg}`,
@@ -366057,6 +366896,7 @@ ${finalVerifyResult.logs ?? ""}`;
366057
366896
  summary: `Fatal error: ${msg}`,
366058
366897
  exploreStats: { pagesDiscovered: 0, pagesVisited: 0, elementsFound: 0, transitionsFound: 0 },
366059
366898
  duration: (Date.now() - startTime) / 1e3,
366899
+ auditDroppedCount,
366060
366900
  mode: ctx.mode,
366061
366901
  error: msg,
366062
366902
  streamedTestCount: streamedTestKeys.size,
@@ -366422,6 +367262,7 @@ ${finalVerifyResult.logs ?? ""}`;
366422
367262
  status: typeof c.status === "number" ? c.status : void 0
366423
367263
  })) : void 0;
366424
367264
  const uiPathSucceeded = Array.isArray(reproduce.stepResults) && reproduce.stepResults.filter((s) => s.status === "passed").length >= Math.max(1, reproduce.stepResults.length - 1);
367265
+ const failedStepOrder = Array.isArray(reproduce.stepResults) ? reproduce.stepResults.find((s) => s.status === "failed")?.stepOrder : void 0;
366425
367266
  const heal = await (0, import_runner_core14.executeMobileTestWithHealing)(
366426
367267
  mobileSteps,
366427
367268
  healTarget,
@@ -366433,6 +367274,7 @@ ${finalVerifyResult.logs ?? ""}`;
366433
367274
  testName: run2.testName,
366434
367275
  tags: tagList,
366435
367276
  failureCount,
367277
+ failedStepOrder,
366436
367278
  apiCalls: reproduceApiCalls,
366437
367279
  uiPathSucceeded
366438
367280
  },