@validate.qa/runner 1.0.24 → 1.0.26

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 +1331 -293
  2. package/dist/cli.mjs +1331 -293
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -681,6 +681,8 @@ var require_mobile_source_parser = __commonJS({
681
681
  exports2.buildLocatorBundle = buildLocatorBundle;
682
682
  exports2.preferredLocator = preferredLocator;
683
683
  exports2.parseMobileSource = parseMobileSource2;
684
+ exports2.resolveLocatorAgainstScreenDetailed = resolveLocatorAgainstScreenDetailed;
685
+ exports2.resolveLocatorAgainstScreen = resolveLocatorAgainstScreen;
684
686
  var IOS_ACTIONABLE_ROLE_SUFFIXES = [
685
687
  "Button",
686
688
  "TextField",
@@ -1084,6 +1086,106 @@ var require_mobile_source_parser = __commonJS({
1084
1086
  windowSize: null
1085
1087
  };
1086
1088
  }
1089
+ var XPATH_IDENTITY_TEXT_ATTRS = /* @__PURE__ */ new Set([
1090
+ "text",
1091
+ "content-desc",
1092
+ "label",
1093
+ "name",
1094
+ "value"
1095
+ ]);
1096
+ function elementValuesForXpathAttr(el, attr) {
1097
+ if (attr === "resource-id")
1098
+ return [el.resourceId];
1099
+ if (attr === "class")
1100
+ return [el.role];
1101
+ if (XPATH_IDENTITY_TEXT_ATTRS.has(attr))
1102
+ return [el.text, el.accessibilityId, el.label];
1103
+ return [];
1104
+ }
1105
+ function elementCarriesIdentityText(el, value) {
1106
+ return el.text === value || el.accessibilityId === value || el.label === value;
1107
+ }
1108
+ function parseXpathClauses(xpath) {
1109
+ const clauses = [];
1110
+ const seen = /* @__PURE__ */ new Set();
1111
+ const push = (attr, value, matchKind) => {
1112
+ const key = `${attr}\0${value}\0${matchKind}`;
1113
+ if (seen.has(key))
1114
+ return;
1115
+ seen.add(key);
1116
+ clauses.push({ attr, value, matchKind });
1117
+ };
1118
+ const fnRe = /\b(contains|starts-with)\s*\(\s*@([A-Za-z_][\w.:-]*)\s*,\s*("([^"]*)"|'([^']*)')\s*\)/gi;
1119
+ let m;
1120
+ while ((m = fnRe.exec(xpath)) !== null) {
1121
+ const kind = m[1].toLowerCase() === "contains" ? "contains" : "starts-with";
1122
+ const value = m[4] ?? m[5] ?? "";
1123
+ push(m[2], value, kind);
1124
+ }
1125
+ const eqRe = /@([A-Za-z_][\w.:-]*)\s*=\s*("([^"]*)"|'([^']*)')/g;
1126
+ while ((m = eqRe.exec(xpath)) !== null) {
1127
+ const value = m[3] ?? m[4] ?? "";
1128
+ push(m[1], value, "exact");
1129
+ }
1130
+ return clauses;
1131
+ }
1132
+ function elementMatchesClause(el, clause) {
1133
+ const values = elementValuesForXpathAttr(el, clause.attr);
1134
+ return values.some((v) => {
1135
+ if (v === void 0)
1136
+ return false;
1137
+ if (clause.matchKind === "contains")
1138
+ return v.includes(clause.value);
1139
+ if (clause.matchKind === "starts-with")
1140
+ return v.startsWith(clause.value);
1141
+ return v === clause.value;
1142
+ });
1143
+ }
1144
+ function matchXpath(xpath, elements) {
1145
+ const clauses = parseXpathClauses(xpath);
1146
+ if (clauses.length === 0)
1147
+ return { elements: [], exact: false };
1148
+ const matched = elements.filter((el) => clauses.some((c) => elementMatchesClause(el, c)));
1149
+ const exact = clauses.every((c) => c.matchKind === "exact");
1150
+ return { elements: matched, exact };
1151
+ }
1152
+ function resolveLocatorAgainstScreenDetailed(candidate, screen) {
1153
+ const elements = screen.elements;
1154
+ const accId = candidate.accessibilityId?.trim();
1155
+ if (accId) {
1156
+ const matches = elements.filter((el) => el.accessibilityId === accId);
1157
+ if (matches.length > 0)
1158
+ return { elements: matches, strategy: "accessibilityId", exact: true };
1159
+ }
1160
+ const resId = candidate.resourceId?.trim();
1161
+ if (resId) {
1162
+ const matches = elements.filter((el) => el.resourceId === resId);
1163
+ if (matches.length > 0)
1164
+ return { elements: matches, strategy: "resourceId", exact: true };
1165
+ }
1166
+ const text = candidate.text?.trim();
1167
+ if (text) {
1168
+ const matches = elements.filter((el) => elementCarriesIdentityText(el, text));
1169
+ if (matches.length > 0)
1170
+ return { elements: matches, strategy: "text", exact: true };
1171
+ }
1172
+ const xpath = candidate.xpath?.trim();
1173
+ if (xpath) {
1174
+ const res = matchXpath(xpath, elements);
1175
+ if (res.elements.length > 0)
1176
+ return { elements: res.elements, strategy: "xpath", exact: res.exact };
1177
+ }
1178
+ const className = candidate.className?.trim();
1179
+ if (className) {
1180
+ const matches = elements.filter((el) => el.role === className);
1181
+ if (matches.length > 0)
1182
+ return { elements: matches, strategy: "className", exact: true };
1183
+ }
1184
+ return { elements: [], strategy: "none", exact: false };
1185
+ }
1186
+ function resolveLocatorAgainstScreen(candidate, screen) {
1187
+ return resolveLocatorAgainstScreenDetailed(candidate, screen).elements;
1188
+ }
1087
1189
  }
1088
1190
  });
1089
1191
 
@@ -62139,7 +62241,7 @@ Rules:
62139
62241
  - Register ONCE per run. If signup says the account ALREADY exists, log in with that email + the \`${opts.passwordKey}\` password instead of registering again.
62140
62242
  - Only call the verification tools AFTER submitting the signup form; pass the app as \`senderMatch\` (the inbox is shared).`;
62141
62243
  }
