@reticlehq/engine 3.6.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/disagreement/contradiction-evidence.d.ts +134 -2
  2. package/dist/disagreement/contradiction-evidence.js +291 -3
  3. package/dist/disagreement/contradiction-types.d.ts +16 -1
  4. package/dist/disagreement/contradictions.d.ts +12 -0
  5. package/dist/disagreement/contradictions.js +56 -84
  6. package/dist/disagreement/stale-response.js +56 -17
  7. package/dist/evidence/already-true.d.ts +5 -0
  8. package/dist/evidence/already-true.js +27 -6
  9. package/dist/evidence/baseline.js +2 -6
  10. package/dist/evidence/blind-spots.d.ts +14 -3
  11. package/dist/evidence/blind-spots.js +48 -10
  12. package/dist/evidence/body-capture-remedy.d.ts +1 -15
  13. package/dist/evidence/body-capture-remedy.js +6 -1
  14. package/dist/evidence/instrumentation-gaps.js +3 -1
  15. package/dist/evidence/state-bookkeeping.d.ts +2 -0
  16. package/dist/evidence/state-bookkeeping.js +2 -0
  17. package/dist/evidence/step-effect.d.ts +20 -1
  18. package/dist/evidence/step-effect.js +30 -2
  19. package/dist/evidence/superseded-checks.d.ts +29 -0
  20. package/dist/evidence/superseded-checks.js +30 -0
  21. package/dist/evidence/uncaptured-bodies.d.ts +18 -1
  22. package/dist/evidence/uncaptured-bodies.js +22 -1
  23. package/dist/evidence/unread-outcome.d.ts +7 -0
  24. package/dist/evidence/unread-outcome.js +22 -0
  25. package/dist/evidence/unsettled.js +29 -2
  26. package/dist/evidence/verified.d.ts +8 -1
  27. package/dist/evidence/verified.js +33 -5
  28. package/dist/question/declared.d.ts +20 -0
  29. package/dist/question/declared.js +20 -1
  30. package/dist/question/predicate/net-blind-spots.d.ts +49 -0
  31. package/dist/question/predicate/net-blind-spots.js +153 -0
  32. package/dist/question/predicate/predicate-compare.js +7 -1
  33. package/dist/question/predicate/predicate-console.js +23 -10
  34. package/dist/question/predicate/predicate-element.d.ts +23 -0
  35. package/dist/question/predicate/predicate-element.js +208 -16
  36. package/dist/question/predicate/predicate-eval-kit.d.ts +28 -3
  37. package/dist/question/predicate/predicate-eval-kit.js +34 -7
  38. package/dist/question/predicate/predicate-eval.d.ts +11 -1
  39. package/dist/question/predicate/predicate-eval.js +138 -177
  40. package/dist/question/predicate/predicate-parse.js +34 -0
  41. package/dist/question/predicate/predicate-request-body.d.ts +15 -1
  42. package/dist/question/predicate/predicate-request-body.js +23 -3
  43. package/dist/question/predicate/predicate-route.d.ts +2 -0
  44. package/dist/question/predicate/predicate-route.js +30 -0
  45. package/dist/question/predicate/predicate-schema.d.ts +11 -0
  46. package/dist/question/predicate/predicate-schema.js +52 -1
  47. package/dist/question/predicate/predicate-state.js +7 -0
  48. package/dist/question/predicate/predicate.js +58 -18
  49. package/dist/question/predicate/split-text-miss.d.ts +7 -0
  50. package/dist/question/predicate/split-text-miss.js +18 -1
  51. package/dist/state-bookkeeping.d.ts +27 -0
  52. package/dist/state-bookkeeping.js +74 -0
  53. package/dist/window/adversary.js +5 -1
  54. package/package.json +2 -2
