@sedum-dev/core 0.1.0-alpha.0 → 0.1.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -785,7 +785,7 @@ function projectCandidates(page) {
785
785
  if (!page.complete || page.candidates.length > CANDIDATE_LIMIT)
786
786
  throw new Error("candidate_set_incomplete");
787
787
  return page.candidates.map((candidate) => {
788
- if (codePoints(candidate.name) > NAME_LIMIT || candidate.role !== "" && !isSafeRole(candidate.role) || candidate.peers.length > 2 || candidate.peers.some((peer) => codePoints(peer) > PEER_LIMIT))
788
+ if (codePoints(candidate.name) > NAME_LIMIT || candidate.role !== "" && !isSafeRole(candidate.role) || candidate.peers.length > 2 || candidate.peers.some((peer) => codePoints(peer) > PEER_LIMIT) || candidate.location !== void 0 && codePoints(candidate.location) > PEER_LIMIT)
789
789
  throw new Error("candidate_field_too_large");
790
790
  return {
791
791
  id: candidate.ref,
@@ -793,6 +793,7 @@ function projectCandidates(page) {
793
793
  role: candidate.role,
794
794
  name: candidate.name,
795
795
  peers: candidate.peers,
796
+ ...candidate.location ? { location: candidate.location } : {},
796
797
  editable: candidate.editable,
797
798
  disabled: candidate.disabled
798
799
  };
@@ -877,7 +878,7 @@ function hasTargetContext(sentence, label, context) {
877
878
  return contextClues(sentence, label).some((word) => contextWords.has(word));
878
879
  }
879
880
  function stageEntry(key, route, operation, sentence, candidate, eligible) {
880
- if (codePoints(candidate.name) > NAME_LIMIT || candidate.role !== "" && !isSafeRole(candidate.role) || candidate.peers.length > 2 || candidate.peers.some((peer) => codePoints(peer) > PEER_LIMIT))
881
+ if (candidate.signals.nameTruncated || codePoints(candidate.name) > NAME_LIMIT || candidate.role !== "" && !isSafeRole(candidate.role) || candidate.peers.length > 2 || candidate.peers.some((peer) => codePoints(peer) > PEER_LIMIT))
881
882
  throw new RangeError("Candidate exceeds cache signal bounds");
882
883
  if (candidate.tag === "input" && !candidate.editable)
883
884
  throw new Error("candidate_not_distinguishable");
@@ -923,6 +924,8 @@ function stageEntry(key, route, operation, sentence, candidate, eligible) {
923
924
  return entry;
924
925
  }
925
926
  function score(entry, candidate, key) {
927
+ if (candidate.signals.nameTruncated)
928
+ return { score: 0, conflict: false, identity: false };
926
929
  if (entry.tag !== candidate.tag || entry.role !== candidate.role || entry.inputType !== candidate.inputType || entry.editable !== candidate.editable || entry.disabled !== candidate.disabled)
927
930
  return { score: 0, conflict: false, identity: false };
928
931
  let points = 0;
@@ -1000,7 +1003,7 @@ function validVersion(value) {
1000
1003
  }
1001
1004
  function validPage(value) {
1002
1005
  return !!value && value.protocol === PAGE_PROTOCOL && validVersion(value.version) && Number.isInteger(value.total) && value.total >= 0 && Number.isInteger(value.offset) && value.offset >= 0 && (value.next === null || Number.isInteger(value.next) && value.next > value.offset) && typeof value.complete === "boolean" && Array.isArray(value.candidates) && value.candidates.every(
1003
- (item) => typeof item.ref === "string" && typeof item.name === "string" && typeof item.tag === "string" && typeof item.role === "string" && Array.isArray(item.peers) && typeof item.disabled === "boolean" && typeof item.editable === "boolean" && !!item.signals && typeof item.signals.path === "string"
1006
+ (item) => typeof item.ref === "string" && typeof item.name === "string" && typeof item.tag === "string" && typeof item.role === "string" && Array.isArray(item.peers) && (item.location === void 0 || typeof item.location === "string") && typeof item.disabled === "boolean" && typeof item.editable === "boolean" && !!item.signals && typeof item.signals.path === "string"
1004
1007
  );
1005
1008
  }
1006
1009
  async function call(page, method, argument) {
@@ -1477,9 +1480,16 @@ var PlaywrightPage = class {
1477
1480
  ).catch(() => ({ actionable: false, reason: "stale" }));
1478
1481
  if (!checked.actionable) return checked;
1479
1482
  const handle = await this.page.evaluateHandle((ref) => {
1480
- const matches = Array.from(
1481
- document.querySelectorAll("[data-sedum-ref]")
1482
- ).filter((element) => element.getAttribute("data-sedum-ref") === ref);
1483
+ const matches = [];
1484
+ const roots = [document];
1485
+ while (roots.length) {
1486
+ const root = roots.pop();
1487
+ for (const element of Array.from(root.querySelectorAll("*"))) {
1488
+ if (element.getAttribute("data-sedum-ref") === ref)
1489
+ matches.push(element);
1490
+ if (element.shadowRoot) roots.push(element.shadowRoot);
1491
+ }
1492
+ }
1483
1493
  return matches.length === 1 ? matches[0] : null;
1484
1494
  }, aim.ref).catch(() => null);
1485
1495
  if (!handle) return { actionable: false, reason: "stale" };
@@ -2175,52 +2185,20 @@ var MAX_SENTENCE_POINTS = 512;
2175
2185
  var MAX_PARALLEL_CHOICES = 4;
2176
2186
  var MIN_CONFIDENCE = 0.3;
2177
2187
  var MIN_LEAD = 0.1;
2178
- var WEAK_MEMBER_WORDS = /* @__PURE__ */ new Set([
2179
- "a",
2180
- "add",
2181
- "an",
2182
- "and",
2183
- "article",
2184
- "at",
2185
- "body",
2186
- "button",
2187
- "by",
2188
- "cart",
2189
- "control",
2190
- "entry",
2191
- "field",
2192
- "first",
2193
- "for",
2194
- "from",
2195
- "in",
2196
- "input",
2197
- "item",
2198
- "label",
2199
- "last",
2200
- "link",
2201
- "list",
2202
- "more",
2203
- "of",
2204
- "on",
2205
- "option",
2206
- "or",
2207
- "page",
2208
- "post",
2209
- "product",
2210
- "result",
2211
- "results",
2212
- "story",
2213
- "that",
2214
- "the",
2215
- "thing",
2216
- "this",
2217
- "to",
2218
- "with"
2219
- ]);
2220
2188
  function excerpt(value, limit) {
2221
2189
  const points = Array.from(value);
2222
2190
  return points.length <= limit ? value : points.slice(0, limit).join("");
2223
2191
  }
2192
+ function maskedName(name) {
2193
+ return name.trim().toLocaleLowerCase().replace(/\d[\d.,]*[km]?(?=\s+\p{L})/gu, "#");
2194
+ }
2195
+ function hintedCandidate(candidate) {
2196
+ const hint = candidate.signals.nameHint;
2197
+ if (!hint) return candidate;
2198
+ const points = Array.from(`${candidate.name} (${hint})`);
2199
+ const name = points.length <= NAME_LIMIT ? points.join("") : points.slice(0, NAME_LIMIT - 1).join("") + "\u2026";
2200
+ return { ...candidate, name };
2201
+ }
2224
2202
  var LocatorError = class extends Error {
2225
2203
  constructor(reason) {
2226
2204
  super(reason);
@@ -2256,8 +2234,7 @@ async function fullSet(page, operation) {
2256
2234
  }
2257
2235
  next = part.next;
2258
2236
  }
2259
- if (collected.length !== first.total || !sameVersion3(await pageVersion(page), first.version))
2260
- throw new LocatorError("stale");
2237
+ if (collected.length !== first.total) throw new LocatorError("stale");
2261
2238
  return { ...first, next: null, candidates: collected };
2262
2239
  }
2263
2240
  function requestOptions(candidates) {
@@ -2304,6 +2281,18 @@ function batches(sentence, candidates) {
2304
2281
  if (batch.length) result.push(batch);
2305
2282
  return result;
2306
2283
  }
2284
+ function withSiblings(sentence, finalists, candidates) {
2285
+ const keep = new Set(finalists);
2286
+ for (const finalist of finalists)
2287
+ for (const sibling of repeatedGroup(finalist, candidates))
2288
+ keep.add(sibling);
2289
+ const ordered = candidates.filter((candidate) => keep.has(candidate));
2290
+ try {
2291
+ return batches(sentence, ordered).length === 1 ? ordered : [...finalists];
2292
+ } catch {
2293
+ return [...finalists];
2294
+ }
2295
+ }
2307
2296
  function validateDecision(decision, candidates) {
2308
2297
  const ids = new Set(candidates.map((candidate) => candidate.ref));
2309
2298
  const expected = /* @__PURE__ */ new Set([...ids, "none"]);
@@ -2359,37 +2348,390 @@ function sentenceEvidence(sentence, selected, group) {
2359
2348
  if (/\barticle body\b/i.test(sentence) && selected.signals.region === "article-body" && group.filter((candidate) => candidate.signals.region === "article-body").length === 1)
2360
2349
  return true;
2361
2350
  const firstStory = (candidate) => candidate.peers.some((peer) => /^1[.)]\s/.test(peer));
2362
- const namesRequestedPurpose = (candidate) => words2(candidate.name).some(
2363
- (word) => !WEAK_MEMBER_WORDS.has(word) && sentenceWords.includes(word)
2364
- );
2365
- if (/\b(first|top) story\b/i.test(sentence) && firstStory(selected) && namesRequestedPurpose(selected) && group.filter(
2351
+ const namesRequestedPurpose = (candidate) => words2(candidate.name).some((word) => sentenceWords.includes(word));
2352
+ if (/\b(first|top)(?:\s+ranked)?\s+story\b/i.test(sentence) && firstStory(selected) && namesRequestedPurpose(selected) && group.filter(
2366
2353
  (candidate) => firstStory(candidate) && namesRequestedPurpose(candidate)
2367
2354
  ).length === 1)
2368
2355
  return true;
2369
2356
  const containsPhrase = (haystack, phrase) => phrase.length > 0 && haystack.some(
2370
2357
  (_, index) => phrase.every((word, offset) => haystack[index + offset] === word)
2371
2358
  );
2372
- const otherTexts = group.filter((candidate) => candidate !== selected).flatMap((candidate) => [candidate.name, ...candidate.peers].map(words2));
2373
- return [selected.name, ...selected.peers].some((text) => {
2359
+ const texts = (candidate) => [
2360
+ candidate.name,
2361
+ ...candidate.peers,
2362
+ ...candidate.location?.split(/[,·]/) ?? []
2363
+ ];
2364
+ const otherTexts = group.filter((candidate) => candidate !== selected).flatMap((candidate) => texts(candidate).map(words2));
2365
+ return texts(selected).some((text) => {
2374
2366
  const phrase = words2(text);
2375
- return phrase.some((word) => !WEAK_MEMBER_WORDS.has(word)) && containsPhrase(sentenceWords, phrase) && !otherTexts.some((other) => containsPhrase(other, phrase));
2367
+ return containsPhrase(sentenceWords, phrase) && !otherTexts.some((other) => containsPhrase(other, phrase));
2376
2368
  });
2377
2369
  }
2378
- function explicitRegionEvidence(sentence, candidate) {
2379
- if (/\barticle body\b/i.test(sentence) && candidate.signals.region !== "article-body")
2380
- return false;
2381
- if (/\b(first|top) story\b/i.test(sentence) && !candidate.peers.some((peer) => /^1[.)]\s/.test(peer)))
2370
+ function repeatedMemberAccepted(policy, sentence, member, group, decision) {
2371
+ if (!policy) return null;
2372
+ if (policy.modelPick)
2373
+ return group.some(
2374
+ (other) => other !== member && sentenceEvidence(sentence, other, group)
2375
+ ) ? null : "repeated_member_model_pick";
2376
+ const href = member.signals.href?.trim();
2377
+ if (policy.sameDestination && href && // "#" and script links run page code, so equal hrefs prove nothing.
2378
+ href !== "#" && !/^javascript:/i.test(href) && group.every((candidate) => candidate.signals.href?.trim() === href))
2379
+ return "repeated_member_same_destination";
2380
+ if (policy.duplicateLinks && href && href !== "#" && !/^javascript:/i.test(href) && group.length <= 3 && !qualifiesMember(sentence, member) && group.every((candidate) => {
2381
+ const name = candidate.name.trim().toLocaleLowerCase();
2382
+ const picked = member.name.trim().toLocaleLowerCase();
2383
+ return candidate.signals.href?.trim() === href && (name.includes(picked) || picked.includes(name));
2384
+ }))
2385
+ return "repeated_member_duplicate_link";
2386
+ if (policy.trust && qualifiesMember(sentence, member) && decision.probabilities[member.ref] >= policy.trust.minProbability && comparableLead(decision, member.ref) >= policy.trust.minLead)
2387
+ return "repeated_member_trusted";
2388
+ return null;
2389
+ }
2390
+ var FILLER_WORDS = new Set(
2391
+ "a an the this that it its please then and or of on in into to at for click tap press hit open select choose check tick uncheck toggle type enter fill go button link icon field box option menu tab checkbox radio switch item control".split(" ")
2392
+ );
2393
+ function qualifiesMember(sentence, member) {
2394
+ const words2 = (text) => text.toLocaleLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
2395
+ const label = new Set(words2(member.name));
2396
+ return words2(sentence.replace(/\{\{[^}]*\}\}/g, " ")).some(
2397
+ (word) => !label.has(word) && !FILLER_WORDS.has(word)
2398
+ );
2399
+ }
2400
+ var REGIONS = [
2401
+ {
2402
+ sentence: /\b(header|navbar|masthead|top (?:nav(?:igation)?|bar|menu)|(?:global|main) (?:nav(?:igation)?|menu))\b/i,
2403
+ location: (location) => /\bheader\b/.test(location) || /\bnavigation\b/.test(location) && !/\b(footer|sidebar)\b/.test(location)
2404
+ },
2405
+ {
2406
+ sentence: /\b(footer|bottom of the page)\b/i,
2407
+ location: (location) => /\bfooter\b/.test(location)
2408
+ },
2409
+ {
2410
+ sentence: /\b(sidebar|side ?bar|side menu|left (?:menu|nav(?:igation)?)|table of contents)\b/i,
2411
+ location: (location) => /\bsidebar\b/.test(location) || /\bnavigation\b/.test(location) && !/\b(header|footer)\b/.test(location)
2412
+ },
2413
+ {
2414
+ sentence: /\b(dialog|modal|pop-?up)\b/i,
2415
+ location: (location) => /\bdialog\b/.test(location)
2416
+ }
2417
+ ];
2418
+ function inNamedRegion(sentence, candidates) {
2419
+ const named = REGIONS.filter((region) => region.sentence.test(sentence));
2420
+ if (named.length !== 1) return [...candidates];
2421
+ const words2 = (text) => text.toLocaleLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
2422
+ const regionWords = new Set(
2423
+ words2(sentence.match(named[0].sentence)?.[0] ?? "")
2424
+ );
2425
+ const wanted = words2(sentence.replace(/\{\{[^}]*\}\}/g, " ")).filter(
2426
+ (word) => !FILLER_WORDS.has(word) && !regionWords.has(word)
2427
+ );
2428
+ const kept = candidates.filter((candidate) => {
2429
+ if (named[0].location(candidate.location ?? "")) return true;
2430
+ if (!wanted.length) return false;
2431
+ const name = new Set(words2(candidate.name));
2432
+ return wanted.every((word) => name.has(word));
2433
+ });
2434
+ return kept.length ? kept : [...candidates];
2435
+ }
2436
+ var GRAMMAR_WORDS = new Set(
2437
+ "a an the this that it its please then and or of on in into to at for".split(
2438
+ " "
2439
+ )
2440
+ );
2441
+ var ROLE_WORDS = new Set(
2442
+ "click tap press hit open select choose check tick uncheck toggle button link icon field box option menu tab checkbox radio switch item control slider dropdown".split(" ")
2443
+ );
2444
+ function roleOnlyAmbiguous(sentence, selected, candidates) {
2445
+ const words2 = (text) => text.toLocaleLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
2446
+ const named = new Set(words2(selected.name));
2447
+ const meaningful = words2(sentence.replace(/\{\{[^}]*\}\}/g, " ")).filter(
2448
+ (word) => !GRAMMAR_WORDS.has(word)
2449
+ );
2450
+ if (!meaningful.length || meaningful.some((word) => !ROLE_WORDS.has(word) || named.has(word)))
2382
2451
  return false;
2383
- return true;
2452
+ const role = selected.role || selected.tag;
2453
+ return candidates.some(
2454
+ (candidate) => candidate !== selected && (candidate.role || candidate.tag) === role && candidate.name.trim().toLocaleLowerCase() !== selected.name.trim().toLocaleLowerCase()
2455
+ );
2456
+ }
2457
+ function nearNamesake(sentence, selected, offered, decision) {
2458
+ const words2 = (text) => text.toLocaleLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
2459
+ const content = words2(sentence.replace(/\{\{[^}]*\}\}/g, " ")).filter(
2460
+ (word) => !FILLER_WORDS.has(word)
2461
+ );
2462
+ if (!content.length) return false;
2463
+ const holdsAll = (candidate) => {
2464
+ const name = new Set(words2(candidate.name));
2465
+ return content.every((word) => name.has(word));
2466
+ };
2467
+ if (!holdsAll(selected)) return false;
2468
+ return offered.some(
2469
+ (candidate) => candidate !== selected && candidate.name.trim().toLocaleLowerCase() !== selected.name.trim().toLocaleLowerCase() && (decision.probabilities[candidate.ref] ?? 0) >= 0.05 && holdsAll(candidate)
2470
+ );
2471
+ }
2472
+ var ORDINALS = {
2473
+ first: 1,
2474
+ second: 2,
2475
+ third: 3,
2476
+ fourth: 4,
2477
+ fifth: 5,
2478
+ sixth: 6,
2479
+ seventh: 7,
2480
+ eighth: 8,
2481
+ ninth: 9,
2482
+ tenth: 10,
2483
+ "1st": 1,
2484
+ "2nd": 2,
2485
+ "3rd": 3,
2486
+ "4th": 4,
2487
+ "5th": 5,
2488
+ last: -1
2489
+ };
2490
+ var ITEM_NOUNS = new Set(
2491
+ "story post result product item row card example question comment entry listing article plan option message email file folder review one button link icon checkbox tab field demo form".split(" ")
2492
+ );
2493
+ var MONEY = /(?:[$€£]\s?\d[\d,]*(?:\.\d+)?|\brs\.?\s?\d[\d,]*(?:\.\d+)?)/gi;
2494
+ function resolveInCode(sentence, pick, candidates, loose = false) {
2495
+ const key = (candidate) => loose ? maskedName(candidate.name) : candidate.name.trim().toLocaleLowerCase();
2496
+ const name = key(pick);
2497
+ let group = inNamedRegion(
2498
+ sentence,
2499
+ candidates.filter((candidate) => key(candidate) === name)
2500
+ );
2501
+ if (group.length < 2 || !group.includes(pick)) return null;
2502
+ const words2 = (text) => text.toLocaleLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
2503
+ const said = words2(sentence.replace(/\{\{[^}]*\}\}/g, " "));
2504
+ const label = new Set(words2(pick.name));
2505
+ const referenceAt = said.findIndex(
2506
+ (word) => /^(for|on|about|of|from|under|by)$/.test(word)
2507
+ );
2508
+ const ordinal = said.find((word, index) => {
2509
+ if (ORDINALS[word] === void 0 || label.has(word)) return false;
2510
+ const next = said[index + 1] ?? "";
2511
+ return !(loose && referenceAt >= 0 && index > referenceAt && !label.has(next) && /^(released|published|created|updated|modified)$/.test(next));
2512
+ });
2513
+ const lowest = /\b(cheapest|lowest[- ]priced?|least expensive)\b/i.test(
2514
+ sentence
2515
+ );
2516
+ const highest = /\b(most expensive|highest[- ]priced?|priciest)\b/i.test(
2517
+ sentence
2518
+ );
2519
+ if (ordinal || lowest || highest) {
2520
+ let request = said.join(" ");
2521
+ const scope = /\s+(?:in|under|inside|within) (?:the )?(.+)$/.exec(request);
2522
+ if (scope) {
2523
+ const wanted2 = scope[1].replace(/ (?:section|region)$/, "");
2524
+ group = group.filter(
2525
+ (member) => /^article(?: body)?$/.test(wanted2) ? member.signals.region === "article-body" : [member.signals.section, member.location].some(
2526
+ (value) => value?.split("\u203A").some((part) => words2(part).join(" ") === wanted2)
2527
+ )
2528
+ );
2529
+ if (!group.length) return null;
2530
+ request = request.slice(0, scope.index);
2531
+ }
2532
+ const control = words2(loose ? maskedName(pick.name) : pick.name).join(" ");
2533
+ if (!control) return null;
2534
+ const relation = ordinal ?? (lowest ? "(?:cheapest|lowest price(?:d)?|least expensive)" : "(?:most expensive|highest price(?:d)?|priciest)");
2535
+ const noun = `(?:${[...ITEM_NOUNS].join("|")})`;
2536
+ const target = `(?:the )?${control}(?: button| link)?`;
2537
+ const ranked = `(?:the )?${relation}`;
2538
+ const form = new RegExp(
2539
+ `^(?:(?:please )?(?:click|tap|press|open|select|choose) )?(?:${ranked} ${target}|${target} (?:for|on|of) ${ranked}(?: ${noun})?|${target} ${ranked} ${noun}|${ranked} ${noun}(?: s)? ${target})$`
2540
+ );
2541
+ if (!form.test(request) || lowest && highest) return null;
2542
+ const kind = new RegExp(`${control} (button|link)(?: |$)`).exec(
2543
+ request
2544
+ )?.[1];
2545
+ if (kind) {
2546
+ group = group.filter((member) => member.role === kind);
2547
+ if (!group.length) return null;
2548
+ }
2549
+ }
2550
+ const items = group.map((member) => member.signals.item ?? "");
2551
+ const complete = group.every((member) => !!member.signals.item);
2552
+ if (items.some(
2553
+ (text) => /\b(sponsored|promoted|pinned|advertisement)\b/i.test(text)
2554
+ ))
2555
+ return null;
2556
+ if (ordinal) {
2557
+ const k = ORDINALS[ordinal];
2558
+ const index = k === -1 ? group.length - 1 : k - 1;
2559
+ return index < group.length ? group[index] : null;
2560
+ }
2561
+ if ((lowest || highest) && !complete) return null;
2562
+ if (lowest || highest) {
2563
+ const prices = items.map((text) => {
2564
+ const found = new Set(
2565
+ (text.match(MONEY) ?? []).map(
2566
+ (value) => Number(value.replace(/[^\d.]/g, ""))
2567
+ )
2568
+ );
2569
+ return found.size === 1 ? [...found][0] : NaN;
2570
+ });
2571
+ if (prices.some((price) => Number.isNaN(price))) return null;
2572
+ const target = lowest ? Math.min(...prices) : Math.max(...prices);
2573
+ const at2 = prices.flatMap(
2574
+ (price, index) => price === target ? [index] : []
2575
+ );
2576
+ return at2.length === 1 ? group[at2[0]] : null;
2577
+ }
2578
+ const reference = /\b(?:for|on|about|of|from|under|by)\s+(.+)$/i.exec(
2579
+ sentence.replace(/\{\{[^}]*\}\}/g, " ")
2580
+ );
2581
+ if (!reference || !complete && !(loose && items.filter((text) => !!text).length >= 2))
2582
+ return null;
2583
+ const phrase = reference[0].toLocaleLowerCase();
2584
+ if (candidates.some(
2585
+ (candidate) => candidate.name.toLocaleLowerCase().includes(phrase)
2586
+ ))
2587
+ return null;
2588
+ const wanted = words2(reference[1]).filter(
2589
+ (word) => word.length > 1 && !FILLER_WORDS.has(word) && !ITEM_NOUNS.has(word) && !label.has(word) && !(loose && REFERENCE_WORDS.has(word))
2590
+ );
2591
+ if (!wanted.length) return null;
2592
+ const matching = group.filter((member, index) => {
2593
+ if (!items[index]) return false;
2594
+ const own = new Set(words2(member.name));
2595
+ const text = new Set(words2(items[index]).filter((word) => !own.has(word)));
2596
+ return wanted.every((word) => text.has(word));
2597
+ });
2598
+ return matching.length === 1 ? matching[0] : null;
2599
+ }
2600
+ var NAVIGATION_VERBS = new Set("go view see show visit".split(" "));
2601
+ function statedGroupPick(sentence, candidates) {
2602
+ const words2 = (text) => text.toLocaleLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
2603
+ const said = new Set(words2(sentence.replace(/\{\{[^}]*\}\}/g, " ")));
2604
+ const content = (name) => words2(name.replace("#", " ")).filter(
2605
+ (word) => !FILLER_WORDS.has(word) && !NAVIGATION_VERBS.has(word)
2606
+ );
2607
+ const counts = /* @__PURE__ */ new Map();
2608
+ for (const candidate of candidates) {
2609
+ const key = maskedName(candidate.name);
2610
+ counts.set(key, (counts.get(key) ?? 0) + 1);
2611
+ }
2612
+ let best = [];
2613
+ for (const candidate of candidates) {
2614
+ if (candidate.signals.nameTruncated) continue;
2615
+ const key = maskedName(candidate.name);
2616
+ const own = content(key);
2617
+ if (!own.length || !own.every((word) => said.has(word))) continue;
2618
+ if ((counts.get(key) ?? 0) < 2) continue;
2619
+ if (best.length && own.length < best[0].size) continue;
2620
+ if (best.length && own.length > best[0].size) best = [];
2621
+ if (!best.some((entry) => entry.key === key))
2622
+ best.push({ key, size: own.length, pick: candidate });
2623
+ }
2624
+ return best.length === 1 ? best[0].pick : null;
2625
+ }
2626
+ function nameStated(sentence, candidate) {
2627
+ const words2 = (text) => text.toLocaleLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
2628
+ const said = new Set(words2(sentence));
2629
+ const own = words2(maskedName(candidate.name).replace("#", " ")).filter(
2630
+ (word) => !FILLER_WORDS.has(word) && !NAVIGATION_VERBS.has(word)
2631
+ );
2632
+ return own.length > 0 && own.every((word) => said.has(word));
2633
+ }
2634
+ function codeAfterNone(sentence, candidates) {
2635
+ const pick = statedGroupPick(sentence, candidates);
2636
+ return pick ? resolveInCode(sentence, pick, candidates, true) : null;
2637
+ }
2638
+ var REFERENCE_WORDS = new Set(
2639
+ "about from by under with in is was were that which whose where".split(" ")
2640
+ );
2641
+ var REFERENCE_PHRASE = /\b(?:on|for|about|of)\s+(?:the|a|an|this|that)\s+(.+)$/i;
2642
+ var ORDINAL_OR_PRICE = /\b(first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|last|\d+(?:st|nd|rd|th)|cheapest|lowest|highest|most expensive|least expensive|priciest)\b/i;
2643
+ var MAX_VERIFIED_ITEMS = 40;
2644
+ var ITEM_TEXT_LIMIT = 300;
2645
+ function itemQuestionGroup(sentence, pick, candidates) {
2646
+ const text = sentence.replace(/\{\{[^}]*\}\}/g, " ");
2647
+ const reference = REFERENCE_PHRASE.exec(text);
2648
+ if (!reference || ORDINAL_OR_PRICE.test(reference[1])) return null;
2649
+ const phrase = reference[0].toLocaleLowerCase();
2650
+ if (candidates.some(
2651
+ (candidate) => candidate.name.toLocaleLowerCase().includes(phrase)
2652
+ ))
2653
+ return null;
2654
+ const name = maskedName(pick.name);
2655
+ const group = inNamedRegion(
2656
+ sentence,
2657
+ candidates.filter((candidate) => maskedName(candidate.name) === name)
2658
+ );
2659
+ if (!group.includes(pick) || !pick.signals.item) return null;
2660
+ const members = group.filter((member) => !!member.signals.item?.trim());
2661
+ if (members.length < 2 || members.length > MAX_VERIFIED_ITEMS) return null;
2662
+ return members;
2663
+ }
2664
+ var SECTION_NOUNS = new Set(
2665
+ "sidebar side section box demo panel area region list banner header footer navigation nav menu bar top bottom left right under inside within below beneath above near page example card block widget part container group dropdown select field input textbox".split(" ")
2666
+ );
2667
+ function resolveBySection(sentence, pick, candidates) {
2668
+ const text = sentence.replace(/\{\{[^}]*\}\}/g, " ");
2669
+ if (!/\b(in|under|inside|within|from|below|beneath|of)\b/i.test(text))
2670
+ return null;
2671
+ const stem = (word) => word.length > 3 && word.endsWith("s") ? word.slice(0, -1) : word;
2672
+ const words2 = (value) => (value.toLocaleLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []).map(stem);
2673
+ const name = pick.name.trim().toLocaleLowerCase();
2674
+ const group = inNamedRegion(
2675
+ sentence,
2676
+ candidates.filter(
2677
+ (candidate) => candidate.name.trim().toLocaleLowerCase() === name
2678
+ )
2679
+ );
2680
+ if (group.length < 2 || !group.includes(pick)) return null;
2681
+ const label = new Set(words2(pick.name));
2682
+ const filler = new Set([...FILLER_WORDS, ...SECTION_NOUNS].map(stem));
2683
+ const wanted = [
2684
+ ...new Set(
2685
+ words2(text).filter((word) => !label.has(word) && !filler.has(word))
2686
+ )
2687
+ ];
2688
+ if (!wanted.length) return null;
2689
+ const matching = group.filter((member) => {
2690
+ const section = new Set(words2(member.signals.section ?? ""));
2691
+ return wanted.every((word) => section.has(word));
2692
+ });
2693
+ return matching.length === 1 ? matching[0] : null;
2694
+ }
2695
+ function lexicalMiss(sentence, selected, offered) {
2696
+ const words2 = (text) => text.toLocaleLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
2697
+ const content = words2(sentence.replace(/\{\{[^}]*\}\}/g, " ")).filter(
2698
+ (word) => !FILLER_WORDS.has(word)
2699
+ );
2700
+ if (!content.length) return false;
2701
+ const picked = new Set(words2(selected.name));
2702
+ if (content.some((word) => picked.has(word))) return false;
2703
+ return offered.some((candidate) => {
2704
+ if (candidate === selected) return false;
2705
+ const name = new Set(words2(candidate.name));
2706
+ return content.every((word) => name.has(word));
2707
+ });
2384
2708
  }
2385
2709
  function sameIdentity(a, b) {
2386
- if (a.tag !== b.tag || a.role !== b.role || a.name !== b.name || a.inputType !== b.inputType || a.editable !== b.editable || a.disabled !== b.disabled || a.signals.region !== b.signals.region || JSON.stringify(a.peers) !== JSON.stringify(b.peers))
2710
+ if (a.signals.nodeId !== b.signals.nodeId || a.tag !== b.tag || a.role !== b.role || a.name !== b.name || a.inputType !== b.inputType || a.editable !== b.editable || a.disabled !== b.disabled || a.signals.rawName !== b.signals.rawName || a.signals.nameTruncated !== b.signals.nameTruncated || a.signals.region !== b.signals.region || a.signals.path !== b.signals.path || a.signals.item !== b.signals.item || a.signals.section !== b.signals.section || JSON.stringify(a.peers) !== JSON.stringify(b.peers) || a.location !== b.location)
2387
2711
  return false;
2388
2712
  for (const key of ["hook", "id", "name", "href"]) {
2389
- if (a.signals[key] && a.signals[key] !== b.signals[key]) return false;
2713
+ if (a.signals[key] !== b.signals[key]) return false;
2390
2714
  }
2391
2715
  return true;
2392
2716
  }
2717
+ function sameChoiceSurface(original, fresh) {
2718
+ return original.length === fresh.length && original.every((candidate, index) => {
2719
+ const next = fresh[index];
2720
+ return next && sameIdentity(candidate, next);
2721
+ });
2722
+ }
2723
+ function exactNameRequested(sentence, candidate) {
2724
+ if (candidate.signals.nameTruncated) return false;
2725
+ const words2 = (text) => text.toLocaleLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
2726
+ const name = words2(candidate.name);
2727
+ const request = words2(sentence);
2728
+ return name.length > 0 && request.some(
2729
+ (_, index) => name.every((word, offset) => request[index + offset] === word)
2730
+ );
2731
+ }
2732
+ function sameNodeControl(a, b) {
2733
+ return !!a.signals.nodeId && a.signals.nodeId === b.signals.nodeId && a.tag === b.tag && a.role === b.role && a.name === b.name && a.inputType === b.inputType && a.editable === b.editable && a.disabled === b.disabled && a.signals.rawName === b.signals.rawName && a.signals.nameTruncated === b.signals.nameTruncated && a.signals.region === b.signals.region && a.signals.path === b.signals.path && a.signals.hook === b.signals.hook && a.signals.id === b.signals.id && a.signals.name === b.signals.name && a.signals.href === b.signals.href;
2734
+ }
2393
2735
  function provedTargetChange(old, selected, candidates, key) {
2394
2736
  const oldHook = old.digests.hook;
2395
2737
  const oldId = old.digests.id;
@@ -2401,6 +2743,10 @@ function provedTargetChange(old, selected, candidates, key) {
2401
2743
  }
2402
2744
  async function resolveTarget(page, resolver, options) {
2403
2745
  const calls = [];
2746
+ const repeatedMember = options.repeatedMember ?? { modelPick: true };
2747
+ const nameHints = options.nameHints !== false;
2748
+ const verifyItems = options.verifyItems !== false;
2749
+ const codeFallback = options.codeFallback !== false;
2404
2750
  let candidateCount = 0;
2405
2751
  let rounds = 0;
2406
2752
  let top = [];
@@ -2439,8 +2785,15 @@ async function resolveTarget(page, resolver, options) {
2439
2785
  let source = await fullSet(page, options.operation);
2440
2786
  observationVersion = source.version;
2441
2787
  ensureActive();
2442
- if (options.operation === "fill" && source.candidates.length === 0)
2443
- source = await fullSet(page, "click");
2788
+ if (options.operation === "fill" && source.candidates.length === 0) {
2789
+ const deadline = performance.now() + 1500;
2790
+ while (source.candidates.length === 0 && performance.now() < deadline) {
2791
+ ensureActive();
2792
+ await new Promise((resolve) => setTimeout(resolve, 150));
2793
+ source = await fullSet(page, "fill");
2794
+ }
2795
+ if (source.candidates.length === 0) source = await fullSet(page, "click");
2796
+ }
2444
2797
  observationVersion = source.version;
2445
2798
  ensureActive();
2446
2799
  if (options.cache) {
@@ -2536,12 +2889,15 @@ async function resolveTarget(page, resolver, options) {
2536
2889
  {
2537
2890
  complete: true,
2538
2891
  options: [
2539
- ...projectCandidates(requestOptions(pool2)).map((candidate) => ({
2892
+ ...projectCandidates(
2893
+ requestOptions(nameHints ? pool2.map(hintedCandidate) : pool2)
2894
+ ).map((candidate) => ({
2540
2895
  kind: "candidate",
2541
2896
  candidate: options.projectText ? {
2542
2897
  ...candidate,
2543
2898
  name: options.projectText(candidate.name),
2544
- peers: candidate.peers.map(options.projectText)
2899
+ peers: candidate.peers.map(options.projectText),
2900
+ ...candidate.location ? { location: options.projectText(candidate.location) } : {}
2545
2901
  } : candidate
2546
2902
  })),
2547
2903
  { kind: "none", id: "none" }
@@ -2558,16 +2914,18 @@ async function resolveTarget(page, resolver, options) {
2558
2914
  rounds++;
2559
2915
  return decision2;
2560
2916
  };
2561
- let pool = [...candidates];
2917
+ let pool = candidates.length > CANDIDATE_LIMIT ? inNamedRegion(options.sentence, candidates) : [...candidates];
2562
2918
  let finalists = [];
2563
2919
  let decision;
2920
+ let reducedAcrossBatches = false;
2564
2921
  while (true) {
2565
2922
  const heats = batches(options.sentence, pool);
2566
2923
  if (heats.length === 1) {
2567
- finalists = heats[0];
2924
+ finalists = reducedAcrossBatches ? withSiblings(options.sentence, heats[0], candidates) : heats[0];
2568
2925
  decision = await choose(finalists);
2569
2926
  break;
2570
2927
  }
2928
+ reducedAcrossBatches = true;
2571
2929
  const reduced = [];
2572
2930
  for (let index = 0; index < heats.length; index += MAX_PARALLEL_CHOICES) {
2573
2931
  ensureActive();
@@ -2595,23 +2953,58 @@ async function resolveTarget(page, resolver, options) {
2595
2953
  throw new LocatorError("resource_limit");
2596
2954
  pool = reduced;
2597
2955
  }
2598
- if (!sameVersion3(await pageVersion(page), source.version))
2956
+ if (reducedAcrossBatches && !sameVersion3(await pageVersion(page), source.version))
2599
2957
  return unresolved("stale");
2600
2958
  top = topOptions(decision, finalists);
2601
2959
  confidence = decision.confidence;
2602
- if (decision.selection.kind === "none") return unresolved("none");
2960
+ if (decision.selection.kind === "none") {
2961
+ const fallback = codeFallback ? codeAfterNone(options.sentence, candidates) : null;
2962
+ if (!fallback) return unresolved("none");
2963
+ gate = "resolved_in_code_after_none";
2964
+ if (options.operation === "fill" && !fallback.editable)
2965
+ return unresolved("not_fillable");
2966
+ return await refresh(fallback);
2967
+ }
2603
2968
  const selected = byId.get(decision.selection.id);
2604
2969
  if (!selected) return unresolved("provider_error");
2970
+ const anchor = codeFallback && !nameStated(options.sentence, selected) ? statedGroupPick(options.sentence, candidates) ?? selected : selected;
2971
+ const inCode = (pick) => resolveInCode(options.sentence, pick, candidates) ?? (codeFallback ? resolveInCode(options.sentence, anchor, candidates, true) : null);
2972
+ const bySection = options.sectionMatch !== false && !inCode(selected) ? resolveBySection(options.sentence, selected, candidates) : null;
2973
+ const coded = bySection ?? inCode(selected);
2974
+ if (coded) {
2975
+ gate = bySection ? "resolved_by_section" : "resolved_in_code";
2976
+ if (options.operation === "fill" && !coded.editable)
2977
+ return unresolved("not_fillable");
2978
+ return await refresh(coded);
2979
+ }
2980
+ const itemMembers = verifyItems && resolver.verifyItems ? itemQuestionGroup(
2981
+ options.sentence,
2982
+ nameStated(options.sentence, selected) ? selected : statedGroupPick(options.sentence, candidates) ?? selected,
2983
+ candidates
2984
+ ) : null;
2985
+ if (itemMembers) {
2986
+ const verified = await verifyByItems(itemMembers);
2987
+ if (verified) {
2988
+ gate = "resolved_by_items";
2989
+ if (options.operation === "fill" && !verified.editable)
2990
+ return unresolved("not_fillable");
2991
+ return await refresh(verified);
2992
+ }
2993
+ }
2605
2994
  const group = repeatedGroup(selected, candidates);
2606
- const low = decision.confidence !== null && decision.confidence < MIN_CONFIDENCE || decision.probabilities[selected.ref] < MIN_CONFIDENCE || comparableLead(decision, selected.ref) < MIN_LEAD;
2607
- if (low) {
2995
+ const low = decision.confidence !== null && decision.confidence < MIN_CONFIDENCE || comparableLead(decision, selected.ref) < MIN_LEAD;
2996
+ if (low && group.length >= 2 && repeatedMember.modelPick)
2997
+ gate = "repeated_member_model_pick";
2998
+ else if (low && group.length < 2 && options.acceptLowConfidence)
2999
+ gate = "low_confidence_accepted";
3000
+ else if (low) {
2608
3001
  gate = "low_confidence_or_margin";
2609
3002
  if (group.length < 2) return unresolved("ambiguous");
2610
3003
  const groupProbability = group.reduce(
2611
3004
  (sum, candidate) => sum + (decision.probabilities[candidate.ref] ?? 0),
2612
3005
  0
2613
3006
  );
2614
- if (groupProbability < 0.75 || groupProbability - (1 - groupProbability) < 0.2) {
3007
+ if (groupProbability < 0.75) {
2615
3008
  gate = "repeated_group_weak";
2616
3009
  return unresolved("ambiguous");
2617
3010
  }
@@ -2631,43 +3024,123 @@ async function resolveTarget(page, resolver, options) {
2631
3024
  return unresolved("ambiguous");
2632
3025
  }
2633
3026
  if (!sentenceEvidence(options.sentence, member, group)) {
2634
- gate = "repeated_member_no_evidence";
2635
- return unresolved("ambiguous");
2636
- }
2637
- if (!explicitRegionEvidence(options.sentence, member)) {
2638
- gate = "explicit_region_unproven";
2639
- return unresolved("ambiguous");
3027
+ const accepted = repeatedMemberAccepted(
3028
+ repeatedMember,
3029
+ options.sentence,
3030
+ member,
3031
+ group,
3032
+ narrower
3033
+ );
3034
+ if (!accepted) {
3035
+ gate = "repeated_member_no_evidence";
3036
+ return unresolved("ambiguous");
3037
+ }
3038
+ gate = accepted;
2640
3039
  }
2641
- gate = "repeated_member_proven";
3040
+ if (gate === "low_confidence_or_margin") gate = "repeated_member_proven";
2642
3041
  if (options.operation === "fill" && !member.editable)
2643
3042
  return unresolved("not_fillable");
3043
+ if (roleOnlyAmbiguous(options.sentence, member, candidates)) {
3044
+ gate = "role_only_ambiguous";
3045
+ return unresolved("ambiguous");
3046
+ }
2644
3047
  return await refresh(member);
2645
3048
  }
2646
- if (group.length > 1 && !sentenceEvidence(options.sentence, selected, group)) {
2647
- gate = "repeated_member_no_evidence";
2648
- return unresolved("ambiguous");
3049
+ const masked = (name) => name.trim().toLocaleLowerCase().replace(/\d[\d.,]*[km]?(?=\s+\p{L})/gu, "#");
3050
+ const sameName = candidates.filter(
3051
+ (candidate) => masked(candidate.name) === masked(selected.name)
3052
+ );
3053
+ if (sameName.length > 1 && !sentenceEvidence(options.sentence, selected, sameName)) {
3054
+ const accepted = repeatedMemberAccepted(
3055
+ repeatedMember,
3056
+ options.sentence,
3057
+ selected,
3058
+ sameName,
3059
+ decision
3060
+ );
3061
+ if (!accepted) {
3062
+ gate = "repeated_member_no_evidence";
3063
+ return unresolved("ambiguous");
3064
+ }
3065
+ gate = accepted;
2649
3066
  }
2650
3067
  if (options.operation === "fill" && !selected.editable)
2651
3068
  return unresolved("not_fillable");
2652
- if (!explicitRegionEvidence(options.sentence, selected)) {
2653
- gate = "explicit_region_unproven";
3069
+ if (roleOnlyAmbiguous(options.sentence, selected, candidates)) {
3070
+ gate = "role_only_ambiguous";
3071
+ return unresolved("ambiguous");
3072
+ }
3073
+ if (group.length < 2 && nearNamesake(options.sentence, selected, finalists, decision)) {
3074
+ gate = "near_namesake";
3075
+ return unresolved("ambiguous");
3076
+ }
3077
+ if (lexicalMiss(options.sentence, selected, finalists)) {
3078
+ gate = "lexical_miss";
2654
3079
  return unresolved("ambiguous");
2655
3080
  }
2656
3081
  return await refresh(selected);
3082
+ async function verifyByItems(members) {
3083
+ ensureActive();
3084
+ const project = options.projectText ?? ((text) => text);
3085
+ let verdict2;
3086
+ try {
3087
+ verdict2 = await resolver.verifyItems(
3088
+ options.sentence,
3089
+ members.map((member) => ({
3090
+ id: member.ref,
3091
+ text: project(
3092
+ Array.from(member.signals.item.replace(/\s+/g, " ").trim()).slice(0, ITEM_TEXT_LIMIT).join("")
3093
+ )
3094
+ })),
3095
+ { signal: controller.signal }
3096
+ );
3097
+ } catch (error2) {
3098
+ calls.push(unknownCostCall(error2));
3099
+ ensureActive();
3100
+ return null;
3101
+ }
3102
+ calls.push(verdict2.call);
3103
+ ensureActive();
3104
+ const ranked = members.map((member) => ({
3105
+ member,
3106
+ score: verdict2.scores[member.ref]
3107
+ })).filter(
3108
+ (entry) => typeof entry.score === "number" && Number.isFinite(entry.score) && entry.score >= 0 && entry.score <= 1
3109
+ ).sort((a, b) => b.score - a.score);
3110
+ if (ranked.length !== members.length) return null;
3111
+ const [best, second] = ranked;
3112
+ if (!best || best.score < 0.6 || best.score - (second?.score ?? 0) < 0.2)
3113
+ return null;
3114
+ if (!sameVersion3(await pageVersion(page), source.version)) return null;
3115
+ return best.member;
3116
+ }
2657
3117
  async function refresh(selectedCandidate) {
2658
3118
  ensureActive();
2659
3119
  const fresh = await liveCandidates(page, options.operation);
2660
3120
  ensureActive();
2661
3121
  if (!fresh.complete || fresh.total > MAX_CANDIDATES || fresh.total !== fresh.candidates.length || fresh.version.document !== source.version.document || fresh.version.route !== source.version.route || !sameVersion3(await pageVersion(page), fresh.version))
2662
3122
  return unresolved("stale");
2663
- const matches = fresh.candidates.filter(
3123
+ const surfaceStable = sameChoiceSurface(
3124
+ source.candidates,
3125
+ fresh.candidates
3126
+ );
3127
+ let matches = fresh.candidates.filter(
2664
3128
  (candidate) => sameIdentity(selectedCandidate, candidate)
2665
3129
  );
2666
- if (matches.length !== 1) return unresolved("stale");
2667
- if (!explicitRegionEvidence(options.sentence, matches[0])) {
2668
- gate = "explicit_region_unproven";
2669
- return unresolved("ambiguous");
3130
+ if (!surfaceStable) {
3131
+ const uniqueBefore = source.candidates.filter(
3132
+ (candidate) => candidate.name === selectedCandidate.name && candidate.role === selectedCandidate.role
3133
+ ).length === 1;
3134
+ const uniqueAfter = fresh.candidates.filter(
3135
+ (candidate) => candidate.name === selectedCandidate.name && candidate.role === selectedCandidate.role
3136
+ ).length === 1;
3137
+ if (!uniqueBefore || !uniqueAfter || !exactNameRequested(options.sentence, selectedCandidate))
3138
+ return unresolved("stale");
3139
+ matches = fresh.candidates.filter(
3140
+ (candidate) => sameNodeControl(selectedCandidate, candidate)
3141
+ );
2670
3142
  }
3143
+ if (matches.length !== 1) return unresolved("stale");
2671
3144
  ensureActive();
2672
3145
  if (cacheOutcome?.outcome === "miss" && storedEntry && options.cache?.key && provedTargetChange(
2673
3146
  storedEntry,
@@ -5017,7 +5490,7 @@ function excerpt2(text) {
5017
5490
  return Array.from(text).slice(0, available).join("") + TRUNCATION_MARKER;
5018
5491
  }
5019
5492
  async function judgePage(page, judge, claim2, timeoutMs, signal, projectText) {
5020
- const digest = await settledDigest(page, timeoutMs, signal);
5493
+ let digest = await settledDigest(page, timeoutMs, signal);
5021
5494
  const projectedText = projectText ? projectText(digest.text) : digest.text;
5022
5495
  canceled(signal);
5023
5496
  let decision;
@@ -5057,8 +5530,28 @@ async function judgePage(page, judge, claim2, timeoutMs, signal, projectText) {
5057
5530
  const observed = observationError(error2, signal);
5058
5531
  throw new AssertionEngineError(observed.code, decision.call);
5059
5532
  }
5060
- if (!sameVersion4(current, digest.version))
5061
- throw new AssertionEngineError("stale_observation", decision.call);
5533
+ if (!sameVersion4(current, digest.version)) {
5534
+ if (current.document !== digest.version.document || current.route !== digest.version.route)
5535
+ throw new AssertionEngineError("stale_observation", decision.call);
5536
+ try {
5537
+ const deadline = performance.now() + POST_JUDGE_VERSION_TIMEOUT_MS;
5538
+ const fresh = await withinObservation(pageDigest(page), deadline, signal);
5539
+ validateDigest(fresh);
5540
+ const latest = await withinObservation(
5541
+ pageVersion(page),
5542
+ deadline,
5543
+ signal
5544
+ );
5545
+ if (fresh.text !== digest.text || !sameVersion4(fresh.version, latest) || fresh.version.document !== digest.version.document || fresh.version.route !== digest.version.route)
5546
+ throw new AssertionEngineError("stale_observation", decision.call);
5547
+ digest = fresh;
5548
+ } catch (error2) {
5549
+ throw new AssertionEngineError(
5550
+ observationError(error2, signal).code === "canceled" ? "canceled" : "stale_observation",
5551
+ decision.call
5552
+ );
5553
+ }
5554
+ }
5062
5555
  return { decision, digest: { ...digest, text: projectedText } };
5063
5556
  }
5064
5557
  async function verify(page, judge, claim2, options = {}) {
@@ -5085,7 +5578,7 @@ async function verify(page, judge, claim2, options = {}) {
5085
5578
  ...options.contradictionCutoff === void 0 ? {} : { contradictionCutoff: options.contradictionCutoff }
5086
5579
  });
5087
5580
  const needsExcerpt = policy.verdict === "failed" || policy.flags.length > 0;
5088
- return Object.defineProperty(
5581
+ return Object.defineProperties(
5089
5582
  {
5090
5583
  kind: "verify",
5091
5584
  ...policy,
@@ -5095,8 +5588,9 @@ async function verify(page, judge, claim2, options = {}) {
5095
5588
  elapsedMs: performance.now() - started,
5096
5589
  ...needsExcerpt ? { judgedExcerpt: excerpt2(digest.text) } : {}
5097
5590
  },
5098
- "observationVersion",
5099
- { value: digest.version, enumerable: false }
5591
+ {
5592
+ observationVersion: { value: digest.version, enumerable: false }
5593
+ }
5100
5594
  );
5101
5595
  }
5102
5596
  async function measure(page, judge, claim2, options = {}) {
@@ -5221,7 +5715,7 @@ function runtimeFailure(file, error2) {
5221
5715
  file,
5222
5716
  code: `provider_${error2.code}`,
5223
5717
  message: "The model provider could not complete the run safely.",
5224
- fix: error2.code === "configuration" || error2.code === "authentication" ? "Check TYPESAFE_API_KEY and provider access, then rerun the test." : "Check provider availability and the test input, then rerun the test."
5718
+ fix: error2.code === "configuration" || error2.code === "authentication" ? "Check the configured provider API key and access, then rerun the test." : "Check provider availability and the test input, then rerun the test."
5225
5719
  };
5226
5720
  }
5227
5721
  return {
@@ -5614,7 +6108,7 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
5614
6108
  }
5615
6109
  if (resolved.kind === "unresolved" && resolved.reason === "stale") {
5616
6110
  const priorCalls = resolved.calls;
5617
- const settled = await quietPage(page, 80, 4e3).catch(() => ({
6111
+ const settled = await quietPage(page, 1e3, 4e3).catch(() => ({
5618
6112
  quiet: false
5619
6113
  }));
5620
6114
  if (settled.quiet) {
@@ -5639,6 +6133,23 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
5639
6133
  }
5640
6134
  }
5641
6135
  }
6136
+ if (resolved.kind === "unresolved" && resolved.reason === "no_candidates") {
6137
+ const deadline = performance.now() + 8e3;
6138
+ while (performance.now() < deadline && !dependencies.signal?.aborted) {
6139
+ await new Promise((resolve) => setTimeout(resolve, 400));
6140
+ const settled = await quietPage(page, 80, 1e3).catch(() => ({
6141
+ quiet: false
6142
+ }));
6143
+ if (!settled.quiet) continue;
6144
+ try {
6145
+ const fresh = await locate();
6146
+ resolved = { ...fresh, calls: [...resolved.calls, ...fresh.calls] };
6147
+ if (resolved.kind !== "unresolved" || resolved.reason !== "no_candidates")
6148
+ break;
6149
+ } catch {
6150
+ }
6151
+ }
6152
+ }
5642
6153
  if (resolved.kind !== "resolved") {
5643
6154
  if (resolved.reason === "none" || resolved.reason === "ambiguous" || resolved.reason === "no_candidates")
5644
6155
  return record("failed", {
@@ -5663,16 +6174,9 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
5663
6174
  }
5664
6175
  );
5665
6176
  }
5666
- let command;
5667
- if (step.op === "click") command = { op: "click", target: resolved.target };
5668
- else {
5669
- command = {
5670
- op: "type",
5671
- target: resolved.target,
5672
- value: typeValue
5673
- };
5674
- }
5675
- const locatedPage = report ? await reportPage(
6177
+ const commandFor = (target) => step.op === "click" ? { op: "click", target } : { op: "type", target, value: typeValue };
6178
+ let command = commandFor(resolved.target);
6179
+ let locatedPage = report ? await reportPage(
5676
6180
  page,
5677
6181
  `${stepId}:observation:1`,
5678
6182
  report.privacy,
@@ -5680,21 +6184,50 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries) {
5680
6184
  ) : void 0;
5681
6185
  let replayFrame;
5682
6186
  let targetBox = null;
5683
- try {
5684
- await executeStep(page, command, {
5685
- ...dependencies.signal ? { signal: dependencies.signal } : {},
5686
- ...report?.replay ? {
5687
- beforeAction: async (box, aimVersion) => {
5688
- if (safeUrl(aimVersion.route, report.privacy).sensitive || safeUrl(page.url, report.privacy).sensitive) {
5689
- replayFrame = { status: "omitted", reason: "sensitive_page" };
5690
- return;
5691
- }
5692
- const frame = await capture("replay", aimVersion);
5693
- replayFrame = frame;
5694
- targetBox = frame.status === "captured" ? box ?? null : null;
6187
+ const performAction = () => executeStep(page, command, {
6188
+ ...dependencies.signal ? { signal: dependencies.signal } : {},
6189
+ ...report?.replay ? {
6190
+ beforeAction: async (box, aimVersion) => {
6191
+ if (safeUrl(aimVersion.route, report.privacy).sensitive || safeUrl(page.url, report.privacy).sensitive) {
6192
+ replayFrame = { status: "omitted", reason: "sensitive_page" };
6193
+ return;
5695
6194
  }
5696
- } : {}
5697
- });
6195
+ const frame = await capture("replay", aimVersion);
6196
+ replayFrame = frame;
6197
+ targetBox = frame.status === "captured" ? box ?? null : null;
6198
+ }
6199
+ } : {}
6200
+ });
6201
+ try {
6202
+ try {
6203
+ await performAction();
6204
+ } catch (error2) {
6205
+ if (!(error2 instanceof StepExecutionError) || error2.code !== "stale" || !error2.retryable)
6206
+ throw error2;
6207
+ const priorCalls = resolved.calls;
6208
+ replayFrame = void 0;
6209
+ targetBox = null;
6210
+ const quiet2 = await quietPage(page, 80, 4e3).catch(() => ({
6211
+ quiet: false
6212
+ }));
6213
+ if (!quiet2.quiet) throw error2;
6214
+ const retried = await locate();
6215
+ if (retried.kind !== "resolved") {
6216
+ resolved = { ...resolved, calls: [...priorCalls, ...retried.calls] };
6217
+ throw error2;
6218
+ }
6219
+ resolved = { ...retried, calls: [...priorCalls, ...retried.calls] };
6220
+ command = commandFor(resolved.target);
6221
+ locatedPage = report ? await reportPage(
6222
+ page,
6223
+ `${stepId}:observation:2`,
6224
+ report.privacy,
6225
+ resolved.target.driverTarget().version
6226
+ ) : void 0;
6227
+ replayFrame = void 0;
6228
+ targetBox = null;
6229
+ await performAction();
6230
+ }
5698
6231
  let recordedLocator = resolved;
5699
6232
  if (resolved.cacheSeed && dependencies.locatorCache?.key) {
5700
6233
  const seed = resolved.cacheSeed;