62142
- function buildSystemPrompt(mode, platform3, enableRecordJourney, maxIterations, appBrief, targetAppId, existingScreens) {
62244
+ function buildSystemPrompt(mode, platform3, enableRecordJourney, maxIterations, appBrief, targetAppId, existingScreens, incremental) {
62143
62245
  const platformLabel = platform3 === "IOS" ? "iOS" : "Android";
62144
62246
  const targetLine = targetAppId ? ` Target app package/bundle: ${targetAppId}.` : "";
62145
62247
  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.
@@ -62149,13 +62251,12 @@ Rules:
62149
62251
  - Every element is addressed by a ref like e1, e2. **Refs are ONLY valid for the most recent mobile_snapshot.** Re-snapshot after every action that changes the screen, then use the NEW refs.
62150
62252
  - mobile_tap/mobile_type/mobile_clear take a ref. The loop resolves the ref to coordinates for you \u2014 you never pass coordinates.
62151
62253
 
62152
- ## Strategy
62153
- 1. mobile_snapshot the launch screen.
62154
- 2. capture_screen to record it (name + type). Then record_transition when you move between screens.
62155
- 3. Systematically open every navigation target: tabs, list rows (open ONE per list \u2014 they share a template), menus, drawers.
62156
- 4. Use mobile_swipe up/down to reveal off-screen content and scroll long screens.
62157
- 5. mobile_back to return; mobile_relaunch only for a clean restart between episodes.
62158
- 6. When no new screens remain, call finish_exploration.
62254
+ ## Strategy \u2014 three phases, in order
62255
+ **Phase 1 \u2014 Logged-out entry (be quick, ~15% of budget).** mobile_snapshot the launch screen, capture_screen it, and capture each distinct pre-login screen ONCE (landing, theme/language picker, sign-up, sign-in, forgot-password). Do NOT exhaustively try onboarding variants (every theme, every language) \u2014 one capture per screen type is enough. Then LOG IN using the provided credentials and verify you are actually signed in.
62256
+ **Phase 2 \u2014 Logged-in breadth first (~35% of budget).** Once signed in, find the primary navigation (bottom tab bar, drawer, or menu) and visit EVERY top-level destination ONCE, capturing each screen, BEFORE drilling into any of them. A survey that maps one tab deeply but never opens the other tabs has failed \u2014 breadth across all tabs/drawer entries is mandatory.
62257
+ **Phase 3 \u2014 Depth (remaining budget).** Return to each captured tab and explore its sub-screens: open ONE list row per list (rows share a template), open menus/sheets/dialogs, capture detail screens, and mobile_swipe up/down to reveal off-screen content. record_transition whenever you move between screens.
62258
+
62259
+ Rules that apply throughout: capture_screen every new screen (name + type \u2014 use type "onboarding"/"landing" for pre-login screens, "auth" for sign-in/sign-up); record_transition on every move; mobile_back to return; mobile_relaunch only for a clean restart between episodes. When no new screens remain, call finish_exploration.
62159
62260
 
62160
62261
  ## Boundaries (survey = map, do not mutate)
62161
62262
  - Do NOT submit forms, save, delete, purchase, or send anything. You MAY open modals/menus to catalog them, then dismiss.
@@ -62185,7 +62286,7 @@ Max iterations: ${maxIterations}. You will be warned near the end.`;
62185
62286
  ## Application Brief
62186
62287
  ${appBrief}
62187
62288
  Use this to prioritize which screens and flows to cover.` : "";
62188
- const existingScreensBlock = mode === "survey" && existingScreens && existingScreens.length > 0 ? `
62289
+ const existingScreensBlock = mode === "survey" && incremental && existingScreens && existingScreens.length > 0 ? `
62189
62290
 
62190
62291
  ## ALREADY DISCOVERED SCREENS (skip these; find new)
62191
62292
  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.
@@ -62380,7 +62481,7 @@ ${existingScreens.slice(0, 100).map((s) => `- ${s.screenId}${s.name ? ` "${s.nam
62380
62481
  const browserCreds = ctx.variableContext.allTestVariables ?? ctx.variableContext.publicTestVariables;
62381
62482
  const { secrets: credentialSecrets } = (0, credential_tools_js_1.partitionTestVariables)(browserCreds);
62382
62483
  const hasCredentials = Object.keys(credentialSecrets).length > 0;
62383
- const systemPrompt = buildSystemPrompt(mode, platform3, enableRecordJourney, maxIterations, ctx.appBrief, targetAppId, existingScreens) + buildMobileCredentialPromptBlock(credentialSecrets) + (registerMode && inboxState ? buildMobileInboxPromptBlock({
62484
+ const systemPrompt = buildSystemPrompt(mode, platform3, enableRecordJourney, maxIterations, ctx.appBrief, targetAppId, existingScreens, ctx.incremental) + buildMobileCredentialPromptBlock(credentialSecrets) + (registerMode && inboxState ? buildMobileInboxPromptBlock({
62384
62485
  email: inboxState.email,
62385
62486
  passwordKey: inboxState.passwordKey ?? "TEST_USER_PASSWORD",
62386
62487
  context: mode
@@ -65645,6 +65746,7 @@ Return ONLY one valid JSON object matching the schema below. Do NOT include <thi
65645
65746
  7. Feature descriptions MUST reference actual element labels / accessibility-ids from the evidence
65646
65747
  8. Do NOT create standalone features for generic error / empty screens (network-error, permission-denied). If a feature screen is broken or crashes, keep it in its intended feature and note the failure in the description.
65647
65748
  9. COVER EVERY SCREEN: every explored screen except generic error / permission screens MUST appear in exactly one feature group's routes. Do not leave screens ungrouped \u2014 a screen the explorer reached is part of SOME feature. Attach an ambiguous screen to its most closely related feature and note the ambiguity in that feature's description. Sign-in / sign-up / forgot-password screens form an "Authentication" group even when they were only reached via links from other screens.
65749
+ 10. LOGGED-OUT vs LOGGED-IN SEPARATION: screens shown BEFORE the user is signed in (splash, landing/welcome, theme or language pickers, walkthroughs, sign-up, sign-in, forgot-password, demo/preview screens) must NEVER share a feature group with the signed-in app. Put sign-in / sign-up / forgot-password in "Authentication" (rule 4) and the remaining pre-login screens in an "Onboarding" group. Features named after signed-in areas (feeds, dashboards, tabs, settings) must contain ONLY screens reached after authentication. A pre-login flow is a linear sequence, not a navigation destination \u2014 do not let it swallow the app's main features.
65648
65750
 
65649
65751
  ## Output JSON Schema
65650
65752
  {
@@ -66028,7 +66130,8 @@ ${constraints.join("\n")}`);
66028
66130
  const orderedScreens = targetAppScreens(graph, appId).filter((state2) => state2.screenType?.toLowerCase() !== "error").sort((a, b) => a.firstSeenIteration - b.firstSeenIteration);
66029
66131
  const includedScreenIds = new Set(orderedScreens.map((state2) => state2.screenId));
66030
66132
  for (const state2 of orderedScreens) {
66031
- const groupName = state2.screenType?.toLowerCase() === "auth" ? "Authentication" : screenDisplayName(state2);
66133
+ const screenTypeLower = state2.screenType?.toLowerCase();
66134
+ const groupName = screenTypeLower === "auth" ? "Authentication" : screenTypeLower === "onboarding" || screenTypeLower === "landing" || screenTypeLower === "splash" ? "Onboarding" : screenDisplayName(state2);
66032
66135
  const group = groups.get(groupName) ?? {
66033
66136
  name: groupName,
66034
66137
  description: `Native mobile screens related to ${groupName}.`,
@@ -66487,6 +66590,7 @@ var require_mobile_generator = __commonJS({
66487
66590
  ## Rules
66488
66591
  - Re-snapshot before every assertion so the ref is fresh.
66489
66592
  - Assert the OUTCOME of the flow (the new screen / new content), not the control you just tapped.
66593
+ - 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 ("Add Your First \u2026", "Get Started", "No items yet"), onboarding banners, or counters \u2014 they vanish as soon as the account has data, and the test then fails forever on a healthy app.
66490
66594
  - Do NOT trigger irreversible side effects (real payments, sending messages to others) \u2014 note them and assert what you safely can.
66491
66595
  - Stay inside this app.${targetLine} Do not open or use app stores, browsers, email apps, settings, or any other app. If an action leaves the target app, the runner will relaunch the target app and reject that action.
66492
66596
  - Do ONLY the actions this scenario needs. Do NOT re-open a menu you already opened, re-select an option that is already selected, toggle a setting back and forth, or repeat a step that already succeeded \u2014 EVERY action you take is baked into the generated test verbatim, so each extra action becomes a permanent junk step.
@@ -67136,6 +67240,24 @@ ${statePacket}` },
67136
67240
  return true;
67137
67241
  return false;
67138
67242
  }
67243
+ var BARE_CONTAINER_CLASS_RE = /(webview|framelayout|linearlayout|relativelayout|viewgroup|scrollview|recyclerview|listview|XCUIElementTypeWebView|XCUIElementTypeApplication|XCUIElementTypeWindow|XCUIElementTypeOther|XCUIElementTypeScrollView)$/i;
67244
+ function isBareContainerTap(action) {
67245
+ if (action.type !== "TAP")
67246
+ return false;
67247
+ const bundle = action.metadata.locatorBundle;
67248
+ if (!bundle)
67249
+ return false;
67250
+ const hasIdentity = Boolean(bundle.text?.trim() || bundle.contentDesc?.trim() || bundle.accessibilityId?.trim() || action.metadata.targetLabel?.trim());
67251
+ if (hasIdentity)
67252
+ return false;
67253
+ const resourceId = bundle.resourceId?.trim() ?? "";
67254
+ const localName = resourceId.includes("/") ? resourceId.slice(resourceId.indexOf("/") + 1) : resourceId;
67255
+ const containerishId = localName !== "" && (localName === "webview" || ALWAYS_PRESENT_CONTAINER_ID_NAMES.has(localName));
67256
+ const containerishClass = BARE_CONTAINER_CLASS_RE.test(bundle.className ?? "");
67257
+ if (containerishId)
67258
+ return true;
67259
+ return containerishClass && (resourceId === "" || containerishId);
67260
+ }
67139
67261
  function appendHybridFloor(actions, recording, platform3) {
67140
67262
  const anchor = pickLandingAnchor(recording.lastSnapshot);
67141
67263
  if (!anchor)
@@ -67176,10 +67298,15 @@ ${statePacket}` },
67176
67298
  }
67177
67299
  function assembleTest(args) {
67178
67300
  const { scenario, recording, ctx, platform: platform3, appDataCleared, log: log2 } = args;
67179
- const actions = collapseRetryCycles(recording.actions);
67301
+ let actions = collapseRetryCycles(recording.actions);
67180
67302
  if (actions.length < recording.actions.length) {
67181
67303
  log2(` collapsed ${recording.actions.length - actions.length} retry-cycle step(s) out of the recorded trace (${recording.actions.length} \u2192 ${actions.length}).`);
67182
67304
  }
67305
+ const beforeContainerDrop = actions.length;
67306
+ actions = actions.filter((a) => !isBareContainerTap(a));
67307
+ if (actions.length < beforeContainerDrop) {
67308
+ log2(` dropped ${beforeContainerDrop - actions.length} bare-container tap step(s) (no identity \u2014 un-replayable ambient taps).`);
67309
+ }
67183
67310
  const floorAppended = appendHybridFloor(actions, recording, platform3);
67184
67311
  if (floorAppended) {
67185
67312
  log2(" appended hybrid durable-outcome floor (landing-screen ASSERT_VISIBLE).");
@@ -67367,6 +67494,1157 @@ Mobile generate phase complete: ${tests.length}/${scenarios.length} test(s) gene
67367
67494
  }
67368
67495
  });
67369
67496
 
67497
+ // ../runner-core/dist/services/mobile/mobile-heal-postprocess.js
67498
+ var require_mobile_heal_postprocess = __commonJS({
67499
+ "../runner-core/dist/services/mobile/mobile-heal-postprocess.js"(exports2) {
67500
+ "use strict";
67501
+ Object.defineProperty(exports2, "__esModule", { value: true });
67502
+ exports2.redactMobileSecretsFromText = redactMobileSecretsFromText;
67503
+ exports2.detectMobileStepSecretLeak = detectMobileStepSecretLeak;
67504
+ exports2.computeMobileHealOutcome = computeMobileHealOutcome2;
67505
+ var REDACT_KEY_RE = /email|username|user|phone|password|secret|token|api[_-]?key|access[_-]?key|\bpass\b|credential|bearer|\bpat\b|session|cookie|jwt|otp|pin/i;
67506
+ var DETECT_KEY_RE = /password|secret|token|api[_]?key|\bpass\b|credential|bearer|\bpat\b/i;
67507
+ var MIN_REDACT_LEN = 4;
67508
+ var MIN_DETECT_LEN = 6;
67509
+ var TOKEN_SOURCES = [
67510
+ "eyJ[A-Za-z0-9_-]{6,}\\.[A-Za-z0-9_-]{6,}\\.[A-Za-z0-9_-]{4,}",
67511
+ // JWT (three base64url segments)
67512
+ "Bearer\\s+[A-Za-z0-9._~+/=-]{12,}",
67513
+ // Authorization: Bearer <token>
67514
+ "sk-[A-Za-z0-9]{16,}"
67515
+ // OpenAI-style secret key
67516
+ ];
67517
+ var EMAIL_RE = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
67518
+ function escapeRegExp(value) {
67519
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
67520
+ }
67521
+ function collectSecretVars(testVariables, minLen, keyRe) {
67522
+ if (!testVariables)
67523
+ return [];
67524
+ const out = [];
67525
+ for (const [key, value] of Object.entries(testVariables)) {
67526
+ if (typeof value === "string" && value.length >= minLen && keyRe.test(key)) {
67527
+ out.push({ key, value });
67528
+ }
67529
+ }
67530
+ return out.sort((a, b) => b.value.length - a.value.length);
67531
+ }
67532
+ function redactMobileSecretsFromText(text, testVariables) {
67533
+ if (!text)
67534
+ return text;
67535
+ let out = text;
67536
+ for (const { key, value } of collectSecretVars(testVariables, MIN_REDACT_LEN, REDACT_KEY_RE)) {
67537
+ out = out.replace(new RegExp(escapeRegExp(value), "g"), `{{${key}}}`);
67538
+ }
67539
+ for (const source of TOKEN_SOURCES) {
67540
+ out = out.replace(new RegExp(source, "g"), "[REDACTED]");
67541
+ }
67542
+ out = out.replace(EMAIL_RE, "[EMAIL]");
67543
+ return out;
67544
+ }
67545
+ function detectMobileStepSecretLeak(steps, testVariables) {
67546
+ if (!Array.isArray(steps) || steps.length === 0)
67547
+ return null;
67548
+ const serialized = JSON.stringify(steps);
67549
+ if (typeof serialized !== "string")
67550
+ return null;
67551
+ for (const { key, value } of collectSecretVars(testVariables, MIN_DETECT_LEN, DETECT_KEY_RE)) {
67552
+ if (serialized.includes(value))
67553
+ return `literal value of ${key}`;
67554
+ }
67555
+ for (const source of TOKEN_SOURCES) {
67556
+ if (new RegExp(source).test(serialized))
67557
+ return "embedded token/bearer/JWT";
67558
+ }
67559
+ return null;
67560
+ }
67561
+ var NEEDS_REVIEW_VERDICTS = /* @__PURE__ */ new Set([
67562
+ "prereq_unmet",
67563
+ "state_stale",
67564
+ "test_invalid",
67565
+ "unhealable_dynamic"
67566
+ ]);
67567
+ function computeMobileHealOutcome2(args) {
67568
+ const { heal } = args;
67569
+ const hasFix = Array.isArray(heal.healedSteps) && heal.healedSteps.length > 0;
67570
+ const secretLeak = heal.passed && hasFix ? detectMobileStepSecretLeak(heal.healedSteps, args.testVariables) : null;
67571
+ const isConfigIssue = heal.verdict === "config_issue";
67572
+ const isAppBug = heal.verdict === "app_bug";
67573
+ const extraTags = new Set((heal.extraTags ?? []).filter((t) => typeof t === "string" && t.length > 0));
67574
+ if (secretLeak)
67575
+ extraTags.add("@needs-review");
67576
+ if (!heal.passed && NEEDS_REVIEW_VERDICTS.has(heal.verdict))
67577
+ extraTags.add("@needs-review");
67578
+ let status;
67579
+ if (secretLeak)
67580
+ status = "FAILED";
67581
+ else if (heal.passed)
67582
+ status = "PASSED";
67583
+ else if (isConfigIssue)
67584
+ status = "ERROR";
67585
+ else
67586
+ status = "FAILED";
67587
+ let error2;
67588
+ if (status === "PASSED") {
67589
+ error2 = void 0;
67590
+ } else if (secretLeak) {
67591
+ error2 = `HEAL_SECRET_LEAK: healed steps contained a literal secret (${secretLeak}); patch dropped, tagged @needs-review`;
67592
+ } else if (isConfigIssue) {
67593
+ error2 = `CONFIG_ISSUE: ${heal.healReason ?? args.finalError ?? args.reproduceError ?? "environment/rate-limit blocker"}`;
67594
+ } else if (isAppBug) {
67595
+ error2 = `APP_BUG: ${heal.healReason ?? args.finalError ?? args.reproduceError ?? "application defect found during heal"}`;
67596
+ } else {
67597
+ error2 = args.finalError ?? heal.healReason ?? args.reproduceError ?? void 0;
67598
+ }
67599
+ return {
67600
+ status,
67601
+ error: error2,
67602
+ extraTags: extraTags.size > 0 ? [...extraTags] : void 0,
67603
+ removeTags: heal.removeTags,
67604
+ shouldPatch: heal.passed === true && hasFix && !secretLeak,
67605
+ secretLeak
67606
+ };
67607
+ }
67608
+ }
67609
+ });
67610
+
67611
+ // ../runner-core/dist/services/selector-registry-context.js
67612
+ var require_selector_registry_context = __commonJS({
67613
+ "../runner-core/dist/services/selector-registry-context.js"(exports2) {
67614
+ "use strict";
67615
+ Object.defineProperty(exports2, "__esModule", { value: true });
67616
+ exports2.normalizeSelectorRegistryEntries = normalizeSelectorRegistryEntries;
67617
+ exports2.formatSelectorRegistryContextForPrompt = formatSelectorRegistryContextForPrompt;
67618
+ exports2.collectRegistryCandidates = collectRegistryCandidates;
67619
+ exports2.buildRegistryCandidateBlock = buildRegistryCandidateBlock;
67620
+ exports2.planRegistryFallbackFix = planRegistryFallbackFix;
67621
+ exports2.substituteSelectorInCode = substituteSelectorInCode;
67622
+ exports2.parseMobileLocatorExpression = parseMobileLocatorExpression;
67623
+ exports2.collectMobileRegistryCandidates = collectMobileRegistryCandidates;
67624
+ exports2.mobileCandidateToTarget = mobileCandidateToTarget;
67625
+ function isRecord(value) {
67626
+ return value !== null && typeof value === "object" && !Array.isArray(value);
67627
+ }
67628
+ function asString(value, fallback = "") {
67629
+ return typeof value === "string" ? value : fallback;
67630
+ }
67631
+ function asNumber(value, fallback = 0) {
67632
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
67633
+ }
67634
+ function asStringArray(value) {
67635
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
67636
+ }
67637
+ function truncateForSelectorPrompt(value, maxLength = 180) {
67638
+ const normalized = (value ?? "").replace(/\s+/g, " ").trim();
67639
+ if (normalized.length <= maxLength)
67640
+ return normalized;
67641
+ return `${normalized.slice(0, Math.max(0, maxLength - 3))}...`;
67642
+ }
67643
+ function inlineCode(value, maxLength = 180) {
67644
+ return `\`${truncateForSelectorPrompt(value, maxLength).replace(/`/g, "'")}\``;
67645
+ }
67646
+ function normalizeRef(value) {
67647
+ if (!isRecord(value))
67648
+ return null;
67649
+ const expression = asString(value.expression).trim();
67650
+ if (!expression)
67651
+ return null;
67652
+ return {
67653
+ route: asString(value.route, "*"),
67654
+ usage: asString(value.usage, "locator"),
67655
+ source: asString(value.source, "generated"),
67656
+ expression,
67657
+ occurrenceIndex: asNumber(value.occurrenceIndex, 0)
67658
+ };
67659
+ }
67660
+ function normalizeSibling(value) {
67661
+ if (!isRecord(value))
67662
+ return null;
67663
+ const testCaseId = asString(value.testCaseId).trim();
67664
+ const expression = asString(value.expression).trim();
67665
+ if (!testCaseId || !expression)
67666
+ return null;
67667
+ return {
67668
+ testCaseId,
67669
+ name: asString(value.name, testCaseId),
67670
+ suite: typeof value.suite === "string" ? value.suite : null,
67671
+ lastPassedAt: typeof value.lastPassedAt === "string" ? value.lastPassedAt : null,
67672
+ expression,
67673
+ usage: asString(value.usage, "locator"),
67674
+ route: asString(value.route, "*"),
67675
+ source: asString(value.source, "generated")
67676
+ };
67677
+ }
67678
+ function normalizeEntry(value) {
67679
+ if (!isRecord(value))
67680
+ return null;
67681
+ const id = asString(value.id).trim();
67682
+ const expression = asString(value.expression).trim();
67683
+ if (!id || !expression)
67684
+ return null;
67685
+ return {
67686
+ id,
67687
+ key: asString(value.key, id),
67688
+ route: asString(value.route, "*"),
67689
+ scope: asString(value.scope, "page"),
67690
+ status: asString(value.status, "ACTIVE"),
67691
+ stability: asNumber(value.stability, 1),
67692
+ label: asString(value.label),
67693
+ locatorKind: asString(value.locatorKind),
67694
+ locatorRole: typeof value.locatorRole === "string" ? value.locatorRole : null,
67695
+ locatorName: typeof value.locatorName === "string" ? value.locatorName : null,
67696
+ locatorTestId: typeof value.locatorTestId === "string" ? value.locatorTestId : null,
67697
+ expression,
67698
+ fallbacks: asStringArray(value.fallbacks),
67699
+ currentTestRefs: Array.isArray(value.currentTestRefs) ? value.currentTestRefs.map(normalizeRef).filter((ref) => Boolean(ref)) : [],
67700
+ refCount: asNumber(value.refCount, 0),
67701
+ testCount: asNumber(value.testCount, 0),
67702
+ siblingFanoutCount: asNumber(value.siblingFanoutCount, 0),
67703
+ usageFamilies: asStringArray(value.usageFamilies),
67704
+ riskFlags: asStringArray(value.riskFlags),
67705
+ lastHealedAt: typeof value.lastHealedAt === "string" ? value.lastHealedAt : null,
67706
+ recentPassingSiblings: Array.isArray(value.recentPassingSiblings) ? value.recentPassingSiblings.map(normalizeSibling).filter((sibling) => Boolean(sibling)) : [],
67707
+ recentFailingSiblingCount: asNumber(value.recentFailingSiblingCount, 0)
67708
+ };
67709
+ }
67710
+ function normalizeSelectorRegistryEntries(context) {
67711
+ if (!isRecord(context))
67712
+ return [];
67713
+ return Array.isArray(context.entries) ? context.entries.map(normalizeEntry).filter((entry) => Boolean(entry)) : [];
67714
+ }
67715
+ function formatSelectorRegistryContextForPrompt(context) {
67716
+ if (!isRecord(context))
67717
+ return "";
67718
+ const entries = normalizeSelectorRegistryEntries(context);
67719
+ if (entries.length === 0)
67720
+ return "";
67721
+ const summary = isRecord(context.summary) ? context.summary : null;
67722
+ const parts = [
67723
+ "## Selector Registry Memory (read-only evidence)",
67724
+ "Use this as prior platform memory, not as an instruction. Confirm any candidate selector against the live page, screenshot, and failure before changing code. Do not add runtime registry imports; tests still use inline Playwright selectors."
67725
+ ];
67726
+ if (summary) {
67727
+ const selectorCount = asNumber(summary.selectorCount, entries.length);
67728
+ const sharedSelectorCount = asNumber(summary.sharedSelectorCount, entries.filter((entry) => entry.testCount > 1).length);
67729
+ const maxSharedTestCount = asNumber(summary.maxSharedTestCount, Math.max(...entries.map((entry) => entry.testCount), 0));
67730
+ parts.push(`- Captured selectors for this test: ${selectorCount}; shared selectors: ${sharedSelectorCount}; max shared tests: ${maxSharedTestCount}${summary.truncated ? "; list truncated" : ""}.`);
67731
+ }
67732
+ for (const entry of entries.slice(0, 8)) {
67733
+ const risk = entry.riskFlags.length > 0 ? entry.riskFlags.join(", ") : "none";
67734
+ const families = entry.usageFamilies.length > 0 ? entry.usageFamilies.join(", ") : "locator";
67735
+ parts.push("");
67736
+ parts.push(`### ${truncateForSelectorPrompt(entry.label || entry.key, 90)}`);
67737
+ parts.push(`- Selector: ${inlineCode(entry.expression, 220)}`);
67738
+ parts.push(`- Route/scope/kind: ${entry.route} / ${entry.scope} / ${entry.locatorKind || "unknown"}; usage families: ${families}.`);
67739
+ parts.push(`- Shared by: ${entry.testCount} test(s), ${entry.siblingFanoutCount} sibling(s), ${entry.refCount} ref(s); risks: ${risk}; status: ${entry.status}; stability: ${entry.stability}.`);
67740
+ if (entry.lastHealedAt)
67741
+ parts.push(`- Last registry heal: ${entry.lastHealedAt}.`);
67742
+ const currentRefs = entry.currentTestRefs.slice(0, 3);
67743
+ if (currentRefs.length > 0) {
67744
+ parts.push("- Current test occurrences:");
67745
+ for (const ref of currentRefs) {
67746
+ parts.push(` - ${ref.usage} on ${ref.route} from ${ref.source}: ${inlineCode(ref.expression, 180)}`);
67747
+ }
67748
+ }
67749
+ const siblings = entry.recentPassingSiblings.slice(0, 3);
67750
+ if (siblings.length > 0) {
67751
+ parts.push("- Recent passing sibling tests using this registry entry:");
67752
+ for (const sibling of siblings) {
67753
+ const suite = sibling.suite ? ` (${truncateForSelectorPrompt(sibling.suite, 50)})` : "";
67754
+ const passed = sibling.lastPassedAt ? ` passed ${sibling.lastPassedAt}` : "";
67755
+ parts.push(` - ${truncateForSelectorPrompt(sibling.name, 80)}${suite}${passed}: ${inlineCode(sibling.expression, 180)}`);
67756
+ }
67757
+ }
67758
+ if (entry.recentFailingSiblingCount && entry.recentFailingSiblingCount > 0) {
67759
+ parts.push(`- Other recent failing siblings on this entry: ${entry.recentFailingSiblingCount}.`);
67760
+ }
67761
+ const fallbacks = (entry.fallbacks ?? []).slice(0, 3);
67762
+ if (fallbacks.length > 0) {
67763
+ parts.push(`- Registry fallbacks: ${fallbacks.map((fallback) => inlineCode(fallback, 120)).join(", ")}.`);
67764
+ }
67765
+ }
67766
+ return `${parts.join("\n")}
67767
+ `;
67768
+ }
67769
+ function selectorKey(expression) {
67770
+ return expression.trim().replace(/^page\s*\.\s*/, "").replace(/\s+/g, " ").replace(/"/g, "'").trim();
67771
+ }
67772
+ function collectRegistryCandidates(context) {
67773
+ const entries = normalizeSelectorRegistryEntries(context).slice(0, 8);
67774
+ const seen = /* @__PURE__ */ new Set();
67775
+ const ranked = [[], [], []];
67776
+ for (const entry of entries) {
67777
+ const entryLabel = entry.label || entry.key;
67778
+ for (const sibling of entry.recentPassingSiblings) {
67779
+ const key = selectorKey(sibling.expression);
67780
+ if (seen.has(key))
67781
+ continue;
67782
+ seen.add(key);
67783
+ ranked[0].push({ expression: sibling.expression, source: "passing-sibling", entryLabel, siblingName: sibling.name });
67784
+ }
67785
+ const entryKey = selectorKey(entry.expression);
67786
+ if (!seen.has(entryKey)) {
67787
+ seen.add(entryKey);
67788
+ ranked[1].push({ expression: entry.expression, source: "registry-entry", entryLabel });
67789
+ }
67790
+ for (const fallback of entry.fallbacks ?? []) {
67791
+ const key = selectorKey(fallback);
67792
+ if (seen.has(key))
67793
+ continue;
67794
+ seen.add(key);
67795
+ ranked[2].push({ expression: fallback, source: "fallback", entryLabel });
67796
+ }
67797
+ }
67798
+ return ranked.flat();
67799
+ }
67800
+ function buildRegistryCandidateBlock(context, excludeExpressions) {
67801
+ const exclude = new Set(excludeExpressions.map(selectorKey));
67802
+ const candidates = collectRegistryCandidates(context).filter((candidate) => !exclude.has(selectorKey(candidate.expression))).slice(0, 6);
67803
+ if (candidates.length === 0)
67804
+ return "";
67805
+ const lines = [
67806
+ "## Untried Selector Candidates (from registry memory)",
67807
+ "Ranked alternatives for elements this test uses, from the platform selector registry. Verify each against the screenshot and error before adopting \u2014 do not adopt blindly."
67808
+ ];
67809
+ for (const candidate of candidates) {
67810
+ const provenance = candidate.source === "passing-sibling" ? `proven in passing sibling "${truncateForSelectorPrompt(candidate.siblingName, 80)}"` : candidate.source === "registry-entry" ? `registry entry for "${truncateForSelectorPrompt(candidate.entryLabel, 80)}"` : `registry fallback for "${truncateForSelectorPrompt(candidate.entryLabel, 80)}"`;
67811
+ lines.push(`- ${inlineCode(candidate.expression, 180)} \u2014 ${provenance}`);
67812
+ }
67813
+ return lines.join("\n");
67814
+ }
67815
+ function findExpressionInCode(code, expression) {
67816
+ const trimmed = expression.trim();
67817
+ if (trimmed && code.includes(trimmed))
67818
+ return trimmed;
67819
+ const withoutPage = trimmed.replace(/^page\s*\.\s*/, "");
67820
+ if (withoutPage !== trimmed && withoutPage && code.includes(withoutPage))
67821
+ return withoutPage;
67822
+ const withPage = `page.${withoutPage}`;
67823
+ if (withPage !== trimmed && code.includes(withPage))
67824
+ return withPage;
67825
+ return null;
67826
+ }
67827
+ function extractFailureFocus(error2) {
67828
+ const focus = error2.split(/\r?\n/).filter((line) => /^\s*>/.test(line) || /waiting for|locator resolved to/i.test(line) || /^\s*locator:/i.test(line));
67829
+ return focus.length > 0 ? focus.join("\n") : error2;
67830
+ }
67831
+ function planRegistryFallbackFix(args) {
67832
+ const { code, error: error2, context } = args;
67833
+ if (!error2 || !code)
67834
+ return null;
67835
+ const entries = normalizeSelectorRegistryEntries(context).slice(0, 8);
67836
+ if (entries.length === 0)
67837
+ return null;
67838
+ const errorKey = selectorKey(extractFailureFocus(error2));
67839
+ for (const entry of entries) {
67840
+ const failingExpressions = [entry.expression, ...entry.currentTestRefs.map((ref) => ref.expression)];
67841
+ const failingSeen = /* @__PURE__ */ new Set();
67842
+ for (const failing of failingExpressions) {
67843
+ const failingKey = selectorKey(failing);
67844
+ if (!failingKey || failingSeen.has(failingKey))
67845
+ continue;
67846
+ failingSeen.add(failingKey);
67847
+ if (!errorKey.includes(failingKey))
67848
+ continue;
67849
+ const matchedInCode = findExpressionInCode(code, failing);
67850
+ if (!matchedInCode)
67851
+ continue;
67852
+ const entryLabel = entry.label || entry.key;
67853
+ const candidateSeen = /* @__PURE__ */ new Set([failingKey]);
67854
+ const candidates = [];
67855
+ for (const fallback of entry.fallbacks ?? []) {
67856
+ const key = selectorKey(fallback);
67857
+ if (!key || candidateSeen.has(key) || code.includes(fallback.trim()))
67858
+ continue;
67859
+ candidateSeen.add(key);
67860
+ candidates.push({ expression: fallback, source: "fallback", entryLabel });
67861
+ }
67862
+ for (const sibling of entry.recentPassingSiblings) {
67863
+ const key = selectorKey(sibling.expression);
67864
+ if (!key || candidateSeen.has(key) || code.includes(sibling.expression.trim()))
67865
+ continue;
67866
+ candidateSeen.add(key);
67867
+ candidates.push({ expression: sibling.expression, source: "passing-sibling", entryLabel, siblingName: sibling.name });
67868
+ }
67869
+ if (candidates.length === 0)
67870
+ continue;
67871
+ return { matchedInCode, entryLabel, candidates };
67872
+ }
67873
+ }
67874
+ return null;
67875
+ }
67876
+ function substituteSelectorInCode(code, matchedInCode, replacement) {
67877
+ const target = matchedInCode.trim();
67878
+ let normalized = replacement.trim();
67879
+ const targetHasPage = /^page\s*\.\s*/.test(target);
67880
+ const replacementHasPage = /^page\s*\.\s*/.test(normalized);
67881
+ if (targetHasPage && !replacementHasPage)
67882
+ normalized = `page.${normalized}`;
67883
+ if (!targetHasPage && replacementHasPage)
67884
+ normalized = normalized.replace(/^page\s*\.\s*/, "");
67885
+ return code.split(target).join(normalized);
67886
+ }
67887
+ var MOBILE_LOCATOR_RE = /^mobile\.(accessibilityId|resourceId|text|contentDesc|xpath|className|locator)\(\s*'((?:\\.|[^'])*)'\s*\)$/;
67888
+ function unescapeMobileLocatorValue(value) {
67889
+ return value.replace(/\\'/g, "'").replace(/\\\\/g, "\\");
67890
+ }
67891
+ function parseMobileLocatorExpression(expression) {
67892
+ const match = MOBILE_LOCATOR_RE.exec(expression.trim());
67893
+ if (!match)
67894
+ return null;
67895
+ return { kind: match[1], value: unescapeMobileLocatorValue(match[2]).trim() };
67896
+ }
67897
+ function mobileIdentityKey(parts) {
67898
+ return `${parts.kind}\0${parts.value}`;
67899
+ }
67900
+ function collectMobileFallbackExpressions(entry, primary) {
67901
+ const seen = /* @__PURE__ */ new Set([mobileIdentityKey(primary)]);
67902
+ const fallbacks = [];
67903
+ const consider = (expression) => {
67904
+ const parsed = parseMobileLocatorExpression(expression);
67905
+ if (!parsed)
67906
+ return;
67907
+ const key = mobileIdentityKey(parsed);
67908
+ if (seen.has(key))
67909
+ return;
67910
+ seen.add(key);
67911
+ fallbacks.push(expression.trim());
67912
+ };
67913
+ for (const fallback of entry.fallbacks ?? [])
67914
+ consider(fallback);
67915
+ for (const sibling of entry.recentPassingSiblings)
67916
+ consider(sibling.expression);
67917
+ return fallbacks;
67918
+ }
67919
+ function collectMobileRegistryCandidates(context) {
67920
+ const entries = normalizeSelectorRegistryEntries(context).slice(0, 8);
67921
+ const seen = /* @__PURE__ */ new Set();
67922
+ const candidates = [];
67923
+ for (const entry of entries) {
67924
+ const primary = parseMobileLocatorExpression(entry.expression);
67925
+ if (!primary)
67926
+ continue;
67927
+ const identityKey = mobileIdentityKey(primary);
67928
+ if (seen.has(identityKey))
67929
+ continue;
67930
+ seen.add(identityKey);
67931
+ candidates.push({
67932
+ kind: primary.kind,
67933
+ value: primary.value,
67934
+ fallbacks: collectMobileFallbackExpressions(entry, primary)
67935
+ });
67936
+ }
67937
+ return candidates;
67938
+ }
67939
+ function mobileCandidateToTarget(candidate) {
67940
+ const { kind, value } = candidate;
67941
+ switch (kind) {
67942
+ case "resourceId":
67943
+ return { locatorBundle: { resourceId: value } };
67944
+ case "accessibilityId":
67945
+ return { locatorBundle: { accessibilityId: value } };
67946
+ case "text":
67947
+ return { locatorBundle: { text: value } };
67948
+ case "contentDesc":
67949
+ return { locatorBundle: { contentDesc: value } };
67950
+ case "xpath":
67951
+ return { locatorBundle: { xpath: value } };
67952
+ case "className":
67953
+ return { locatorBundle: { className: value } };
67954
+ default:
67955
+ return {};
67956
+ }
67957
+ }
67958
+ }
67959
+ });
67960
+
67961
+ // ../runner-core/dist/services/mobile/mobile-heal-loop.js
67962
+ var require_mobile_heal_loop = __commonJS({
67963
+ "../runner-core/dist/services/mobile/mobile-heal-loop.js"(exports2) {
67964
+ "use strict";
67965
+ Object.defineProperty(exports2, "__esModule", { value: true });
67966
+ exports2.MOBILE_LIVE_HEAL_SYSTEM_PROMPT = exports2.MOBILE_SCRIPT_HEAL_SYSTEM_PROMPT = void 0;
67967
+ exports2.executeMobileScriptDrivenHeal = executeMobileScriptDrivenHeal;
67968
+ exports2.executeMobileTestWithHealing = executeMobileTestWithHealing2;
67969
+ exports2.executeMobileLiveHeal = executeMobileLiveHeal2;
67970
+ var ai_provider_js_1 = require_ai_provider();
67971
+ var ai_queue_js_1 = require_ai_queue();
67972
+ var ai_retry_js_1 = require_ai_retry();
67973
+ var mobile_source_parser_js_1 = require_mobile_source_parser();
67974
+ var mobile_heal_postprocess_js_1 = require_mobile_heal_postprocess();
67975
+ var mobile_observation_js_1 = require_mobile_observation();
67976
+ var selector_registry_context_js_1 = require_selector_registry_context();
67977
+ exports2.MOBILE_SCRIPT_HEAL_SYSTEM_PROMPT = `You are a QA engineer fixing a failing Appium (mobile UI automation) test. You receive: the test STEPS as JSON, the failure ERROR + step-level results, and the PAGE-SOURCE accessibility tree captured at the moment of failure (this tree is your 'screenshot'), plus optional known-good selector candidates from a registry.
67978
+ ## You MUST try to fix the steps
67979
+ Reason over steps + error + tree + registry and return working healed steps. Do NOT return needs_device unless you have genuinely exhausted that reasoning (and NEVER before your final attempt).
67980
+ ## Analyze
67981
+ 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.
67982
+ 2. STEP RESULTS: which steps passed before the failure.
67983
+ 3. TREE: does the current screen match what the failed step expects?
67984
+ 3b. STALE EMPTY-STATE ASSERT: a failing assert on one-time / data-dependent UI (empty-state CTAs like "Add Your First \u2026", "No items yet", 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).
67985
+ 4. 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 "Get Started" 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.
67986
+ ## Response \u2014 STRICT JSON, exactly one verdict:
67987
+ {"verdict":"fix","steps":[<FULL healed MobileTestStep array, all steps, your changes applied, order/metadata preserved>],"reason":"what changed and why","confidence":0.0-1.0}
67988
+ {"verdict":"app_bug","reason":"app crashed/blank/5xx (NOT rate-limit)"}
67989
+ {"verdict":"config_issue","reason":"429/rate limit/lockout/quota"}
67990
+ {"verdict":"needs_device","reason":"cannot fix from a static tree; need live re-observation"}
67991
+ {"verdict":"prereq_unmet","reason":"required entity/state absent for the account"}
67992
+ {"verdict":"state_stale","reason":"leftover data blocks a baseline assertion"}
67993
+ {"verdict":"test_invalid","reason":"scenario cannot be made to pass"}
67994
+ For a fix, return the COMPLETE steps array (not a diff).`;
67995
+ var DEFAULT_SCRIPT_MAX_ATTEMPTS = 6;
67996
+ var RECOVERABLE_MAX = 3;
67997
+ var BONUS_ATTEMPTS_CEIL = 4;
67998
+ var DEFAULT_BONUS_ATTEMPTS = 2;
67999
+ var MAX_LOG_CHARS = 4096;
68000
+ var OBSERVATION_MAX_ELEMENTS = 120;
68001
+ var REGISTRY_PREFLIGHT_MAX_CANDIDATES = 2;
68002
+ var MOBILE_HEAL_VERDICTS = [
68003
+ "fix",
68004
+ "app_bug",
68005
+ "config_issue",
68006
+ "needs_device",
68007
+ "prereq_unmet",
68008
+ "state_stale",
68009
+ "test_invalid",
68010
+ "unhealable_dynamic"
68011
+ ];
68012
+ var TERMINAL_VERDICTS = /* @__PURE__ */ new Set([
68013
+ "app_bug",
68014
+ "config_issue",
68015
+ "prereq_unmet",
68016
+ "state_stale",
68017
+ "test_invalid",
68018
+ "unhealable_dynamic"
68019
+ ]);
68020
+ function isRecord(value) {
68021
+ return typeof value === "object" && value !== null && !Array.isArray(value);
68022
+ }
68023
+ function envInt2(key) {
68024
+ const raw = process.env[key];
68025
+ if (raw === void 0)
68026
+ return void 0;
68027
+ const parsed = Number.parseInt(raw, 10);
68028
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
68029
+ }
68030
+ function tailLimit(text, max) {
68031
+ return text.length <= max ? text : text.slice(text.length - max);
68032
+ }
68033
+ function isMobileHealVerdict(value) {
68034
+ return MOBILE_HEAL_VERDICTS.includes(value);
68035
+ }
68036
+ function isLocatorNotFound(error2) {
68037
+ return /not found|no such element/i.test(error2 ?? "");
68038
+ }
68039
+ function isDrift(error2) {
68040
+ return /unexpected screen|screen drift/i.test(error2 ?? "");
68041
+ }
68042
+ function stripCodeFences(text) {
68043
+ const trimmed = text.trim();
68044
+ const fenced = /^```(?:json)?\s*([\s\S]*?)\s*```$/m.exec(trimmed);
68045
+ return fenced ? fenced[1].trim() : trimmed;
68046
+ }
68047
+ function extractBracesSubstring(text) {
68048
+ const first = text.indexOf("{");
68049
+ const last = text.lastIndexOf("}");
68050
+ if (first === -1 || last === -1 || last <= first)
68051
+ return null;
68052
+ return text.slice(first, last + 1);
68053
+ }
68054
+ function safeJsonParse(text) {
68055
+ try {
68056
+ return JSON.parse(text);
68057
+ } catch {
68058
+ return void 0;
68059
+ }
68060
+ }
68061
+ function coerceSteps(value) {
68062
+ if (!Array.isArray(value) || value.length === 0)
68063
+ return void 0;
68064
+ const allValid = value.every((step) => isRecord(step) && typeof step.action === "string" && typeof step.order === "number");
68065
+ return allValid ? value : void 0;
68066
+ }
68067
+ function parseHealVerdict(content) {
68068
+ const cleaned = stripCodeFences(content);
68069
+ let obj = safeJsonParse(cleaned);
68070
+ if (!isRecord(obj)) {
68071
+ const sub = extractBracesSubstring(cleaned);
68072
+ obj = sub ? safeJsonParse(sub) : void 0;
68073
+ }
68074
+ if (!isRecord(obj))
68075
+ return null;
68076
+ const rawVerdict = obj.verdict;
68077
+ if (typeof rawVerdict !== "string" || !isMobileHealVerdict(rawVerdict))
68078
+ return null;
68079
+ return {
68080
+ verdict: rawVerdict,
68081
+ steps: coerceSteps(obj.steps),
68082
+ reason: typeof obj.reason === "string" ? obj.reason : void 0,
68083
+ confidence: typeof obj.confidence === "number" ? obj.confidence : void 0
68084
+ };
68085
+ }
68086
+ function partsToCandidate(parts) {
68087
+ switch (parts.kind) {
68088
+ case "accessibilityId":
68089
+ return { accessibilityId: parts.value };
68090
+ case "resourceId":
68091
+ return { resourceId: parts.value };
68092
+ case "text":
68093
+ case "contentDesc":
68094
+ return { text: parts.value };
68095
+ case "xpath":
68096
+ return { xpath: parts.value };
68097
+ case "className":
68098
+ return { className: parts.value };
68099
+ default:
68100
+ return {};
68101
+ }
68102
+ }
68103
+ function hasIdentitySignal(candidate) {
68104
+ return Boolean(candidate.accessibilityId || candidate.resourceId || candidate.text || candidate.xpath);
68105
+ }
68106
+ function stepToLocatorCandidate(step) {
68107
+ const primary = step.target?.primary;
68108
+ if (primary) {
68109
+ const parsed = (0, selector_registry_context_js_1.parseMobileLocatorExpression)(primary);
68110
+ if (parsed) {
68111
+ const candidate = partsToCandidate(parsed);
68112
+ if (hasIdentitySignal(candidate))
68113
+ return candidate;
68114
+ }
68115
+ }
68116
+ const bundle = step.target?.locatorBundle;
68117
+ if (bundle) {
68118
+ const candidate = {};
68119
+ if (bundle.accessibilityId)
68120
+ candidate.accessibilityId = bundle.accessibilityId;
68121
+ if (bundle.resourceId)
68122
+ candidate.resourceId = bundle.resourceId;
68123
+ if (bundle.text)
68124
+ candidate.text = bundle.text;
68125
+ else if (bundle.contentDesc)
68126
+ candidate.text = bundle.contentDesc;
68127
+ if (bundle.xpath)
68128
+ candidate.xpath = bundle.xpath;
68129
+ if (hasIdentitySignal(candidate))
68130
+ return candidate;
68131
+ }
68132
+ return null;
68133
+ }
68134
+ function stepIdentityExpressions(step) {
68135
+ const out = [];
68136
+ const primary = step.target?.primary;
68137
+ if (primary)
68138
+ out.push(primary);
68139
+ const bundle = step.target?.locatorBundle;
68140
+ if (bundle) {
68141
+ if (bundle.resourceId)
68142
+ out.push(`mobile.resourceId('${bundle.resourceId}')`);
68143
+ if (bundle.accessibilityId)
68144
+ out.push(`mobile.accessibilityId('${bundle.accessibilityId}')`);
68145
+ if (bundle.text)
68146
+ out.push(`mobile.text('${bundle.text}')`);
68147
+ if (bundle.contentDesc)
68148
+ out.push(`mobile.contentDesc('${bundle.contentDesc}')`);
68149
+ if (bundle.xpath)
68150
+ out.push(`mobile.xpath('${bundle.xpath}')`);
68151
+ }
68152
+ return out;
68153
+ }
68154
+ function stepTargetChanged(base2, healed) {
68155
+ return JSON.stringify(base2?.target) !== JSON.stringify(healed.target);
68156
+ }
68157
+ function findMissingChangedLocators(baseSteps, healedSteps, screen) {
68158
+ const missing = [];
68159
+ healedSteps.forEach((healed, index) => {
68160
+ if (!stepTargetChanged(baseSteps[index], healed))
68161
+ return;
68162
+ const candidate = stepToLocatorCandidate(healed);
68163
+ if (!candidate)
68164
+ return;
68165
+ if ((0, mobile_source_parser_js_1.resolveLocatorAgainstScreen)(candidate, screen).length === 0) {
68166
+ missing.push({
68167
+ label: healed.target?.primary ?? JSON.stringify(candidate),
68168
+ expressions: stepIdentityExpressions(healed)
68169
+ });
68170
+ }
68171
+ });
68172
+ return missing;
68173
+ }
68174
+ function changedStepExpressions(baseSteps, healedSteps) {
68175
+ const out = [];
68176
+ healedSteps.forEach((healed, index) => {
68177
+ if (stepTargetChanged(baseSteps[index], healed))
68178
+ out.push(...stepIdentityExpressions(healed));
68179
+ });
68180
+ return out;
68181
+ }
68182
+ function pushUnique(target, additions) {
68183
+ for (const value of additions) {
68184
+ if (value && !target.includes(value))
68185
+ target.push(value);
68186
+ }
68187
+ }
68188
+ function buildUserContent(args) {
68189
+ const parts = [];
68190
+ const safeError = (0, mobile_heal_postprocess_js_1.redactMobileSecretsFromText)(args.activeError ?? void 0, args.testVariables);
68191
+ const safeLogs = (0, mobile_heal_postprocess_js_1.redactMobileSecretsFromText)(args.trimmedLogs, args.testVariables);
68192
+ parts.push("## Failing test steps (JSON)");
68193
+ parts.push("```json\n" + JSON.stringify(args.baseSteps, null, 2) + "\n```");
68194
+ parts.push("## Steps (numbered)");
68195
+ parts.push(args.baseSteps.map((step, index) => {
68196
+ const locator = step.target?.primary ? ` -> ${step.target.primary}` : "";
68197
+ return `${index + 1}. [${step.action}] ${step.description ?? ""}${locator}`;
68198
+ }).join("\n"));
68199
+ parts.push("## Failure");
68200
+ parts.push(`Error: ${safeError ?? "(none reported)"}`);
68201
+ if (safeLogs)
68202
+ parts.push("Logs (tail):\n" + safeLogs);
68203
+ if (args.activeFailingSource) {
68204
+ const safeSource = (0, mobile_heal_postprocess_js_1.redactMobileSecretsFromText)(args.activeFailingSource, args.testVariables) ?? args.activeFailingSource;
68205
+ const screen = (0, mobile_source_parser_js_1.parseMobileSource)(safeSource, args.platform);
68206
+ parts.push("## Captured screen (accessibility tree at moment of failure)");
68207
+ parts.push((0, mobile_observation_js_1.renderMobileObservation)(screen, { maxElements: OBSERVATION_MAX_ELEMENTS }));
68208
+ }
68209
+ if (args.attempt === 1) {
68210
+ const registryBlock = (0, selector_registry_context_js_1.formatSelectorRegistryContextForPrompt)(args.registryContext);
68211
+ if (registryBlock)
68212
+ parts.push(registryBlock);
68213
+ } else {
68214
+ const candidateBlock = (0, selector_registry_context_js_1.buildRegistryCandidateBlock)(args.registryContext, [...args.triedLocators]);
68215
+ if (candidateBlock)
68216
+ parts.push(candidateBlock);
68217
+ if (args.triedLocators.length > 0) {
68218
+ parts.push("## Locators already tried (do NOT repeat):\n" + args.triedLocators.map((locator) => `- ${locator}`).join("\n"));
68219
+ }
68220
+ const safeLastError = (0, mobile_heal_postprocess_js_1.redactMobileSecretsFromText)(args.lastError, args.testVariables);
68221
+ if (safeLastError)
68222
+ parts.push(`## Previous fix failed with:
68223
+ ${safeLastError}`);
68224
+ }
68225
+ if (args.directive)
68226
+ parts.push(`## Directive
68227
+ ${args.directive}`);
68228
+ return parts.join("\n\n");
68229
+ }
68230
+ function findFailingStepIndex(steps, error2) {
68231
+ const withTarget = steps.map((step, index) => ({ step, index })).filter((entry) => Boolean(entry.step.target?.primary));
68232
+ if (withTarget.length === 0)
68233
+ return -1;
68234
+ if (error2) {
68235
+ for (let k = withTarget.length - 1; k >= 0; k -= 1) {
68236
+ const primary = withTarget[k].step.target?.primary;
68237
+ if (primary && error2.includes(primary))
68238
+ return withTarget[k].index;
68239
+ }
68240
+ }
68241
+ return withTarget[withTarget.length - 1].index;
68242
+ }
68243
+ function substituteStepTarget(steps, index, candidate, bundlePartial) {
68244
+ const existing = steps[index].target;
68245
+ const newBundle = {
68246
+ xpath: existing?.locatorBundle?.xpath ?? "",
68247
+ className: existing?.locatorBundle?.className ?? "",
68248
+ ...existing?.locatorBundle,
68249
+ ...bundlePartial
68250
+ };
68251
+ const escaped = candidate.value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
68252
+ const newTarget = {
68253
+ primary: `mobile.${candidate.kind}('${escaped}')`,
68254
+ fallbacks: existing?.fallbacks ?? [],
68255
+ screenName: existing?.screenName ?? "",
68256
+ locatorBundle: newBundle,
68257
+ platformLocators: existing?.platformLocators
68258
+ };
68259
+ return steps.map((step, i) => i === index ? { ...step, target: newTarget } : step);
68260
+ }
68261
+ async function tryRegistryPreflight(steps, target, ctx, options) {
68262
+ const runNativeTest = options.runNativeTest;
68263
+ if (!runNativeTest || !options.selectorRegistryContext || !ctx.error)
68264
+ return null;
68265
+ const candidates = (0, selector_registry_context_js_1.collectMobileRegistryCandidates)(options.selectorRegistryContext);
68266
+ const failingIndex = findFailingStepIndex(steps, ctx.error);
68267
+ if (failingIndex < 0)
68268
+ return null;
68269
+ let tried = 0;
68270
+ for (const candidate of candidates) {
68271
+ if (tried >= REGISTRY_PREFLIGHT_MAX_CANDIDATES)
68272
+ break;
68273
+ const mapped = (0, selector_registry_context_js_1.mobileCandidateToTarget)(candidate);
68274
+ if (!mapped.locatorBundle || Object.keys(mapped.locatorBundle).length === 0)
68275
+ continue;
68276
+ tried += 1;
68277
+ const healedSteps = substituteStepTarget(steps, failingIndex, candidate, mapped.locatorBundle);
68278
+ const verify = await runNativeTest({ steps: healedSteps, target, testVariables: ctx.testVariables });
68279
+ if (verify.passed) {
68280
+ return {
68281
+ passed: true,
68282
+ verdict: "fix",
68283
+ healedSteps,
68284
+ healReason: "registry-fallback",
68285
+ stepResults: verify.stepResults,
68286
+ logs: verify.logs
68287
+ };
68288
+ }
68289
+ }
68290
+ return null;
68291
+ }
68292
+ async function executeMobileScriptDrivenHeal(steps, target, ctx, options) {
68293
+ const aiClient = options.aiClient ?? (options.model ? (0, ai_provider_js_1.getMobileClientForModel)(options.model) : (0, ai_provider_js_1.getMobileAIClient)());
68294
+ const model = options.model ? (0, ai_provider_js_1.resolveModelForTask)(options.model, "strong") : (0, ai_provider_js_1.getModel)("strong");
68295
+ const base2 = options.maxScriptAttempts ?? envInt2("MOBILE_HEAL_SCRIPT_MAX_ATTEMPTS") ?? DEFAULT_SCRIPT_MAX_ATTEMPTS;
68296
+ const bonusMax = Math.min(options.bonusAttempts ?? DEFAULT_BONUS_ATTEMPTS, BONUS_ATTEMPTS_CEIL);
68297
+ const registryPresent = options.selectorRegistryContext != null;
68298
+ const platform3 = target.platform;
68299
+ const trimmedLogs = tailLimit(ctx.logs ?? "", MAX_LOG_CHARS);
68300
+ let attemptCap = base2;
68301
+ let recoverableUsed = 0;
68302
+ let bonusUsed = 0;
68303
+ let attempt = 0;
68304
+ let baseSteps = steps;
68305
+ let activeError = ctx.error;
68306
+ let activeFailingSource = ctx.failingSource;
68307
+ let lastError;
68308
+ let lastHealedSteps;
68309
+ let lastHealReason;
68310
+ let lastConfidence;
68311
+ let lastVerdict;
68312
+ let pendingDirective = null;
68313
+ const triedLocators = [];
68314
+ let sameErrorCount = 0;
68315
+ let lastErrorSignature = null;
68316
+ const markRecoverableTurn = () => {
68317
+ if (recoverableUsed < RECOVERABLE_MAX) {
68318
+ attemptCap += 1;
68319
+ recoverableUsed += 1;
68320
+ }
68321
+ };
68322
+ const noteError = (error2) => {
68323
+ const signature = (error2 ?? "").slice(0, 150);
68324
+ if (signature && signature === lastErrorSignature) {
68325
+ sameErrorCount += 1;
68326
+ } else {
68327
+ sameErrorCount = error2 ? 1 : 0;
68328
+ lastErrorSignature = signature;
68329
+ }
68330
+ };
68331
+ for (; ; ) {
68332
+ if (attempt >= attemptCap) {
68333
+ const untriedRegistry = registryPresent && (0, selector_registry_context_js_1.buildRegistryCandidateBlock)(options.selectorRegistryContext, triedLocators) !== "";
68334
+ const canBonus = bonusUsed < bonusMax && lastHealedSteps !== void 0 && sameErrorCount < 2 && untriedRegistry;
68335
+ if (canBonus) {
68336
+ attemptCap += 1;
68337
+ bonusUsed += 1;
68338
+ } else {
68339
+ break;
68340
+ }
68341
+ }
68342
+ attempt += 1;
68343
+ const userContent = buildUserContent({
68344
+ attempt,
68345
+ baseSteps,
68346
+ activeError,
68347
+ trimmedLogs,
68348
+ activeFailingSource,
68349
+ platform: platform3,
68350
+ registryContext: options.selectorRegistryContext ?? null,
68351
+ triedLocators,
68352
+ lastError,
68353
+ directive: pendingDirective,
68354
+ testVariables: ctx.testVariables
68355
+ });
68356
+ pendingDirective = null;
68357
+ const messages = [
68358
+ { role: "system", content: exports2.MOBILE_SCRIPT_HEAL_SYSTEM_PROMPT },
68359
+ { role: "user", content: userContent }
68360
+ ];
68361
+ let content;
68362
+ try {
68363
+ const response = await (0, ai_retry_js_1.resilientAICall)((signal, arm) => (0, ai_queue_js_1.queuedAICall)(() => {
68364
+ arm();
68365
+ return aiClient.chat.completions.create({ model, messages, max_tokens: 8e3, temperature: 0.1 }, { signal });
68366
+ }), { label: `mobile-heal-attempt-${attempt}`, deferTimeoutUntilArmed: true });
68367
+ content = response?.choices?.[0]?.message?.content ?? "";
68368
+ } catch {
68369
+ markRecoverableTurn();
68370
+ pendingDirective = "The previous attempt did not reach the model. Re-analyze and return one valid JSON verdict.";
68371
+ continue;
68372
+ }
68373
+ const parsed = parseHealVerdict(content);
68374
+ if (!parsed) {
68375
+ markRecoverableTurn();
68376
+ pendingDirective = "Your last response was not valid JSON matching the verdict schema. Return exactly one JSON verdict object.";
68377
+ continue;
68378
+ }
68379
+ if (TERMINAL_VERDICTS.has(parsed.verdict)) {
68380
+ return { passed: false, verdict: parsed.verdict, healReason: parsed.reason, attemptsUsed: attempt };
68381
+ }
68382
+ if (parsed.verdict === "needs_device") {
68383
+ const isFinalAttempt = attempt >= attemptCap && recoverableUsed >= RECOVERABLE_MAX;
68384
+ if (!isFinalAttempt) {
68385
+ markRecoverableTurn();
68386
+ pendingDirective = "You returned needs_device but MUST try a step/locator fix first \u2014 this is not your final attempt. Re-analyze the captured tree and return a concrete fix.";
68387
+ continue;
68388
+ }
68389
+ return {
68390
+ passed: false,
68391
+ verdict: "needs_device",
68392
+ healedSteps: lastHealedSteps,
68393
+ healReason: parsed.reason,
68394
+ attemptsUsed: attempt,
68395
+ verifiedFallbackAvailable: lastHealedSteps !== void 0
68396
+ };
68397
+ }
68398
+ const healedSteps = parsed.steps;
68399
+ if (!healedSteps) {
68400
+ markRecoverableTurn();
68401
+ pendingDirective = 'You returned verdict "fix" but no usable steps array. Return the COMPLETE healed MobileTestStep array.';
68402
+ continue;
68403
+ }
68404
+ if (activeFailingSource && isLocatorNotFound(activeError) && !isDrift(activeError)) {
68405
+ const screen = (0, mobile_source_parser_js_1.parseMobileSource)(activeFailingSource, platform3);
68406
+ const missing = findMissingChangedLocators(baseSteps, healedSteps, screen);
68407
+ if (missing.length > 0) {
68408
+ for (const entry of missing)
68409
+ pushUnique(triedLocators, entry.expressions);
68410
+ markRecoverableTurn();
68411
+ lastVerdict = "fix";
68412
+ pendingDirective = `Your proposed locator ${missing[0].label} does NOT exist in the captured screen tree. Pick an identity locator (resource-id, accessibility-id, or exact @text=) that is PRESENT in the tree.`;
68413
+ continue;
68414
+ }
68415
+ }
68416
+ if (!options.runNativeTest) {
68417
+ lastHealedSteps = healedSteps;
68418
+ lastHealReason = parsed.reason;
68419
+ lastConfidence = parsed.confidence;
68420
+ lastVerdict = "fix";
68421
+ pushUnique(triedLocators, changedStepExpressions(baseSteps, healedSteps));
68422
+ baseSteps = healedSteps;
68423
+ pendingDirective = "The proposed fix could not be device-verified here. If it is not clearly correct, revise it.";
68424
+ continue;
68425
+ }
68426
+ const verify = await options.runNativeTest({ steps: healedSteps, target, testVariables: ctx.testVariables });
68427
+ if (verify.passed) {
68428
+ return {
68429
+ passed: true,
68430
+ verdict: "fix",
68431
+ healedSteps,
68432
+ healReason: parsed.reason,
68433
+ confidence: parsed.confidence,
68434
+ attemptsUsed: attempt
68435
+ };
68436
+ }
68437
+ lastError = verify.error ?? lastError;
68438
+ lastHealedSteps = healedSteps;
68439
+ lastHealReason = parsed.reason;
68440
+ lastConfidence = parsed.confidence;
68441
+ lastVerdict = "fix";
68442
+ noteError(verify.error);
68443
+ pushUnique(triedLocators, changedStepExpressions(baseSteps, healedSteps));
68444
+ if (verify.failingSource)
68445
+ activeFailingSource = verify.failingSource;
68446
+ activeError = verify.error ?? activeError;
68447
+ baseSteps = healedSteps;
68448
+ }
68449
+ return {
68450
+ passed: false,
68451
+ verdict: lastVerdict ?? "fix",
68452
+ healedSteps: lastHealedSteps,
68453
+ healReason: lastHealReason,
68454
+ confidence: lastConfidence,
68455
+ attemptsUsed: attempt,
68456
+ lastError,
68457
+ verifiedFallbackAvailable: lastHealedSteps !== void 0 ? false : void 0
68458
+ };
68459
+ }
68460
+ async function executeMobileTestWithHealing2(steps, target, ctx, options) {
68461
+ const preflight = await tryRegistryPreflight(steps, target, ctx, options);
68462
+ if (preflight)
68463
+ return preflight;
68464
+ const script = await executeMobileScriptDrivenHeal(steps, target, ctx, options);
68465
+ const shouldEscalate = script.verdict === "needs_device" || !script.passed;
68466
+ if (shouldEscalate && options.runLiveHeal) {
68467
+ return options.runLiveHeal({
68468
+ steps: script.healedSteps ?? steps,
68469
+ target,
68470
+ testVariables: ctx.testVariables,
68471
+ options
68472
+ });
68473
+ }
68474
+ return {
68475
+ passed: script.passed,
68476
+ healedSteps: script.healedSteps,
68477
+ healedAppiumCode: script.healedAppiumCode,
68478
+ healReason: script.healReason,
68479
+ verdict: script.verdict,
68480
+ confidence: script.confidence,
68481
+ extraTags: script.extraTags,
68482
+ removeTags: script.removeTags
68483
+ };
68484
+ }
68485
+ var DEFAULT_PHASE2_MAX_PASSES = 6;
68486
+ exports2.MOBILE_LIVE_HEAL_SYSTEM_PROMPT = `You are a QA engineer fixing a failing Appium (mobile UI automation) test with LIVE device access (Phase 2). You receive: the failing test STEPS as JSON, the PRIOR failure error, and the LIVE current screen accessibility tree observed on-device RIGHT NOW. Unlike a frozen failure snapshot, this LIVE tree is the REAL screen the app is on this instant.
68487
+ ## Key insight \u2014 ENTRY-SCREEN DRIFT
68488
+ The recorded flow may have expected a DIFFERENT starting screen than the one shown. When the LIVE screen is an earlier/other screen (e.g. an onboarding or "Get Started" screen), the fix is almost always a MISSING NAVIGATION step: AUTHOR the leading step(s) (e.g. a tap on "Get Started") that reach the recorded first screen, then keep the recorded steps. This is exactly what a static failing-source cannot reveal but a LIVE screen can.
68489
+ ## Analyze
68490
+ 1. Compare the recorded first step's expected screen to the LIVE tree.
68491
+ 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().
68492
+ 3. If a locator is simply wrong, swap it for a stronger identity locator present in the LIVE tree.
68493
+ 3b. If the failing step ASSERTS one-time / data-dependent UI (an empty-state CTA like "Add Your First \u2026") 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.
68494
+ 4. 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.
68495
+ ## Response \u2014 STRICT JSON, exactly one verdict:
68496
+ {"verdict":"fix","steps":[<FULL healed MobileTestStep array, all steps incl. any prepended navigation, order/metadata coherent>],"reason":"what changed and why","confidence":0.0-1.0}
68497
+ {"verdict":"observe","action":{"type":"tap","target":"mobile.text('Get Started')"}}
68498
+ {"verdict":"observe","action":{"type":"back"}}
68499
+ {"verdict":"observe","action":{"type":"relaunch"}}
68500
+ {"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)
68501
+ {"verdict":"app_bug","reason":"app crashed/blank/5xx (NOT rate-limit)"}
68502
+ {"verdict":"config_issue","reason":"429/rate limit/lockout/quota"}
68503
+ {"verdict":"needs_device","reason":"cannot resolve even with live access"}
68504
+ {"verdict":"prereq_unmet","reason":"required entity/state absent for the account"}
68505
+ {"verdict":"state_stale","reason":"leftover data blocks a baseline assertion"}
68506
+ {"verdict":"test_invalid","reason":"scenario cannot be made to pass"}
68507
+ {"verdict":"unhealable_dynamic","reason":"assertion targets non-durable dynamic content"}
68508
+ For a fix, return the COMPLETE steps array (not a diff). Use "observe" only to reveal a screen you cannot yet see; prefer "fix" as soon as the LIVE tree is enough. "observe" with type "tap" REQUIRES a target locator expression; "back"/"relaunch" take no target.`;
68509
+ function parseLiveObserveAction(content) {
68510
+ const cleaned = stripCodeFences(content);
68511
+ let obj = safeJsonParse(cleaned);
68512
+ if (!isRecord(obj)) {
68513
+ const sub = extractBracesSubstring(cleaned);
68514
+ obj = sub ? safeJsonParse(sub) : void 0;
68515
+ }
68516
+ if (!isRecord(obj) || obj.verdict !== "observe")
68517
+ return null;
68518
+ const action = obj.action;
68519
+ if (!isRecord(action))
68520
+ return null;
68521
+ const type = action.type;
68522
+ if (type !== "tap" && type !== "back" && type !== "relaunch" && type !== "reset")
68523
+ return null;
68524
+ const target = typeof action.target === "string" ? action.target : void 0;
68525
+ return { type, target };
68526
+ }
68527
+ async function applyLiveObserveAction(driver, action, screen) {
68528
+ if (action.type === "back") {
68529
+ await driver.back();
68530
+ return;
68531
+ }
68532
+ if (action.type === "relaunch") {
68533
+ await driver.relaunch();
68534
+ return;
68535
+ }
68536
+ if (action.type === "reset") {
68537
+ const cleared = await driver.resetAppState();
68538
+ if (!cleared)
68539
+ await driver.relaunch();
68540
+ return;
68541
+ }
68542
+ if (!action.target)
68543
+ return;
68544
+ const parts = (0, selector_registry_context_js_1.parseMobileLocatorExpression)(action.target);
68545
+ if (!parts)
68546
+ return;
68547
+ const candidate = partsToCandidate(parts);
68548
+ if (!hasIdentitySignal(candidate))
68549
+ return;
68550
+ const first = (0, mobile_source_parser_js_1.resolveLocatorAgainstScreen)(candidate, screen)[0];
68551
+ if (first)
68552
+ await driver.tap(first.bounds);
68553
+ }
68554
+ function buildLiveUserContent(args) {
68555
+ const parts = [];
68556
+ parts.push("## Failing test steps (JSON)");
68557
+ parts.push("```json\n" + JSON.stringify(args.steps, null, 2) + "\n```");
68558
+ parts.push("## Prior failure");
68559
+ parts.push(`Error: ${args.priorError ?? "(none reported)"}`);
68560
+ parts.push("## LIVE current screen (accessibility tree observed on-device NOW)");
68561
+ parts.push(args.observation);
68562
+ return parts.join("\n\n");
68563
+ }
68564
+ async function executeMobileLiveHeal2(args) {
68565
+ const { target, testVariables, options } = args;
68566
+ const liveDriver = options.liveDriver;
68567
+ if (!liveDriver) {
68568
+ return { passed: false, verdict: "needs_device", healReason: "no live driver available" };
68569
+ }
68570
+ const runNativeTest = options.runNativeTest;
68571
+ if (!runNativeTest) {
68572
+ return { passed: false, verdict: "needs_device", healReason: "no native verify seam available" };
68573
+ }
68574
+ const aiClient = options.aiClient ?? (options.model ? (0, ai_provider_js_1.getMobileClientForModel)(options.model) : (0, ai_provider_js_1.getMobileAIClient)());
68575
+ const model = options.model ? (0, ai_provider_js_1.resolveModelForTask)(options.model, "agent") : (0, ai_provider_js_1.getModel)("agent");
68576
+ const maxPasses = envInt2("MOBILE_HEAL_PHASE2_MAX_PASSES") ?? DEFAULT_PHASE2_MAX_PASSES;
68577
+ let baseSteps = args.steps;
68578
+ let priorError = args.priorError ?? null;
68579
+ let bestSteps;
68580
+ let bestStepResults;
68581
+ for (let pass = 1; pass <= maxPasses; pass += 1) {
68582
+ const snap = await liveDriver.snapshot();
68583
+ const screen = (0, mobile_source_parser_js_1.parseMobileSource)(snap.xml, target.platform);
68584
+ const safeScreen = (0, mobile_source_parser_js_1.parseMobileSource)((0, mobile_heal_postprocess_js_1.redactMobileSecretsFromText)(snap.xml, testVariables) ?? snap.xml, target.platform);
68585
+ const observation = (0, mobile_observation_js_1.renderMobileObservation)(safeScreen, { maxElements: OBSERVATION_MAX_ELEMENTS });
68586
+ const messages = [
68587
+ { role: "system", content: exports2.MOBILE_LIVE_HEAL_SYSTEM_PROMPT },
68588
+ {
68589
+ role: "user",
68590
+ content: buildLiveUserContent({
68591
+ steps: baseSteps,
68592
+ priorError: (0, mobile_heal_postprocess_js_1.redactMobileSecretsFromText)(priorError ?? void 0, testVariables) ?? null,
68593
+ observation
68594
+ })
68595
+ }
68596
+ ];
68597
+ let content;
68598
+ try {
68599
+ const response = await (0, ai_retry_js_1.resilientAICall)((signal, arm) => (0, ai_queue_js_1.queuedAICall)(() => {
68600
+ arm();
68601
+ return aiClient.chat.completions.create({ model, messages, max_tokens: 8e3, temperature: 0.1 }, { signal });
68602
+ }), { label: `mobile-live-heal-pass-${pass}`, deferTimeoutUntilArmed: true });
68603
+ content = response?.choices?.[0]?.message?.content ?? "";
68604
+ } catch {
68605
+ continue;
68606
+ }
68607
+ const observe = parseLiveObserveAction(content);
68608
+ if (observe) {
68609
+ await applyLiveObserveAction(liveDriver, observe, screen);
68610
+ continue;
68611
+ }
68612
+ const parsed = parseHealVerdict(content);
68613
+ if (!parsed)
68614
+ continue;
68615
+ if (TERMINAL_VERDICTS.has(parsed.verdict)) {
68616
+ return { passed: false, verdict: parsed.verdict, healReason: parsed.reason, healedSteps: bestSteps };
68617
+ }
68618
+ if (parsed.verdict !== "fix" || !parsed.steps)
68619
+ continue;
68620
+ const healedSteps = parsed.steps;
68621
+ const verify = await runNativeTest({ steps: healedSteps, target, testVariables });
68622
+ if (verify.passed) {
68623
+ return {
68624
+ passed: true,
68625
+ verdict: "fix",
68626
+ healedSteps,
68627
+ healReason: parsed.reason,
68628
+ confidence: parsed.confidence,
68629
+ stepResults: verify.stepResults
68630
+ };
68631
+ }
68632
+ baseSteps = healedSteps;
68633
+ bestSteps = healedSteps;
68634
+ bestStepResults = verify.stepResults;
68635
+ priorError = verify.error ?? priorError;
68636
+ }
68637
+ return {
68638
+ passed: false,
68639
+ verdict: "needs_device",
68640
+ healedSteps: bestSteps,
68641
+ healReason: "live heal exhausted",
68642
+ stepResults: bestStepResults
68643
+ };
68644
+ }
68645
+ }
68646
+ });
68647
+
67370
68648
  // ../runner-core/dist/services/browser-config.js
67371
68649
  var require_browser_config = __commonJS({
67372
68650
  "../runner-core/dist/services/browser-config.js"(exports2) {
@@ -293115,282 +294393,6 @@ var require_preflight_syntax = __commonJS({
293115
294393
  }
293116
294394
  });
293117
294395
 
293118
- // ../runner-core/dist/services/selector-registry-context.js
293119
- var require_selector_registry_context = __commonJS({
293120
- "../runner-core/dist/services/selector-registry-context.js"(exports2) {
293121
- "use strict";
293122
- Object.defineProperty(exports2, "__esModule", { value: true });
293123
- exports2.normalizeSelectorRegistryEntries = normalizeSelectorRegistryEntries;
293124
- exports2.formatSelectorRegistryContextForPrompt = formatSelectorRegistryContextForPrompt;
293125
- exports2.collectRegistryCandidates = collectRegistryCandidates;
293126
- exports2.buildRegistryCandidateBlock = buildRegistryCandidateBlock;
293127
- exports2.planRegistryFallbackFix = planRegistryFallbackFix;
293128
- exports2.substituteSelectorInCode = substituteSelectorInCode;
293129
- function isRecord(value) {
293130
- return value !== null && typeof value === "object" && !Array.isArray(value);
293131
- }
293132
- function asString(value, fallback = "") {
293133
- return typeof value === "string" ? value : fallback;
293134
- }
293135
- function asNumber(value, fallback = 0) {
293136
- return typeof value === "number" && Number.isFinite(value) ? value : fallback;
293137
- }
293138
- function asStringArray(value) {
293139
- return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
293140
- }
293141
- function truncateForSelectorPrompt(value, maxLength = 180) {
293142
- const normalized = (value ?? "").replace(/\s+/g, " ").trim();
293143
- if (normalized.length <= maxLength)
293144
- return normalized;
293145
- return `${normalized.slice(0, Math.max(0, maxLength - 3))}...`;
293146
- }
293147
- function inlineCode(value, maxLength = 180) {
293148
- return `\`${truncateForSelectorPrompt(value, maxLength).replace(/`/g, "'")}\``;
293149
- }
293150
- function normalizeRef(value) {
293151
- if (!isRecord(value))
293152
- return null;
293153
- const expression = asString(value.expression).trim();
293154
- if (!expression)
293155
- return null;
293156
- return {
293157
- route: asString(value.route, "*"),
293158
- usage: asString(value.usage, "locator"),
293159
- source: asString(value.source, "generated"),
293160
- expression,
293161
- occurrenceIndex: asNumber(value.occurrenceIndex, 0)
293162
- };
293163
- }
293164
- function normalizeSibling(value) {
293165
- if (!isRecord(value))
293166
- return null;
293167
- const testCaseId = asString(value.testCaseId).trim();
293168
- const expression = asString(value.expression).trim();
293169
- if (!testCaseId || !expression)
293170
- return null;
293171
- return {
293172
- testCaseId,
293173
- name: asString(value.name, testCaseId),
293174
- suite: typeof value.suite === "string" ? value.suite : null,
293175
- lastPassedAt: typeof value.lastPassedAt === "string" ? value.lastPassedAt : null,
293176
- expression,
293177
- usage: asString(value.usage, "locator"),
293178
- route: asString(value.route, "*"),
293179
- source: asString(value.source, "generated")
293180
- };
293181
- }
293182
- function normalizeEntry(value) {
293183
- if (!isRecord(value))
293184
- return null;
293185
- const id = asString(value.id).trim();
293186
- const expression = asString(value.expression).trim();
293187
- if (!id || !expression)
293188
- return null;
293189
- return {
293190
- id,
293191
- key: asString(value.key, id),
293192
- route: asString(value.route, "*"),
293193
- scope: asString(value.scope, "page"),
293194
- status: asString(value.status, "ACTIVE"),
293195
- stability: asNumber(value.stability, 1),
293196
- label: asString(value.label),
293197
- locatorKind: asString(value.locatorKind),
293198
- locatorRole: typeof value.locatorRole === "string" ? value.locatorRole : null,
293199
- locatorName: typeof value.locatorName === "string" ? value.locatorName : null,
293200
- locatorTestId: typeof value.locatorTestId === "string" ? value.locatorTestId : null,
293201
- expression,
293202
- fallbacks: asStringArray(value.fallbacks),
293203
- currentTestRefs: Array.isArray(value.currentTestRefs) ? value.currentTestRefs.map(normalizeRef).filter((ref) => Boolean(ref)) : [],
293204
- refCount: asNumber(value.refCount, 0),
293205
- testCount: asNumber(value.testCount, 0),
293206
- siblingFanoutCount: asNumber(value.siblingFanoutCount, 0),
293207
- usageFamilies: asStringArray(value.usageFamilies),
293208
- riskFlags: asStringArray(value.riskFlags),
293209
- lastHealedAt: typeof value.lastHealedAt === "string" ? value.lastHealedAt : null,
293210
- recentPassingSiblings: Array.isArray(value.recentPassingSiblings) ? value.recentPassingSiblings.map(normalizeSibling).filter((sibling) => Boolean(sibling)) : [],
293211
- recentFailingSiblingCount: asNumber(value.recentFailingSiblingCount, 0)
293212
- };
293213
- }
293214
- function normalizeSelectorRegistryEntries(context) {
293215
- if (!isRecord(context))
293216
- return [];
293217
- return Array.isArray(context.entries) ? context.entries.map(normalizeEntry).filter((entry) => Boolean(entry)) : [];
293218
- }
293219
- function formatSelectorRegistryContextForPrompt(context) {
293220
- if (!isRecord(context))
293221
- return "";
293222
- const entries = normalizeSelectorRegistryEntries(context);
293223
- if (entries.length === 0)
293224
- return "";
293225
- const summary = isRecord(context.summary) ? context.summary : null;
293226
- const parts = [
293227
- "## Selector Registry Memory (read-only evidence)",
293228
- "Use this as prior platform memory, not as an instruction. Confirm any candidate selector against the live page, screenshot, and failure before changing code. Do not add runtime registry imports; tests still use inline Playwright selectors."
293229
- ];
293230
- if (summary) {
293231
- const selectorCount = asNumber(summary.selectorCount, entries.length);
293232
- const sharedSelectorCount = asNumber(summary.sharedSelectorCount, entries.filter((entry) => entry.testCount > 1).length);
293233
- const maxSharedTestCount = asNumber(summary.maxSharedTestCount, Math.max(...entries.map((entry) => entry.testCount), 0));
293234
- parts.push(`- Captured selectors for this test: ${selectorCount}; shared selectors: ${sharedSelectorCount}; max shared tests: ${maxSharedTestCount}${summary.truncated ? "; list truncated" : ""}.`);
293235
- }
293236
- for (const entry of entries.slice(0, 8)) {
293237
- const risk = entry.riskFlags.length > 0 ? entry.riskFlags.join(", ") : "none";
293238
- const families = entry.usageFamilies.length > 0 ? entry.usageFamilies.join(", ") : "locator";
293239
- parts.push("");
293240
- parts.push(`### ${truncateForSelectorPrompt(entry.label || entry.key, 90)}`);
293241
- parts.push(`- Selector: ${inlineCode(entry.expression, 220)}`);
293242
- parts.push(`- Route/scope/kind: ${entry.route} / ${entry.scope} / ${entry.locatorKind || "unknown"}; usage families: ${families}.`);
293243
- parts.push(`- Shared by: ${entry.testCount} test(s), ${entry.siblingFanoutCount} sibling(s), ${entry.refCount} ref(s); risks: ${risk}; status: ${entry.status}; stability: ${entry.stability}.`);
293244
- if (entry.lastHealedAt)
293245
- parts.push(`- Last registry heal: ${entry.lastHealedAt}.`);
293246
- const currentRefs = entry.currentTestRefs.slice(0, 3);
293247
- if (currentRefs.length > 0) {
293248
- parts.push("- Current test occurrences:");
293249
- for (const ref of currentRefs) {
293250
- parts.push(` - ${ref.usage} on ${ref.route} from ${ref.source}: ${inlineCode(ref.expression, 180)}`);
293251
- }
293252
- }
293253
- const siblings = entry.recentPassingSiblings.slice(0, 3);
293254
- if (siblings.length > 0) {
293255
- parts.push("- Recent passing sibling tests using this registry entry:");
293256
- for (const sibling of siblings) {
293257
- const suite = sibling.suite ? ` (${truncateForSelectorPrompt(sibling.suite, 50)})` : "";
293258
- const passed = sibling.lastPassedAt ? ` passed ${sibling.lastPassedAt}` : "";
293259
- parts.push(` - ${truncateForSelectorPrompt(sibling.name, 80)}${suite}${passed}: ${inlineCode(sibling.expression, 180)}`);
293260
- }
293261
- }
293262
- if (entry.recentFailingSiblingCount && entry.recentFailingSiblingCount > 0) {
293263
- parts.push(`- Other recent failing siblings on this entry: ${entry.recentFailingSiblingCount}.`);
293264
- }
293265
- const fallbacks = (entry.fallbacks ?? []).slice(0, 3);
293266
- if (fallbacks.length > 0) {
293267
- parts.push(`- Registry fallbacks: ${fallbacks.map((fallback) => inlineCode(fallback, 120)).join(", ")}.`);
293268
- }
293269
- }
293270
- return `${parts.join("\n")}
293271
- `;
293272
- }
293273
- function selectorKey(expression) {
293274
- return expression.trim().replace(/^page\s*\.\s*/, "").replace(/\s+/g, " ").replace(/"/g, "'").trim();
293275
- }
293276
- function collectRegistryCandidates(context) {
293277
- const entries = normalizeSelectorRegistryEntries(context).slice(0, 8);
293278
- const seen = /* @__PURE__ */ new Set();
293279
- const ranked = [[], [], []];
293280
- for (const entry of entries) {
293281
- const entryLabel = entry.label || entry.key;
293282
- for (const sibling of entry.recentPassingSiblings) {
293283
- const key = selectorKey(sibling.expression);
293284
- if (seen.has(key))
293285
- continue;
293286
- seen.add(key);
293287
- ranked[0].push({ expression: sibling.expression, source: "passing-sibling", entryLabel, siblingName: sibling.name });
293288
- }
293289
- const entryKey = selectorKey(entry.expression);
293290
- if (!seen.has(entryKey)) {
293291
- seen.add(entryKey);
293292
- ranked[1].push({ expression: entry.expression, source: "registry-entry", entryLabel });
293293
- }
293294
- for (const fallback of entry.fallbacks ?? []) {
293295
- const key = selectorKey(fallback);
293296
- if (seen.has(key))
293297
- continue;
293298
- seen.add(key);
293299
- ranked[2].push({ expression: fallback, source: "fallback", entryLabel });
293300
- }
293301
- }
293302
- return ranked.flat();
293303
- }
293304
- function buildRegistryCandidateBlock(context, excludeExpressions) {
293305
- const exclude = new Set(excludeExpressions.map(selectorKey));
293306
- const candidates = collectRegistryCandidates(context).filter((candidate) => !exclude.has(selectorKey(candidate.expression))).slice(0, 6);
293307
- if (candidates.length === 0)
293308
- return "";
293309
- const lines = [
293310
- "## Untried Selector Candidates (from registry memory)",
293311
- "Ranked alternatives for elements this test uses, from the platform selector registry. Verify each against the screenshot and error before adopting \u2014 do not adopt blindly."
293312
- ];
293313
- for (const candidate of candidates) {
293314
- const provenance = candidate.source === "passing-sibling" ? `proven in passing sibling "${truncateForSelectorPrompt(candidate.siblingName, 80)}"` : candidate.source === "registry-entry" ? `registry entry for "${truncateForSelectorPrompt(candidate.entryLabel, 80)}"` : `registry fallback for "${truncateForSelectorPrompt(candidate.entryLabel, 80)}"`;
293315
- lines.push(`- ${inlineCode(candidate.expression, 180)} \u2014 ${provenance}`);
293316
- }
293317
- return lines.join("\n");
293318
- }
293319
- function findExpressionInCode(code, expression) {
293320
- const trimmed = expression.trim();
293321
- if (trimmed && code.includes(trimmed))
293322
- return trimmed;
293323
- const withoutPage = trimmed.replace(/^page\s*\.\s*/, "");
293324
- if (withoutPage !== trimmed && withoutPage && code.includes(withoutPage))
293325
- return withoutPage;
293326
- const withPage = `page.${withoutPage}`;
293327
- if (withPage !== trimmed && code.includes(withPage))
293328
- return withPage;
293329
- return null;
293330
- }
293331
- function extractFailureFocus(error2) {
293332
- const focus = error2.split(/\r?\n/).filter((line) => /^\s*>/.test(line) || /waiting for|locator resolved to/i.test(line) || /^\s*locator:/i.test(line));
293333
- return focus.length > 0 ? focus.join("\n") : error2;
293334
- }
293335
- function planRegistryFallbackFix(args) {
293336
- const { code, error: error2, context } = args;
293337
- if (!error2 || !code)
293338
- return null;
293339
- const entries = normalizeSelectorRegistryEntries(context).slice(0, 8);
293340
- if (entries.length === 0)
293341
- return null;
293342
- const errorKey = selectorKey(extractFailureFocus(error2));
293343
- for (const entry of entries) {
293344
- const failingExpressions = [entry.expression, ...entry.currentTestRefs.map((ref) => ref.expression)];
293345
- const failingSeen = /* @__PURE__ */ new Set();
293346
- for (const failing of failingExpressions) {
293347
- const failingKey = selectorKey(failing);
293348
- if (!failingKey || failingSeen.has(failingKey))
293349
- continue;
293350
- failingSeen.add(failingKey);
293351
- if (!errorKey.includes(failingKey))
293352
- continue;
293353
- const matchedInCode = findExpressionInCode(code, failing);
293354
- if (!matchedInCode)
293355
- continue;
293356
- const entryLabel = entry.label || entry.key;
293357
- const candidateSeen = /* @__PURE__ */ new Set([failingKey]);
293358
- const candidates = [];
293359
- for (const fallback of entry.fallbacks ?? []) {
293360
- const key = selectorKey(fallback);
293361
- if (!key || candidateSeen.has(key) || code.includes(fallback.trim()))
293362
- continue;
293363
- candidateSeen.add(key);
293364
- candidates.push({ expression: fallback, source: "fallback", entryLabel });
293365
- }
293366
- for (const sibling of entry.recentPassingSiblings) {
293367
- const key = selectorKey(sibling.expression);
293368
- if (!key || candidateSeen.has(key) || code.includes(sibling.expression.trim()))
293369
- continue;
293370
- candidateSeen.add(key);
293371
- candidates.push({ expression: sibling.expression, source: "passing-sibling", entryLabel, siblingName: sibling.name });
293372
- }
293373
- if (candidates.length === 0)
293374
- continue;
293375
- return { matchedInCode, entryLabel, candidates };
293376
- }
293377
- }
293378
- return null;
293379
- }
293380
- function substituteSelectorInCode(code, matchedInCode, replacement) {
293381
- const target = matchedInCode.trim();
293382
- let normalized = replacement.trim();
293383
- const targetHasPage = /^page\s*\.\s*/.test(target);
293384
- const replacementHasPage = /^page\s*\.\s*/.test(normalized);
293385
- if (targetHasPage && !replacementHasPage)
293386
- normalized = `page.${normalized}`;
293387
- if (!targetHasPage && replacementHasPage)
293388
- normalized = normalized.replace(/^page\s*\.\s*/, "");
293389
- return code.split(target).join(normalized);
293390
- }
293391
- }
293392
- });
293393
-
293394
294396
  // ../runner-core/dist/services/heal-selector-ledger.js
293395
294397
  var require_heal_selector_ledger = __commonJS({
293396
294398
  "../runner-core/dist/services/heal-selector-ledger.js"(exports2) {
@@ -313796,7 +314798,7 @@ var require_mobile_discovery_agent = __commonJS({
313796
314798
  log2(exploreAppDataCleared ? "App data cleared \u2014 exploring from a deterministic cold (logged-out) state." : "App data reset unavailable (platform/device policy) \u2014 exploring the app in its current state.");
313797
314799
  const state2 = new mobile_exploration_state_js_1.MobileExplorationState();
313798
314800
  const maxIterations = getMobileExploreBudget(mode, ctx.incremental);
313799
- const existingScreens = compactExistingScreens(ctx.existingSiteMap);
314801
+ const existingScreens = isSurvey && ctx.incremental ? compactExistingScreens(ctx.existingSiteMap) : void 0;
313800
314802
  const explore = await runExplore({
313801
314803
  ctx,
313802
314804
  driver,
@@ -328144,8 +329146,9 @@ var require_dist2 = __commonJS({
328144
329146
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
328145
329147
  };
328146
329148
  Object.defineProperty(exports2, "__esModule", { value: true });
328147
- exports2.buildRepoMapContractMd = exports2.buildRepoMemorySystemRules = exports2.buildRepoMemoryKickoff = exports2.buildRepoMemoryContractMd = exports2.runRepoAnalysisOnRunner = exports2.IMPORT_SCHEMA_VERSION = exports2.validateImportResultFile = exports2.validateImportedTest = exports2.buildImportSystemRules = exports2.buildImportKickoff = exports2.buildImportContractMd = exports2.MAX_ARCHIVE_BYTES = exports2.isUnsafeEntryName = exports2.extractZipSafely = exports2.downloadArchiveCapped = exports2.detectArchiveKind = exports2.acquireRepoForImport = exports2.runFrameworkImportOnRunner = exports2.getAgenticEngine = exports2.resolveRefFromSnapshot = exports2.replayAuthRecipeIntoBrowser = exports2.runRegisterCaptureRun = exports2.runLoginCaptureRun = exports2.AUTH_MARKER_VERSION = exports2.buildHealAuthStamp = exports2.extractAuthRegion = exports2.upsertAuthBlock = exports2.buildAuthRecipe = exports2.commandToReplayStep = exports2.buildReplayPlan = exports2.absoluteRoute = exports2.renderReplaySettleArrow = exports2.renderReplayClickArrow = exports2.renderAuthFn = exports2.canonicalizeRoute = exports2.executeGrokPerBatchHeal = exports2.executeGrokPerTestHeal = exports2.headerVal = exports2.classifyAuthType = exports2.isTextExcerptable = exports2.isStaticAssetByExt = exports2.isApiCall = exports2.buildApiCallSummary = exports2.runMobileGeneratePhase = exports2.runMobileAIPlanner = exports2.buildMobileSiteMap = exports2.formatMobileEvidenceForPlanner = exports2.MOBILE_SCENARIO_SYSTEM_PROMPT = exports2.MOBILE_SURVEY_SYSTEM_PROMPT = exports2.runMobileExplorePhase = void 0;
328148
- exports2.UNSUPPORTED_RENDERER_PREFIX = exports2.UnsupportedRendererError = exports2.buildCanvasModeAuthoringAddendum = exports2.buildUnsupportedRendererMessage = exports2.modelSupportsVision = exports2.decideCanvasStrategy = exports2.decideAppRenderType = exports2.detectCanvasApp = exports2.detectRateLimitBlock = exports2.isSafeCanonicalRedirect = exports2.resolveBaseUrlPreflight = exports2.checkBaseUrlRedirect = exports2.stripJsonFences = exports2.scrubCredentials = exports2.withAIRetry = exports2.snapshotMatchingChildren = exports2.findNewChromiumChildPid = exports2.killProcessTree = exports2.gracefulCloseWithTreeKill = exports2.liveBrowserRegistry = exports2.REPO_SWITCH_REMOVED_FRACTION = exports2.MAX_MANIFEST_FILES = exports2.toDiffSummary = exports2.isLikelyTestFile = exports2.sanitizeRepoRelPath = exports2.sha256Hex = exports2.hashFiles = exports2.enumerateTestFiles = exports2.buildNextManifest = exports2.detectRepoSwitch = exports2.classifyImportDiff = exports2.parseImportManifest = exports2.REPO_ANALYSIS_SCHEMA_VERSION = exports2.validateSourceEndpoints = exports2.validateAuthoredTest = exports2.validateRepoMapFile = exports2.validateRepoMemoryFile = exports2.buildTestingStandardsSection = exports2.buildRepoAuthorSystemRules = exports2.buildRepoAuthorKickoff = exports2.buildRepoAuthorContractMd = exports2.buildRepoMapSystemRules = exports2.buildRepoMapKickoff = void 0;
329149
+ exports2.buildImportSystemRules = exports2.buildImportKickoff = exports2.buildImportContractMd = exports2.MAX_ARCHIVE_BYTES = exports2.isUnsafeEntryName = exports2.extractZipSafely = exports2.downloadArchiveCapped = exports2.detectArchiveKind = exports2.acquireRepoForImport = exports2.runFrameworkImportOnRunner = exports2.getAgenticEngine = exports2.resolveRefFromSnapshot = exports2.replayAuthRecipeIntoBrowser = exports2.runRegisterCaptureRun = exports2.runLoginCaptureRun = exports2.AUTH_MARKER_VERSION = exports2.buildHealAuthStamp = exports2.extractAuthRegion = exports2.upsertAuthBlock = exports2.buildAuthRecipe = exports2.commandToReplayStep = exports2.buildReplayPlan = exports2.absoluteRoute = exports2.renderReplaySettleArrow = exports2.renderReplayClickArrow = exports2.renderAuthFn = exports2.canonicalizeRoute = exports2.executeGrokPerBatchHeal = exports2.executeGrokPerTestHeal = exports2.headerVal = exports2.classifyAuthType = exports2.isTextExcerptable = exports2.isStaticAssetByExt = exports2.isApiCall = exports2.buildApiCallSummary = exports2.computeMobileHealOutcome = exports2.detectMobileStepSecretLeak = exports2.redactMobileSecretsFromText = exports2.MOBILE_LIVE_HEAL_SYSTEM_PROMPT = exports2.MOBILE_SCRIPT_HEAL_SYSTEM_PROMPT = exports2.executeMobileLiveHeal = exports2.executeMobileTestWithHealing = exports2.executeMobileScriptDrivenHeal = exports2.runMobileGeneratePhase = exports2.runMobileAIPlanner = exports2.buildMobileSiteMap = exports2.formatMobileEvidenceForPlanner = exports2.MOBILE_SCENARIO_SYSTEM_PROMPT = exports2.MOBILE_SURVEY_SYSTEM_PROMPT = exports2.runMobileExplorePhase = void 0;
329150
+ exports2.UnsupportedRendererError = exports2.buildCanvasModeAuthoringAddendum = exports2.buildUnsupportedRendererMessage = exports2.modelSupportsVision = exports2.decideCanvasStrategy = exports2.decideAppRenderType = exports2.detectCanvasApp = exports2.detectRateLimitBlock = exports2.isSafeCanonicalRedirect = exports2.resolveBaseUrlPreflight = exports2.checkBaseUrlRedirect = exports2.stripJsonFences = exports2.scrubCredentials = exports2.withAIRetry = exports2.snapshotMatchingChildren = exports2.findNewChromiumChildPid = exports2.killProcessTree = exports2.gracefulCloseWithTreeKill = exports2.liveBrowserRegistry = exports2.REPO_SWITCH_REMOVED_FRACTION = exports2.MAX_MANIFEST_FILES = exports2.toDiffSummary = exports2.isLikelyTestFile = exports2.sanitizeRepoRelPath = exports2.sha256Hex = exports2.hashFiles = exports2.enumerateTestFiles = exports2.buildNextManifest = exports2.detectRepoSwitch = exports2.classifyImportDiff = exports2.parseImportManifest = exports2.REPO_ANALYSIS_SCHEMA_VERSION = exports2.validateSourceEndpoints = exports2.validateAuthoredTest = exports2.validateRepoMapFile = exports2.validateRepoMemoryFile = exports2.buildTestingStandardsSection = exports2.buildRepoAuthorSystemRules = exports2.buildRepoAuthorKickoff = exports2.buildRepoAuthorContractMd = exports2.buildRepoMapSystemRules = exports2.buildRepoMapKickoff = exports2.buildRepoMapContractMd = exports2.buildRepoMemorySystemRules = exports2.buildRepoMemoryKickoff = exports2.buildRepoMemoryContractMd = exports2.runRepoAnalysisOnRunner = exports2.IMPORT_SCHEMA_VERSION = exports2.validateImportResultFile = exports2.validateImportedTest = void 0;
329151
+ exports2.UNSUPPORTED_RENDERER_PREFIX = void 0;
328149
329152
  __exportStar(require_ai_provider(), exports2);
328150
329153
  __exportStar(require_mobile_types(), exports2);
328151
329154
  __exportStar(require_mobile_source_parser(), exports2);
@@ -328174,6 +329177,32 @@ var require_dist2 = __commonJS({
328174
329177
  Object.defineProperty(exports2, "runMobileGeneratePhase", { enumerable: true, get: function() {
328175
329178
  return mobile_generator_js_1.runMobileGeneratePhase;
328176
329179
  } });
329180
+ var mobile_heal_loop_js_1 = require_mobile_heal_loop();
329181
+ Object.defineProperty(exports2, "executeMobileScriptDrivenHeal", { enumerable: true, get: function() {
329182
+ return mobile_heal_loop_js_1.executeMobileScriptDrivenHeal;
329183
+ } });
329184
+ Object.defineProperty(exports2, "executeMobileTestWithHealing", { enumerable: true, get: function() {
329185
+ return mobile_heal_loop_js_1.executeMobileTestWithHealing;
329186
+ } });
329187
+ Object.defineProperty(exports2, "executeMobileLiveHeal", { enumerable: true, get: function() {
329188
+ return mobile_heal_loop_js_1.executeMobileLiveHeal;
329189
+ } });
329190
+ Object.defineProperty(exports2, "MOBILE_SCRIPT_HEAL_SYSTEM_PROMPT", { enumerable: true, get: function() {
329191
+ return mobile_heal_loop_js_1.MOBILE_SCRIPT_HEAL_SYSTEM_PROMPT;
329192
+ } });
329193
+ Object.defineProperty(exports2, "MOBILE_LIVE_HEAL_SYSTEM_PROMPT", { enumerable: true, get: function() {
329194
+ return mobile_heal_loop_js_1.MOBILE_LIVE_HEAL_SYSTEM_PROMPT;
329195
+ } });
329196
+ var mobile_heal_postprocess_js_1 = require_mobile_heal_postprocess();
329197
+ Object.defineProperty(exports2, "redactMobileSecretsFromText", { enumerable: true, get: function() {
329198
+ return mobile_heal_postprocess_js_1.redactMobileSecretsFromText;
329199
+ } });
329200
+ Object.defineProperty(exports2, "detectMobileStepSecretLeak", { enumerable: true, get: function() {
329201
+ return mobile_heal_postprocess_js_1.detectMobileStepSecretLeak;
329202
+ } });
329203
+ Object.defineProperty(exports2, "computeMobileHealOutcome", { enumerable: true, get: function() {
329204
+ return mobile_heal_postprocess_js_1.computeMobileHealOutcome;
329205
+ } });
328177
329206
  __exportStar(require_browser_config(), exports2);
328178
329207
  __exportStar(require_mcp(), exports2);
328179
329208
  var api_call_redaction_js_1 = require_api_call_redaction();
@@ -328483,7 +329512,7 @@ var require_package4 = __commonJS({
328483
329512
  "package.json"(exports2, module2) {
328484
329513
  module2.exports = {
328485
329514
  name: "@validate.qa/runner",
328486
- version: "1.0.24",
329515
+ version: "1.0.26",
328487
329516
  description: "validate local test runner - execute Playwright tests on your machine, connected to validate.qa cloud.",
328488
329517
  bin: {
328489
329518
  "validate-runner": "dist/cli.js"
@@ -331204,9 +332233,18 @@ async function executeMobileTest(options) {
331204
332233
  let entryDrift = false;
331205
332234
  const runPlatform = options.target.platform;
331206
332235
  const isCrossPlatform = options.target.authoringPlatform != null && options.target.authoringPlatform !== runPlatform;
331207
- const entryStep = runSteps.find(
332236
+ const CONTAINER_ONLY_ID_RE = /(?:^|[:/])id\/(webview|content|decor|decor_content_parent|action_bar_root|statusBarBackground|navigationBarBackground)$|^(?:main-content|root|app|app-root|__next|react-root|application)$/i;
332237
+ const isContainerOnlyEntryTarget = (target) => {
332238
+ const primary = target?.primary?.trim() ?? "";
332239
+ if (primary === "") return false;
332240
+ const m = primary.match(/^mobile\.(?:resourceId|accessibilityId)\('([^']+)'\)$/);
332241
+ const value = m ? m[1] : primary;
332242
+ return CONTAINER_ONLY_ID_RE.test(value);
332243
+ };
332244
+ const identityBearingSteps = runSteps.filter(
331208
332245
  (s) => s.action !== "launchApp" && stepAppliesToPlatform(s, runPlatform) && buildIdentityLocatorStrategies(s.target, runPlatform).length > 0
331209
332246
  );
332247
+ const entryStep = identityBearingSteps.find((s) => !isContainerOnlyEntryTarget(s.target)) ?? identityBearingSteps[0];
331210
332248
  if (entryStep) {
331211
332249
  try {
331212
332250
  const entryTimeout = recordedFromClearedState ? Math.max(DEFAULT_STEP_TIMEOUT_MS, COLD_BOOT_ENTRY_TIMEOUT_MS) : DEFAULT_STEP_TIMEOUT_MS;