@@ -0,0 +1,153 @@
1
+ /**
2
+ * What the `net` channel cannot see, and what a miss over it is allowed to claim.
3
+ *
4
+ * The network observer patches `fetch` and `XMLHttpRequest`; a document-initiated subresource, a
5
+ * native download and anything before the SDK attached never reach it. Each rule here exists so a
6
+ * zero-match `net` verdict says "not observable" or names its blind stretch, instead of "never
7
+ * happened". Split from `predicate-eval.ts`, which decides the verdict; this only knows the channel.
8
+ *
9
+ * Takes the filter's parts rather than the predicate, so it needs nothing from the contract.
10
+ */
11
+ /**
12
+ * URL suffixes only the DOCUMENT fetches, which the network observer therefore never records.
13
+ *
14
+ * `network.ts` patches `fetch` and `XMLHttpRequest` and nothing else, so `<link rel=icon>`,
15
+ * `<link rel=manifest>`, stylesheets, fonts and `<img src>` are invisible to it. "No matching call"
16
+ * and "that class of call is not observed" are then indistinguishable, and the miss graded
17
+ * `assertion_failed` — a false RED. Reported from the field: an assert over `/favicon.ico`,
18
+ * `/site.webmanifest` and `/apple-touch-icon.png` returned `verified:"no"` while curl showed all
19
+ * three answering 200. A false negative here is worse than an unknown, because an agent that trusts
20
+ * it goes and "fixes" working code.
21
+ *
22
+ * Deliberately NOT here: `.js` and `.json`. Both are routinely fetched via `fetch`/XHR — a module
23
+ * preload and an API call can share a suffix — so downgrading them would hide real misses. This list
24
+ * is only the suffixes for which the document is the sole plausible initiator.
25
+ *
26
+ * This began as the smaller half of #447: it did not make these requests observable, it stopped
27
+ * Reticle claiming they did not happen. The other half, observing them via resource timing, has
28
+ * since landed in the browser SDK, so the two halves are no longer independent and this downgrade is
29
+ * now GATED: when the event stream carries at least one document-initiated record, the observer is
30
+ * demonstrably live and a miss over these suffixes is real evidence, graded a plain failure. Only a
31
+ * page whose stream holds no resource entry at all keeps the honest "cannot tell apart" answer,
32
+ * because there the observer may simply not exist.
33
+ */
34
+ const DOCUMENT_ONLY_SUFFIXES = [
35
+ '.ico',
36
+ '.png',
37
+ '.jpg',
38
+ '.jpeg',
39
+ '.gif',
40
+ '.svg',
41
+ '.webp',
42
+ '.avif',
43
+ '.bmp',
44
+ '.css',
45
+ '.woff',
46
+ '.woff2',
47
+ '.ttf',
48
+ '.otf',
49
+ '.eot',
50
+ '.webmanifest',
51
+ ];
52
+ /**
53
+ * File suffixes a click typically downloads or navigates to as a document, never as fetch/XHR.
54
+ *
55
+ * Sibling of DOCUMENT_ONLY_SUFFIXES, not a member of it. Those are subresources: once resource
56
+ * timing is live, a miss is evidence. A click on `<a href="/export.pdf">` is a navigation (or a
57
+ * Content-Disposition attachment). Resource timing of stylesheets does not make it visible, so
58
+ * grading the miss as "0 network calls" / a 404 is the lie #805 exists to stop — even on a page
59
+ * whose observer is running. `.js` / `.json` stay off this list for the same reason they stay off
60
+ * the other: they are routinely fetched.
61
+ */
62
+ const NATIVE_DOWNLOAD_SUFFIXES = [
63
+ '.pdf',
64
+ '.csv',
65
+ '.tsv',
66
+ '.zip',
67
+ '.gz',
68
+ '.tar',
69
+ '.xlsx',
70
+ '.xls',
71
+ '.docx',
72
+ '.doc',
73
+ '.pptx',
74
+ '.ppt',
75
+ '.ods',
76
+ '.odt',
77
+ '.rtf',
78
+ '.7z',
79
+ '.rar',
80
+ ];
81
+ /**
82
+ * Does this filter target a class of request the observer cannot see?
83
+ *
84
+ * Read off `urlContains` only, and only when the pattern ENDS in one of the suffixes — a filter of
85
+ * `/api/` that happens to contain `.css` somewhere in a query string is still an ordinary XHR
86
+ * target. Query strings and fragments are stripped first, since `favicon.ico?v=2` is the same asset.
87
+ */
88
+ function filterPath(urlContains) {
89
+ return (urlContains.split('#')[0] ?? '').split('?')[0]?.toLowerCase() ?? '';
90
+ }
91
+ /**
92
+ * Does this filter target a class of request the observer cannot see?
93
+ *
94
+ * Read off `urlContains` only, and only when the pattern ENDS in one of the suffixes — a filter of
95
+ * `/api/` that happens to contain `.css` somewhere in a query string is still an ordinary XHR
96
+ * target. Query strings and fragments are stripped first, since `favicon.ico?v=2` is the same asset.
97
+ */
98
+ export function targetsUnobservedChannel(url) {
99
+ if (undefined === url)
100
+ return false;
101
+ return DOCUMENT_ONLY_SUFFIXES.some((suffix) => filterPath(url).endsWith(suffix));
102
+ }
103
+ export function targetsNativeDownload(url) {
104
+ if (undefined === url)
105
+ return false;
106
+ return NATIVE_DOWNLOAD_SUFFIXES.some((suffix) => filterPath(url).endsWith(suffix));
107
+ }
108
+ /** `filter` is the net clause as applied — `describeNetFilter` of it. */
109
+ export function nativeDownloadReason(filter) {
110
+ return (`no fetch or XHR matched ${filter}. A native download or document navigation ` +
111
+ `(an <a href> to a file, a Content-Disposition attachment, <a download>) never goes through ` +
112
+ `fetch or XMLHttpRequest, so an empty net window is not a 404 and is not evidence the export ` +
113
+ `failed. This is unobservable on the net channel. Assert the link href, or check the file ` +
114
+ `outside the browser — Reticle cannot see the bytes land`);
115
+ }
116
+ /** The sentence both zero-match branches hand to `inconclusive`; `filter` as `nativeDownloadReason`. */
117
+ export function unobservedChannelReason(filter) {
118
+ return (`no call matched ${filter}, and no document-initiated load was recorded either, ` +
119
+ `so this page exposed no resource timing to read: Reticle observes fetch and XMLHttpRequest ` +
120
+ `directly, while a request the document initiates (<link rel=icon|manifest|preload>, a ` +
121
+ `stylesheet, a font, <img src>) leaves no record, and that state cannot be told apart from the ` +
122
+ `request having been made. ` +
123
+ `Nothing here says the app is wrong. Check it outside the browser, or assert something the ` +
124
+ `document does not fetch on its own`);
125
+ }
126
+ /**
127
+ * Appended to a zero-match `net` negative whose window starts at SDK attach.
128
+ *
129
+ * Every event's `t` is stamped `performance.now() - #start`, where `#start` is taken when the SDK
130
+ * is constructed, so `t` is never negative and a window with `since === 0` begins AT attach — never
131
+ * before it. Whatever the page did between navigation start and attach left no event at all, so
132
+ * "no matching call" over such a window cannot be told apart from "the call was made while nothing
133
+ * was watching yet".
134
+ *
135
+ * The gap is routine rather than exotic: a `fetch` from an effect in a root provider, or a classic
136
+ * `<script>` at the end of `<body>`, fires before a deferred module script has run. Read as proof
137
+ * the request was never made, that sends a reader looking for a defect in code that works —
138
+ * restarting dev servers and re-reading providers to establish that the request was invisible rather
139
+ * than absent.
140
+ *
141
+ * Same argument as DOCUMENT_ONLY_SUFFIXES one axis over: that one is a channel Reticle does not
142
+ * watch, this is a stretch of TIME it was not yet watching.
143
+ *
144
+ * The grade is deliberately NOT downgraded to `inconclusive`. A missing API call is the finding this
145
+ * oracle exists to make, and it is the strongest grade available for the startup class — session
146
+ * restore, feature flags, bootstrap config — which is exactly the class that silently breaks on
147
+ * reload. Every window an action opens carries `since > 0` and is untouched. What changes is only
148
+ * what the negative CLAIMS: it stops asserting the request never happened, and names the assertion
149
+ * that can settle it, because the state such a request produces IS observable after attach.
150
+ */
151
+ export const PRE_ATTACH_CAVEAT = ' — note that this window starts where the SDK attached, and requests made before that are never ' +
152
+ 'captured, so a miss here cannot tell a call that was never made apart from one made before the ' +
153
+ 'page connected; if the call is expected during startup, assert on the state it produces instead';
@@ -11,6 +11,8 @@ import { CompareAs, EventType, NetBodySide, PredicateKind, REDACTED_VALUE, urlFo
11
11
  import { parseJsonObject, readField, redactedOnPath, str, } from './predicate-eval-kit.js';
12
12
  import { evalElement, joinedText } from './predicate-element.js';
13
13
  import { evalState } from './predicate-state.js';
14
+ import { skippedBodyRemedy } from './predicate-eval.js';
15
+ import { requestBodySkipRemedy } from './predicate-request-body.js';
14
16
  const REMEDY_BODY_CAPTURE = 'enable it where the app calls connect(): reticle({ captureNetworkBodies: true })';
15
17
  function unknown(reason) {
16
18
  return { result: { pass: false, failureReason: reason, inconclusive: reason } };
@@ -66,7 +68,11 @@ function readNet(events, source) {
66
68
  const request = NetBodySide.REQUEST === source.body;
67
69
  const body = str(call.data[request ? 'requestBody' : 'responseBody']);
68
70
  if (body === undefined) {
69
- return unknown(`the ${label} was not recorded, so it could not be read — ${REMEDY_BODY_CAPTURE}`);
71
+ // With capture on, the SDK says why it skipped this body; the capture remedy is for the rest.
72
+ const remedy = request
73
+ ? requestBodySkipRemedy(call.data['requestBodyType'])
74
+ : skippedBodyRemedy(call.data['responseBodyReason']);
75
+ return unknown(`the ${label} was not recorded, so it could not be read — ${remedy ?? REMEDY_BODY_CAPTURE}`);
70
76
  }
71
77
  const truncated = true === call.data[request ? 'requestBodyTruncated' : 'responseBodyTruncated'];
72
78
  const payload = parseJsonObject(body);
@@ -6,12 +6,26 @@
6
6
  * else in the evaluator reads a CONSOLE_* event.
7
7
  */
8
8
  import { CONSOLE_ATTACH_NOTE, EventType, PredicateKind } from '@reticlehq/core';
9
- /** The only console levels Reticle instruments (console.info/debug/trace are NOT patched). */
9
+ /** The console levels the SDK patches. console.trace is not patched, so it is not here. */
10
10
  const CONSOLE_LEVEL_TYPE = {
11
11
  log: EventType.CONSOLE_LOG,
12
12
  warn: EventType.CONSOLE_WARN,
13
13
  error: EventType.CONSOLE_ERROR,
14
+ info: EventType.CONSOLE_INFO,
15
+ debug: EventType.CONSOLE_DEBUG,
14
16
  };
17
+ /** What a check with no level reads: every level when it names a message, the loud ones when not. */
18
+ const LOUD_LEVELS = new Set([
19
+ EventType.CONSOLE_LOG,
20
+ EventType.CONSOLE_WARN,
21
+ EventType.CONSOLE_ERROR,
22
+ EventType.ERROR_UNCAUGHT,
23
+ ]);
24
+ const EVERY_LEVEL = new Set([
25
+ ...LOUD_LEVELS,
26
+ EventType.CONSOLE_INFO,
27
+ EventType.CONSOLE_DEBUG,
28
+ ]);
15
29
  /**
16
30
  * Has the console channel reported ANYTHING in this window, at any level?
17
31
  *
@@ -35,15 +49,14 @@ function channelReported(events, since) {
35
49
  }
36
50
  export function evalConsole(events, p) {
37
51
  const since = p.since ?? 0;
38
- // Reticle only instruments console.log/warn/error. A level outside that set is never captured,
39
- // so its events can't exist — and an `absent` assertion on it would verify NOTHING while
40
- // reporting green. Fail loudly instead of false-passing.
52
+ // A level the SDK does not patch is never captured, so its events can't exist — and an `absent`
53
+ // assertion on it would verify NOTHING while reporting green. Fail loudly instead of false-passing.
41
54
  if (p.level !== undefined && p.level !== 'error' && CONSOLE_LEVEL_TYPE[p.level] === undefined) {
42
55
  return {
43
56
  pass: false,
44
- failureReason: `console level '${p.level}' is not captured — Reticle instruments console.log, console.warn, console.error only`,
57
+ failureReason: `console level '${p.level}' is not captured — Reticle instruments console.log, console.warn, console.error, console.info and console.debug only`,
45
58
  observed: `level '${p.level}' is not instrumented, so no event of it can ever exist`,
46
- expected: 'a level Reticle captures: log, warn, or error',
59
+ expected: 'a level Reticle captures: log, warn, error, info or debug',
47
60
  assertion: 'console.uninstrumented-level',
48
61
  };
49
62
  }
@@ -52,10 +65,10 @@ export function evalConsole(events, p) {
52
65
  return false;
53
66
  const isErr = e.type === EventType.CONSOLE_ERROR || e.type === EventType.ERROR_UNCAUGHT;
54
67
  if (p.level === undefined) {
55
- return (e.type === EventType.CONSOLE_LOG ||
56
- e.type === EventType.CONSOLE_WARN ||
57
- e.type === EventType.CONSOLE_ERROR ||
58
- e.type === EventType.ERROR_UNCAUGHT);
68
+ // A named message is matched at any level: `{ contains: "X", absent: true }` used to pass
69
+ // while X was logged with console.info. A clean-console check names no message and stays
70
+ // deaf to info/debug chatter, which most apps produce on every action.
71
+ return ('contains' in p && p.contains !== undefined ? EVERY_LEVEL : LOUD_LEVELS).has(e.type);
59
72
  }
60
73
  if ('error' === p.level)
61
74
  return isErr;
@@ -10,7 +10,30 @@ import { type ElementQuery, ElementState } from '@reticlehq/core';
10
10
  import { type EvalResult } from './predicate-eval.js';
11
11
  import type { PredicateSession } from './predicate-session.js';
12
12
  import { type Baseline, type PropertyAssertion } from './property.js';
13
+ export declare const ARIA_HIDDEN_NOTE = "text is inside an aria-hidden subtree \u2014 drawn on screen but excluded from the accessible tree";
14
+ /**
15
+ * HTML tag names mapped to the ARIA role that `getRole` gives them. A query like `{ role: "iframe" }`
16
+ * always returns zero results because `iframe` is a tag, not a role. The map names the correct role
17
+ * so the hint can say exactly what to use instead.
18
+ */
19
+ export declare const HTML_TAG_TO_ARIA_ROLE: Map<string, string>;
13
20
  export declare function evalElement(session: PredicateSession, query: ElementQuery, state: ElementState | undefined, absent: boolean, diagnose: boolean): Promise<EvalResult>;
14
21
  /** The text of every element a passing match described, joined — what a reader sees there. */
15
22
  export declare function joinedText(evidence: unknown): string;
16
23
  export declare function withTextProperty(base: EvalResult, assertion: PropertyAssertion, subject: string, baseline?: Baseline): EvalResult;
24
+ /**
25
+ * The element query a text predicate is evaluated through — one builder for the verdict and its
26
+ * baseline, so the two cannot disagree about what text was asked for.
27
+ *
28
+ * `matchCase` unless the predicate opts out: a check that matched "Saved Priya" against "Saved
29
+ * priya" could never catch a capitalisation defect. An undefined `contains` must not reach the query
30
+ * as `text: undefined` — that is a locator asking for the empty string.
31
+ */
32
+ export declare function textPredicateQuery(predicate: {
33
+ contains?: string | undefined;
34
+ ignoreCase?: boolean | undefined;
35
+ scope?: string | undefined;
36
+ self?: boolean | undefined;
37
+ },
38
+ /** The page SDK's version. A page older than MATCH_CASE_SINCE rejects the field outright. */
39
+ sdkVersion?: string): ElementQuery;
@@ -7,11 +7,77 @@
7
7
  * ever enrich a failure. Nothing else in the predicate layer talks to `ReticleCommand.MATCH`.
8
8
  */
9
9
  import { QueryBy, ReticleCommand, ElementState, } from '@reticlehq/core';
10
- import { describeUnusableElementQuery, residualQueryChecks, satisfiesResiduals, describeResidual, } from './predicate-eval.js';
10
+ import { describeAltOnNonImage, describeUnusableElementQuery, residualQueryChecks, withAltProjected, satisfiesResiduals, describeResidual, } from './predicate-eval.js';
11
11
  import { describeTestidMiss } from './testid-near-miss.js';
12
- import { describeSplitTextMiss } from './split-text-miss.js';
12
+ import { describeCaseMiss, describeSplitTextMiss } from './split-text-miss.js';
13
13
  import { satisfiesProperty } from './property.js';
14
14
  import { describeNameNearMiss } from './name-near-miss.js';
15
+ export const ARIA_HIDDEN_NOTE = 'text is inside an aria-hidden subtree — drawn on screen but excluded from the accessible tree';
16
+ /**
17
+ * HTML tag names mapped to the ARIA role that `getRole` gives them. A query like `{ role: "iframe" }`
18
+ * always returns zero results because `iframe` is a tag, not a role. The map names the correct role
19
+ * so the hint can say exactly what to use instead.
20
+ */
21
+ export const HTML_TAG_TO_ARIA_ROLE = new Map([
22
+ ['iframe', 'generic'],
23
+ ['div', 'generic'],
24
+ ['span', 'generic'],
25
+ ['video', 'generic'],
26
+ ['audio', 'generic'],
27
+ ['canvas', 'generic'],
28
+ ['embed', 'generic'],
29
+ ['object', 'generic'],
30
+ ['input', 'textbox'],
31
+ ['textarea', 'textbox'],
32
+ ['a', 'link'],
33
+ ['select', 'combobox'],
34
+ ['nav', 'navigation'],
35
+ ['li', 'listitem'],
36
+ ['ul', 'list'],
37
+ ['ol', 'list'],
38
+ ['p', 'paragraph'],
39
+ ['h1', 'heading'],
40
+ ['h2', 'heading'],
41
+ ['h3', 'heading'],
42
+ ['h4', 'heading'],
43
+ ['h5', 'heading'],
44
+ ['h6', 'heading'],
45
+ ['header', 'banner'],
46
+ ['footer', 'contentinfo'],
47
+ ['aside', 'complementary'],
48
+ ['section', 'region'],
49
+ ]);
50
+ /**
51
+ * When the query's role is a raw HTML tag name, name the correct ARIA role to use instead.
52
+ * Context-dependent tags state the condition so the hint is never wrong.
53
+ */
54
+ function describeUnreachableRole(role) {
55
+ if (role === undefined)
56
+ return undefined;
57
+ const tag = role.toLowerCase();
58
+ const ariaRole = HTML_TAG_TO_ARIA_ROLE.get(tag);
59
+ if (ariaRole === undefined)
60
+ return undefined;
61
+ if ('section' === tag) {
62
+ return (`'section' is not an ARIA role — ` +
63
+ `a named <section> (with aria-label, aria-labelledby, or title) has role 'region'; ` +
64
+ `an unnamed one has role 'generic'`);
65
+ }
66
+ if ('a' === tag) {
67
+ return `'a' is not an ARIA role — <a> elements have role 'link' when they carry an href, otherwise 'generic'`;
68
+ }
69
+ if ('select' === tag) {
70
+ return `'select' is not an ARIA role — <select> elements have role 'combobox', or 'listbox' when the multiple attribute is set`;
71
+ }
72
+ if ('input' === tag) {
73
+ return (`'input' is not an ARIA role — <input> role depends on its type attribute: ` +
74
+ `'textbox' for text/email/url/password, 'checkbox', 'radio', 'button', or 'slider' for range`);
75
+ }
76
+ if ('generic' === ariaRole) {
77
+ return `'${role}' is not an ARIA role — <${role}> elements have role 'generic'; try { role: 'generic' } with a name or title, or use a testid`;
78
+ }
79
+ return `'${role}' is not an ARIA role — <${role}> elements have role '${ariaRole}'; try { role: '${ariaRole}' }`;
80
+ }
15
81
  /**
16
82
  * The caveat for a present-testid list that was cut at its cap, or nothing when it was whole.
17
83
  *
@@ -45,8 +111,28 @@ function describeAbsentMiss(match, state) {
45
111
  return (`${found}, but ${which} hidden — \`absent\` means removed from the DOM; ` +
46
112
  `to assert it isn't shown, use \`state: "${ElementState.HIDDEN}"\``);
47
113
  }
48
- async function matchOnce(session, query, state) {
49
- const res = await session.command(ReticleCommand.MATCH, { query, state });
114
+ /**
115
+ * Why a match under a framework error dialog proves nothing. The element is in the DOM, but a user
116
+ * sees only the dialog, so a `yes` here was a false green (#1768).
117
+ */
118
+ function describeCovered(dialog) {
119
+ return (`a ${dialog} covers the page, so a user cannot see this match. ` +
120
+ 'Read the error in the dialog and fix it, then check again');
121
+ }
122
+ /**
123
+ * Why a match that a person cannot read proves nothing. The text is in the DOM, but its colour is
124
+ * almost the colour behind it, or it is almost transparent. A `yes` here was a false green (#1797).
125
+ */
126
+ function describeUnreadable(why) {
127
+ return (`the text is on the page, but a user cannot read it (${why}). ` +
128
+ 'Fix the colour or the opacity, then check again');
129
+ }
130
+ async function matchOnce(session, query, state, diagnose) {
131
+ const res = await session.command(ReticleCommand.MATCH, {
132
+ query,
133
+ state,
134
+ ...(true === diagnose ? { diagnose: true } : {}),
135
+ });
50
136
  if (!res.ok)
51
137
  return { matched: false, count: 0, elements: [] };
52
138
  return (res.result ?? { matched: false, count: 0, elements: [] });
@@ -102,21 +188,27 @@ function versionParts(version) {
102
188
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
103
189
  return null === m ? undefined : [Number(m[1]), Number(m[2]), Number(m[3])];
104
190
  }
105
- /** The state, when the page's SDK is older than the first release that answers it. */
106
- function stateTheSdkPredates(sdk, state) {
107
- const since = state === undefined ? undefined : ELEMENT_STATE_SINCE[state];
108
- if (sdk === undefined || state === undefined || since === undefined)
109
- return undefined;
110
- const have = versionParts(sdk);
191
+ /** Whether the page's SDK is older than `since`. An unknown or unreadable version is not. */
192
+ function sdkPredates(sdk, since) {
193
+ const have = sdk === undefined ? undefined : versionParts(sdk);
111
194
  const need = versionParts(since);
112
195
  if (have === undefined || need === undefined)
113
- return undefined;
196
+ return false;
114
197
  for (let i = 0; i < 3; i += 1) {
115
198
  if (have[i] !== need[i])
116
- return (have[i] ?? 0) < (need[i] ?? 0) ? { sdk, state, since } : undefined;
199
+ return (have[i] ?? 0) < (need[i] ?? 0);
117
200
  }
118
- return undefined;
201
+ return false;
202
+ }
203
+ /** The state, when the page's SDK is older than the first release that answers it. */
204
+ function stateTheSdkPredates(sdk, state) {
205
+ const since = state === undefined ? undefined : ELEMENT_STATE_SINCE[state];
206
+ if (sdk === undefined || state === undefined || since === undefined)
207
+ return undefined;
208
+ return sdkPredates(sdk, since) ? { sdk, state, since } : undefined;
119
209
  }
210
+ /** The first SDK release whose element query accepts `matchCase`; an older page refuses the query. */
211
+ const MATCH_CASE_SINCE = '3.7.0';
120
212
  export async function evalElement(session, query, state, absent, diagnose) {
121
213
  const tooOld = stateTheSdkPredates(session.sdkVersion, state);
122
214
  if (tooOld !== undefined) {
@@ -140,7 +232,7 @@ export async function evalElement(session, query, state, absent, diagnose) {
140
232
  const reason = describeUnusableElementQuery(query, residual.unusable);
141
233
  return { pass: false, failureReason: reason, inconclusive: reason };
142
234
  }
143
- let match = await matchOnce(session, query, state);
235
+ let match = await matchOnce(session, withAltProjected(query, residual.checks), state, diagnose);
144
236
  const subject = JSON.stringify(query);
145
237
  // A residual narrows the SET; `count` is every match while `elements` is only the described prefix,
146
238
  // so a locator broad enough to be truncated cannot be narrowed honestly. Say so instead of guessing.
@@ -148,6 +240,13 @@ export async function evalElement(session, query, state, absent, diagnose) {
148
240
  const reason = `${String(match.count)} elements matched ${subject} and only ${String(match.elements.length)} were described, so ${residual.checks.map(([f]) => `\`${f}\``).join(', ')} could not be checked against all of them — narrow the locator`;
149
241
  return { pass: false, failureReason: reason, inconclusive: reason };
150
242
  }
243
+ // `alt` is only meaningful on an image, and the role that says so is on the matched descriptor, so
244
+ // this cannot be refused before the round-trip the way an uncheckable field is. It runs AFTER the
245
+ // truncation check: judged on a cut-off prefix, "none of these is an image" would be a guess.
246
+ const altRefusal = describeAltOnNonImage(residual.checks, match.elements);
247
+ if (altRefusal !== undefined) {
248
+ return { pass: false, failureReason: altRefusal, inconclusive: altRefusal };
249
+ }
151
250
  const kept = match.elements.filter((element) => satisfiesResiduals(element, residual.checks));
152
251
  // The locator found something and the dropped fields disagree with it. Reported separately from a
153
252
  // plain miss because the fixes are opposite: the element IS there, its value is not what was claimed.
@@ -203,6 +302,30 @@ export async function evalElement(session, query, state, absent, diagnose) {
203
302
  }
204
303
  const announced = substantiveMatches(query, match.elements);
205
304
  if (match.matched && (announced.length > 0 || 0 === match.elements.length)) {
305
+ if (match.coveredBy !== undefined) {
306
+ const reason = describeCovered(match.coveredBy);
307
+ return {
308
+ pass: false,
309
+ failureReason: reason,
310
+ inconclusive: reason,
311
+ observed: `element matching ${subject} is in the DOM under the ${match.coveredBy}`,
312
+ expected: `an element matching ${subject} that a user can see`,
313
+ assertion: 'element.covered',
314
+ evidence: announced,
315
+ };
316
+ }
317
+ if (match.unreadable !== undefined) {
318
+ const reason = describeUnreadable(match.unreadable);
319
+ return {
320
+ pass: false,
321
+ failureReason: reason,
322
+ inconclusive: reason,
323
+ observed: `element matching ${subject} is in the DOM, and ${match.unreadable}`,
324
+ expected: `an element matching ${subject} that a user can read`,
325
+ assertion: 'element.readable',
326
+ evidence: announced,
327
+ };
328
+ }
206
329
  return { pass: true, evidence: announced };
207
330
  }
208
331
  // Matched, but every match was a mounted-and-empty live region. Reported as its own failure rather
@@ -266,6 +389,22 @@ export async function evalElement(session, query, state, absent, diagnose) {
266
389
  evidence: { nearMiss: roleOnly.elements },
267
390
  };
268
391
  }
392
+ // Nothing on the page has that role at all. The control is often there under ANOTHER role — a
393
+ // contenteditable composer is not a `textbox`, a styled div is not a `button` — and the name is
394
+ // the part the agent got right. Name the controls carrying it, with their real roles, so the
395
+ // retry targets what exists instead of guessing again. A diagnosis only: `pass` stays false.
396
+ const byName = await nearestByName(session, query.name, state);
397
+ if (byName.length > 0) {
398
+ const seen = byName.map((e) => `${'' === e.role ? 'no role' : e.role} "${'' === e.name ? (e.text ?? '') : e.name}" (${e.ref})`);
399
+ return {
400
+ pass: false,
401
+ failureReason: `no '${query.role}' named '${query.name}'; that name is on: ${seen.join(', ')}`,
402
+ observed: `no element has role '${query.role}'; elements named '${query.name}': ${seen.join(', ')}`,
403
+ expected: `a '${query.role}' named '${query.name}'`,
404
+ assertion: 'element.role+name',
405
+ evidence: { nearestByName: byName },
406
+ };
407
+ }
269
408
  }
270
409
  // The testid near-miss: name what IS here, so a typo is one step from fixed rather than a dead
271
410
  // end. reticle_query has always done this; the predicate path had no equivalent. See
@@ -284,7 +423,15 @@ export async function evalElement(session, query, state, absent, diagnose) {
284
423
  // already limited to that role.
285
424
  const nearMissRole = QueryBy.ROLE === query.by ? query.value : query.role;
286
425
  const nearMiss = describeNameNearMiss(match.hint?.nameNearMiss, query.name, nearMissRole);
287
- const clause = splitText ?? nearMiss ?? (alsoHere === undefined || '' === alsoHere ? undefined : alsoHere);
426
+ const caseMiss = describeCaseMiss(match.hint?.caseMiss);
427
+ const ariaNote = true === match.hint?.ariaHiddenMatch ? ARIA_HIDDEN_NOTE : undefined;
428
+ const unreachableRole = describeUnreachableRole(nearMissRole);
429
+ const clause = caseMiss ??
430
+ splitText ??
431
+ nearMiss ??
432
+ ariaNote ??
433
+ unreachableRole ??
434
+ (alsoHere === undefined || '' === alsoHere ? undefined : alsoHere);
288
435
  const suffix = clause === undefined ? '' : ` — ${clause}`;
289
436
  // The evidence list is capped in document order, so a region low on the page is exactly what it
290
437
  // drops. Handed back with no marker it reads as the whole page, and the field report this came
@@ -293,6 +440,13 @@ export async function evalElement(session, query, state, absent, diagnose) {
293
440
  const cut = describePresentTestidsCut(present.length, total);
294
441
  return {
295
442
  pass: false,
443
+ // The page shows the text in another case. Still a failure — see EvalResult.caseOnlyMiss.
444
+ ...(caseMiss === undefined
445
+ ? {}
446
+ : {
447
+ caseOnlyMiss: true,
448
+ wouldHold: `the same check with ignoreCase: true (the page shows "${match.hint?.caseMiss ?? ''}")`,
449
+ }),
296
450
  failureReason: `no element matched ${subject}${state === undefined ? '' : ` in state '${state}'`}${suffix}${cut}`,
297
451
  observed: `no matching element on the page${suffix}`,
298
452
  expected: `an element matching ${subject}${state === undefined ? '' : ` in state '${state}'`}`,
@@ -300,12 +454,14 @@ export async function evalElement(session, query, state, absent, diagnose) {
300
454
  // `splitText` rides on the evidence because it is a POSITIVE observation: the browser found the
301
455
  // string in the rendered page. `annotateThrottledMiss` reads it so a miss on a backgrounded tab
302
456
  // is not blamed on a render that demonstrably happened.
303
- ...(present.length > 0 || splitText !== undefined
457
+ ...(present.length > 0 || splitText !== undefined || caseMiss !== undefined
304
458
  ? {
305
459
  evidence: {
306
460
  ...(present.length > 0 ? { presentTestids: present } : {}),
307
461
  ...(total === undefined || 0 === present.length ? {} : { presentTestidsTotal: total }),
308
462
  ...(splitText === undefined ? {} : { splitText: match.hint?.splitText }),
463
+ // Positive too: the page rendered the text, in another case.
464
+ ...(caseMiss === undefined ? {} : { caseMiss: match.hint?.caseMiss }),
309
465
  },
310
466
  }
311
467
  : {}),
@@ -356,3 +512,39 @@ export function withTextProperty(base, assertion, subject, baseline) {
356
512
  evidence: described,
357
513
  };
358
514
  }
515
+ /** How many same-name controls a role miss names. */
516
+ const MAX_BY_NAME = 3;
517
+ /**
518
+ * Elements carrying an accessible name, whatever their role: by label (aria-label, <label>), then by
519
+ * placeholder. The first locator that finds any wins; at most MAX_BY_NAME are named.
520
+ */
521
+ async function nearestByName(session, name, state) {
522
+ for (const query of [{ label: name }, { placeholder: name }]) {
523
+ const found = await matchOnce(session, query, state);
524
+ if (found.matched)
525
+ return found.elements.slice(0, MAX_BY_NAME);
526
+ }
527
+ return [];
528
+ }
529
+ /**
530
+ * The element query a text predicate is evaluated through — one builder for the verdict and its
531
+ * baseline, so the two cannot disagree about what text was asked for.
532
+ *
533
+ * `matchCase` unless the predicate opts out: a check that matched "Saved Priya" against "Saved
534
+ * priya" could never catch a capitalisation defect. An undefined `contains` must not reach the query
535
+ * as `text: undefined` — that is a locator asking for the empty string.
536
+ */
537
+ export function textPredicateQuery(predicate,
538
+ /** The page SDK's version. A page older than MATCH_CASE_SINCE rejects the field outright. */
539
+ sdkVersion) {
540
+ // ponytail: an older page compares case-blind, as the engine did before it sent the field; update the SDK for case-exact checks.
541
+ const matchCase = true !== predicate.ignoreCase && !sdkPredates(sdkVersion, MATCH_CASE_SINCE);
542
+ return {
543
+ ...(undefined === predicate.contains
544
+ ? {}
545
+ : { text: predicate.contains, ...(matchCase ? { matchCase: true } : {}) }),
546
+ ...(undefined === predicate.scope
547
+ ? {}
548
+ : { scope: predicate.scope, ...(true === predicate.self ? { self: true } : {}) }),
549
+ };
550
+ }
@@ -1,4 +1,4 @@
1
- import { PredicateKind } from '@reticlehq/core';
1
+ import { PredicateKind, asNumber, asString } from '@reticlehq/core';
2
2
  import type { Predicate } from './predicate-schema.js';
3
3
  /**
4
4
  * What an evaluation ANSWERS, and the small comparisons every oracle answers it with.
@@ -66,14 +66,39 @@ export interface EvalResult {
66
66
  observed?: string;
67
67
  expected?: string;
68
68
  assertion?: string;
69
+ /**
70
+ * The text IS on the page, in another case. `pass` stays false — a capitalisation defect is a
71
+ * defect — and `wouldHold` names the check that would have held, so the retry is one decision
72
+ * (does case matter here?) rather than a hunt.
73
+ */
74
+ caseOnlyMiss?: boolean;
75
+ wouldHold?: string;
69
76
  }
70
- export declare function str(value: unknown): string | undefined;
71
- export declare function num(value: unknown): number | undefined;
77
+ /** Core's `asString` and `asNumber`, under the names the oracles here read them by. */
78
+ export { asString as str, asNumber as num };
72
79
  /**
73
80
  * Match one value against a pattern. Supports `*` (present), strict equality, and operators:
74
81
  * `{$gte,$lte,$gt,$lt}` (numbers), `{$contains}` (array membership or substring), `{$length}`.
75
82
  */
76
83
  export declare function matchValue(got: unknown, want: unknown): boolean;
84
+ /**
85
+ * Detects the #1117 pattern: an MCP client stringified a primitive before sending it, so
86
+ * `false` arrived as `"false"`, `42` as `"42"`, `null` as `"null"`. The store holds the real
87
+ * type and the comparison is a type mismatch, not a value mismatch — inconclusive, not `no`.
88
+ */
89
+ export declare function isStringifiedPrimitiveMismatch(got: unknown, want: unknown): boolean;
90
+ /**
91
+ * The inconclusive result for a stringified-primitive mismatch on a state `equals` check.
92
+ * Shared by both `evalStateNamed` and `evalState` so the reason and evidence shape stay in one
93
+ * place.
94
+ */
95
+ export declare function stringifiedPrimitiveResult(storeName: string, path: string, got: unknown, want: unknown, capDepth: (v: unknown, d: number) => unknown): {
96
+ pass: false;
97
+ failureReason: string;
98
+ inconclusive: string;
99
+ assertion: string;
100
+ evidence: Record<string, unknown>;
101
+ };
77
102
  /** One pattern key read out of a payload: its value, or where the walk stopped. */
78
103
  export interface FieldReading {
79
104
  found: boolean;