@reticlehq/engine 3.8.2 → 3.9.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.
@@ -13,7 +13,7 @@
13
13
  * arbitrary named checkpoints. A `snapshot("cart")` / `compare("cart")` pair is a different feature
14
14
  * and has no evidence behind it.
15
15
  */
16
- import { PredicateKind, ReticleCommand } from '@reticlehq/core';
16
+ import { MatchArg, PredicateKind, ReticleCommand } from '@reticlehq/core';
17
17
  import { textPredicateQuery } from '../question/predicate/predicate-element.js';
18
18
  /** The properties that mean nothing without a before-reading. Mirrors `RELATIVE` in property.ts. */
19
19
  const NEEDS_BASELINE = new Set([
@@ -74,7 +74,12 @@ async function readStateValue(session, predicate) {
74
74
  }
75
75
  async function readText(session, predicate) {
76
76
  const query = textPredicateQuery(predicate, session.sdkVersion);
77
- const match = await session.command(ReticleCommand.MATCH, { query });
77
+ // Read the way the property will read it after the action: a before-reading of the display form
78
+ // against an after-reading of the whole text would call every long text "changed".
79
+ const match = await session.command(ReticleCommand.MATCH, {
80
+ query,
81
+ [MatchArg.FULL_TEXT]: true,
82
+ });
78
83
  if (!match.ok)
79
84
  return undefined;
80
85
  const elements = (match.result ?? {}).elements;
@@ -17,6 +17,9 @@
17
17
  */
18
18
  export declare function targetsUnobservedChannel(url: string | undefined): boolean;
19
19
  export declare function targetsNativeDownload(url: string | undefined): boolean;
20
+ export declare function targetsMediaLoad(url: string | undefined): boolean;
21
+ /** `filter` is the net clause as applied — `describeNetFilter` of it. */
22
+ export declare function mediaLoadReason(filter: string): string;
20
23
  /** `filter` is the net clause as applied — `describeNetFilter` of it. */
21
24
  export declare function nativeDownloadReason(filter: string): string;
22
25
  /** The sentence both zero-match branches hand to `inconclusive`; `filter` as `nativeDownloadReason`. */
@@ -78,6 +78,30 @@ const NATIVE_DOWNLOAD_SUFFIXES = [
78
78
  '.7z',
79
79
  '.rar',
80
80
  ];
81
+ /**
82
+ * File suffixes a media element (`<video>`, `<audio>`, `<track>`) loads.
83
+ *
84
+ * Unlike DOCUMENT_ONLY_SUFFIXES this is not gated on a live resource-timing observer: Chromium does
85
+ * not report media element loads as `resource` entries, so a page that plays the file leaves no
86
+ * record however live the observer is. A miss over one of these says nothing about the file.
87
+ */
88
+ const MEDIA_LOAD_SUFFIXES = [
89
+ '.mp4',
90
+ '.m4v',
91
+ '.webm',
92
+ '.mov',
93
+ '.ogv',
94
+ '.m3u8',
95
+ '.mp3',
96
+ '.m4a',
97
+ '.ogg',
98
+ '.oga',
99
+ '.wav',
100
+ '.aac',
101
+ '.flac',
102
+ '.opus',
103
+ '.vtt',
104
+ ];
81
105
  /**
82
106
  * Does this filter target a class of request the observer cannot see?
83
107
  *
@@ -105,6 +129,20 @@ export function targetsNativeDownload(url) {
105
129
  return false;
106
130
  return NATIVE_DOWNLOAD_SUFFIXES.some((suffix) => filterPath(url).endsWith(suffix));
107
131
  }
132
+ export function targetsMediaLoad(url) {
133
+ if (undefined === url) {
134
+ return false;
135
+ }
136
+ return MEDIA_LOAD_SUFFIXES.some((suffix) => filterPath(url).endsWith(suffix));
137
+ }
138
+ /** `filter` is the net clause as applied — `describeNetFilter` of it. */
139
+ export function mediaLoadReason(filter) {
140
+ return (`no fetch or XHR matched ${filter}. A media element (<video>, <audio>, <track>) loads its ` +
141
+ `source itself: the load goes through neither fetch nor XMLHttpRequest, and the browser does ` +
142
+ `not report it as a resource timing entry, so media element loads are not observed and an ` +
143
+ `empty net window is not evidence the file failed to load. Assert something that proves ` +
144
+ `playback instead, for example an element check on the <video> or <audio>`);
145
+ }
108
146
  /** `filter` is the net clause as applied — `describeNetFilter` of it. */
109
147
  export function nativeDownloadReason(filter) {
110
148
  return (`no fetch or XHR matched ${filter}. A native download or document navigation ` +
@@ -8,11 +8,15 @@
8
8
  * could have read it. Neither is ever a pass, since a comparison with a side missing compares nothing.
9
9
  */
10
10
  import { CompareAs, EventType, NetBodySide, PredicateKind, REDACTED_VALUE, urlForMatch, } from '@reticlehq/core';
11
- import { parseJsonObject, readField, redactedOnPath, str, } from './predicate-eval-kit.js';
12
- import { evalElement, joinedText } from './predicate-element.js';
11
+ import { clipBody, parseJsonObject, readField, redactedOnPath, str, } from './predicate-eval-kit.js';
12
+ import { evalElement, wholeTextOf } from './predicate-element.js';
13
13
  import { evalState } from './predicate-state.js';
14
14
  import { skippedBodyRemedy } from './predicate-eval.js';
15
15
  import { REMEDY_BODY_CAPTURE, requestBodySkipRemedy } from './predicate-request-body.js';
16
+ /** What a verdict quotes of a reading: the slice when there is one, the value as it is otherwise. */
17
+ function quoted(reading) {
18
+ return reading.shown ?? reading.value;
19
+ }
16
20
  function unknown(reason) {
17
21
  return { result: { pass: false, failureReason: reason, inconclusive: reason } };
18
22
  }
@@ -42,10 +46,12 @@ function redacted(label) {
42
46
  * different secrets arrive as the same string and would compare equal.
43
47
  */
44
48
  function asScalar(value, label) {
45
- if (REDACTED_VALUE === value)
49
+ if (REDACTED_VALUE === value) {
46
50
  return redacted(label);
47
- if (isScalar(value))
51
+ }
52
+ if (isScalar(value)) {
48
53
  return { value, label };
54
+ }
49
55
  return unknown(`${label} is ${Array.isArray(value) ? 'an array' : 'an object'}, not a single value — point the path at one field inside it`);
50
56
  }
51
57
  function describeNetSource(source) {
@@ -80,8 +86,9 @@ function readNet(events, source) {
80
86
  ? unknown(`the ${label} was TRUNCATED before it was recorded, so the field could not be read`)
81
87
  : unknown(`the body is not a JSON object, so ${label} names no field — compare reads JSON fields`);
82
88
  }
83
- if (redactedOnPath(payload, source.path))
89
+ if (redactedOnPath(payload, source.path)) {
84
90
  return redacted(label);
91
+ }
85
92
  const field = readField(payload, source.path);
86
93
  if (!field.found) {
87
94
  if (truncated) {
@@ -104,8 +111,9 @@ function readSignal(events, source) {
104
111
  ? payload
105
112
  : undefined;
106
113
  // Signal payloads cross the same transport sanitizer as state, so a parent can be redacted too.
107
- if (record !== undefined && redactedOnPath(record, source.path))
114
+ if (record !== undefined && redactedOnPath(record, source.path)) {
108
115
  return redacted(label);
116
+ }
109
117
  const field = record === undefined ? { found: false, value: undefined } : readField(record, source.path);
110
118
  if (!field.found) {
111
119
  return missing(`${label} is missing; the payload was ${JSON.stringify(payload)}`, label);
@@ -119,17 +127,25 @@ async function readStore(session, source) {
119
127
  path: source.path,
120
128
  ...(source.store === undefined ? {} : { store: source.store }),
121
129
  });
122
- if (!read.pass)
130
+ if (!read.pass) {
123
131
  return { result: read };
132
+ }
124
133
  const value = read.evidence?.value;
125
134
  return asScalar(value, label);
126
135
  }
127
136
  async function readText(session, source, diagnose) {
128
137
  const label = `text of ${source.scope}`;
129
- const found = await evalElement(session, { scope: source.scope, self: true }, undefined, false, diagnose);
130
- if (!found.pass)
138
+ // Read in full: two texts that differ only past the display form's 80 characters would otherwise
139
+ // compare equal, and the equality would be a verdict on a string the page never showed.
140
+ const found = await evalElement(session, { scope: source.scope, self: true }, undefined, false, diagnose, true);
141
+ if (!found.pass) {
131
142
  return { result: found };
132
- return { value: joinedText(found.evidence), label };
143
+ }
144
+ const whole = wholeTextOf(found.evidence, source.scope, 'the comparison');
145
+ if ('result' in whole) {
146
+ return whole;
147
+ }
148
+ return { value: whole.text, label, shown: clipBody(whole.text) };
133
149
  }
134
150
  function readSide(session, events, source, diagnose) {
135
151
  switch (source.from) {
@@ -150,16 +166,19 @@ function readSide(session, events, source, diagnose) {
150
166
  */
151
167
  const NUMBER_TOKEN = /(?:-(?:[\p{Sc}]\s*)?|[\p{Sc}]\s*-?)?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?/gu;
152
168
  /** One number out of a reading, or why there is not exactly one. */
153
- function numberOf(value) {
154
- if ('number' === typeof value)
169
+ function numberOf(reading) {
170
+ const { value } = reading;
171
+ if ('number' === typeof value) {
155
172
  return Number.isFinite(value) ? { n: value } : { why: 'is not finite' };
156
- if ('string' !== typeof value)
173
+ }
174
+ if ('string' !== typeof value) {
157
175
  return { why: `is ${JSON.stringify(value)}, not a number` };
176
+ }
158
177
  const tokens = value.match(NUMBER_TOKEN) ?? [];
159
178
  const [only] = tokens;
160
179
  if (1 !== tokens.length || only === undefined) {
161
180
  return {
162
- why: `holds ${String(tokens.length)} numbers in ${JSON.stringify(value)}, so which one was meant is a guess — narrow the scope to one value`,
181
+ why: `holds ${String(tokens.length)} numbers in ${JSON.stringify(quoted(reading))}, so which one was meant is a guess — narrow the scope to one value`,
163
182
  };
164
183
  }
165
184
  const isNegative = only.includes('-');
@@ -180,12 +199,13 @@ function numberOf(value) {
180
199
  */
181
200
  const LAST_PLACE_NOISE = 2 * Number.EPSILON;
182
201
  function closeEnough(a, b, tolerance) {
183
- if (a === b)
202
+ if (a === b) {
184
203
  return true;
204
+ }
185
205
  return Math.abs(a - b) <= tolerance + LAST_PLACE_NOISE * Math.max(Math.abs(a), Math.abs(b));
186
206
  }
187
207
  function describe(reading) {
188
- return `${reading.label} is ${JSON.stringify(reading.value)}`;
208
+ return `${reading.label} is ${JSON.stringify(quoted(reading))}`;
189
209
  }
190
210
  export async function evalCompare(session, events, p, diagnose) {
191
211
  const [left, right] = await Promise.all([
@@ -199,19 +219,20 @@ export async function evalCompare(session, events, p, diagnose) {
199
219
  return results.find((r) => r.inconclusive !== undefined) ?? results[0] ?? { pass: false };
200
220
  }
201
221
  const evidence = {
202
- left: { source: left.label, value: left.value },
203
- right: { source: right.label, value: right.value },
222
+ left: { source: left.label, value: quoted(left) },
223
+ right: { source: right.label, value: quoted(right) },
204
224
  };
205
225
  if (CompareAs.NUMBER === p.as) {
206
- const a = numberOf(left.value);
207
- const b = numberOf(right.value);
226
+ const a = numberOf(left);
227
+ const b = numberOf(right);
208
228
  if ('why' in a || 'why' in b) {
209
229
  const why = 'why' in a ? `${left.label} ${a.why}` : `${right.label} ${'why' in b ? b.why : ''}`;
210
230
  return { pass: false, failureReason: why, inconclusive: why, evidence };
211
231
  }
212
232
  const tolerance = p.tolerance ?? 0;
213
- if (closeEnough(a.n, b.n, tolerance))
233
+ if (closeEnough(a.n, b.n, tolerance)) {
214
234
  return { pass: true, evidence };
235
+ }
215
236
  const band = 0 === tolerance ? '' : ` (tolerance ${String(tolerance)})`;
216
237
  return {
217
238
  pass: false,
@@ -222,17 +243,23 @@ export async function evalCompare(session, events, p, diagnose) {
222
243
  evidence,
223
244
  };
224
245
  }
225
- if (left.value === right.value)
246
+ if (left.value === right.value) {
226
247
  return { pass: true, evidence };
227
- const numeric = numberOf(left.value);
228
- const other = numberOf(right.value);
248
+ }
249
+ const numeric = numberOf(left);
250
+ const other = numberOf(right);
229
251
  const hint = 'n' in numeric && 'n' in other && closeEnough(numeric.n, other.n, 0)
230
252
  ? ' — they hold the same number in different forms; compare them with `as: "number"`'
231
253
  : '';
254
+ // Two long texts that differ only past what is quoted would read as equal in the message that says
255
+ // they are not, so say where the difference is.
256
+ const unquoted = quoted(left) === quoted(right)
257
+ ? ' — they agree on the part quoted here and differ further on'
258
+ : '';
232
259
  return {
233
260
  pass: false,
234
- failureReason: `${describe(left)}, but ${describe(right)}${hint}`,
235
- observed: `${JSON.stringify(left.value)} against ${JSON.stringify(right.value)}`,
261
+ failureReason: `${describe(left)}, but ${describe(right)}${hint}${unquoted}`,
262
+ observed: `${JSON.stringify(quoted(left))} against ${JSON.stringify(quoted(right))}`,
236
263
  expected: 'the two values to be equal',
237
264
  assertion: 'compare.value',
238
265
  evidence,
@@ -17,9 +17,24 @@ export declare const ARIA_HIDDEN_NOTE = "text is inside an aria-hidden subtree \
17
17
  * so the hint can say exactly what to use instead.
18
18
  */
19
19
  export declare const HTML_TAG_TO_ARIA_ROLE: Map<string, string>;
20
- export declare function evalElement(session: PredicateSession, query: ElementQuery, state: ElementState | undefined, absent: boolean, diagnose: boolean): Promise<EvalResult>;
20
+ export declare function evalElement(session: PredicateSession, query: ElementQuery, state: ElementState | undefined, absent: boolean, diagnose: boolean,
21
+ /** Describe the matches with their full text, for a caller that will JUDGE it (see `withTextProperty`). */
22
+ fullText?: boolean): Promise<EvalResult>;
21
23
  /** The text of every element a passing match described, joined — what a reader sees there. */
22
24
  export declare function joinedText(evidence: unknown): string;
25
+ /**
26
+ * The whole text of a passing match read in full (see `evalElement`'s `fullText`), or the result that
27
+ * says it was cut short.
28
+ *
29
+ * Whatever judges the text on a reading that stopped short could pass or fail on the part not read,
30
+ * so it is not judged: the same refusal a truncated state value gets. `undecided` names what was
31
+ * left undecided, so the caller's own question is the one the message answers.
32
+ */
33
+ export declare function wholeTextOf(evidence: unknown, subject: string, undecided: string): {
34
+ text: string;
35
+ } | {
36
+ result: EvalResult;
37
+ };
23
38
  export declare function withTextProperty(base: EvalResult, assertion: PropertyAssertion, subject: string, baseline?: Baseline): EvalResult;
24
39
  /**
25
40
  * The element query a text predicate is evaluated through — one builder for the verdict and its
@@ -6,8 +6,9 @@
6
6
  * back (`residualQueryChecks`), the absent/present asymmetry, and the near-miss diagnostics that only
7
7
  * ever enrich a failure. Nothing else in the predicate layer talks to `ReticleCommand.MATCH`.
8
8
  */
9
- import { QueryBy, ReticleCommand, ElementState, } from '@reticlehq/core';
9
+ import { MatchArg, QueryBy, ReticleCommand, TRANSPORT_LIMITS, ElementState, } from '@reticlehq/core';
10
10
  import { describeAltOnNonImage, describeUnusableElementQuery, residualQueryChecks, withAltProjected, satisfiesResiduals, describeResidual, } from './predicate-eval.js';
11
+ import { clipBody } from './predicate-eval-kit.js';
11
12
  import { describeTestidMiss } from './testid-near-miss.js';
12
13
  import { describeCaseMiss, describeSplitTextMiss } from './split-text-miss.js';
13
14
  import { satisfiesProperty } from './property.js';
@@ -52,12 +53,14 @@ export const HTML_TAG_TO_ARIA_ROLE = new Map([
52
53
  * Context-dependent tags state the condition so the hint is never wrong.
53
54
  */
54
55
  function describeUnreachableRole(role) {
55
- if (role === undefined)
56
+ if (role === undefined) {
56
57
  return undefined;
58
+ }
57
59
  const tag = role.toLowerCase();
58
60
  const ariaRole = HTML_TAG_TO_ARIA_ROLE.get(tag);
59
- if (ariaRole === undefined)
61
+ if (ariaRole === undefined) {
60
62
  return undefined;
63
+ }
61
64
  if ('section' === tag) {
62
65
  return (`'section' is not an ARIA role — ` +
63
66
  `a named <section> (with aria-label, aria-labelledby, or title) has role 'region'; ` +
@@ -86,8 +89,9 @@ function describeUnreachableRole(role) {
86
89
  * unexamined, not absent. Empty when nothing was cut, so an ordinary miss keeps the message it had.
87
90
  */
88
91
  function describePresentTestidsCut(shown, total) {
89
- if (total === undefined || total <= shown)
92
+ if (total === undefined || total <= shown) {
90
93
  return '';
94
+ }
91
95
  return ` (the present-testid list shows the first ${String(shown)} of ${String(total)} in document order — absence from it proves nothing)`;
92
96
  }
93
97
  /**
@@ -105,8 +109,9 @@ function describeAbsentMiss(match, state) {
105
109
  match.elements.length > 0 &&
106
110
  match.elements.length === match.count &&
107
111
  match.elements.every((element) => !element.visible);
108
- if (!allDescribedHidden)
112
+ if (!allDescribedHidden) {
109
113
  return found;
114
+ }
110
115
  const which = 1 === match.count ? 'it is' : 'every one is';
111
116
  return (`${found}, but ${which} hidden — \`absent\` means removed from the DOM; ` +
112
117
  `to assert it isn't shown, use \`state: "${ElementState.HIDDEN}"\``);
@@ -127,14 +132,31 @@ function describeUnreadable(why) {
127
132
  return (`the text is on the page, but a user cannot read it (${why}). ` +
128
133
  'Fix the colour or the opacity, then check again');
129
134
  }
130
- async function matchOnce(session, query, state, diagnose) {
135
+ /**
136
+ * Why a match is refused before the round-trip (#1990): the page DECLARED its commands and match is
137
+ * not one of them, so sending it could only end in a timeout that reads as a slow page.
138
+ */
139
+ function matchNotServedMessage(sdkVersion, declared) {
140
+ const sdk = sdkVersion === undefined ? 'does not serve' : `is ${sdkVersion} and does not serve`;
141
+ return (`this page's SDK ${sdk} 'match': it declared ${String(declared.length)} command(s) when it ` +
142
+ "connected and this is not one of them. Update the page's @reticlehq packages: " +
143
+ '`reticle update` in the app.');
144
+ }
145
+ async function matchOnce(session, query, state, diagnose, fullText = false) {
146
+ // A page that declared its commands and left match out can never answer (#1990): the session
147
+ // refuses the send, and that refusal used to be read as "zero matches". Refuse before the trip.
148
+ if (session.commands !== undefined && !session.commands.includes(ReticleCommand.MATCH)) {
149
+ throw new Error(matchNotServedMessage(session.sdkVersion, session.commands));
150
+ }
131
151
  const res = await session.command(ReticleCommand.MATCH, {
132
152
  query,
133
153
  state,
134
154
  ...(true === diagnose ? { diagnose: true } : {}),
155
+ ...(fullText ? { [MatchArg.FULL_TEXT]: true } : {}),
135
156
  });
136
- if (!res.ok)
157
+ if (!res.ok) {
137
158
  return { matched: false, count: 0, elements: [] };
159
+ }
138
160
  return (res.result ?? { matched: false, count: 0, elements: [] });
139
161
  }
140
162
  /**
@@ -165,13 +187,15 @@ function substantiveMatches(query, elements) {
165
187
  query.name === undefined &&
166
188
  query.text === undefined &&
167
189
  query.testid === undefined;
168
- if (!bareRole || !ANNOUNCEMENT_ROLES.has(query.role ?? ''))
190
+ if (!bareRole || !ANNOUNCEMENT_ROLES.has(query.role ?? '')) {
169
191
  return elements;
192
+ }
170
193
  // Nothing described, nothing to judge. `elements` is only the described PREFIX of a match — the
171
194
  // browser truncates it, and it can be empty while `count` is not. Calling that hollow would turn a
172
195
  // truncation into a verdict, so an unjudgeable set keeps the old answer.
173
- if (0 === elements.length)
196
+ if (0 === elements.length) {
174
197
  return elements;
198
+ }
175
199
  return elements.filter((e) => e.name.length > 0 || (e.text ?? '').trim().length > 0);
176
200
  }
177
201
  /**
@@ -192,24 +216,29 @@ function versionParts(version) {
192
216
  function sdkPredates(sdk, since) {
193
217
  const have = sdk === undefined ? undefined : versionParts(sdk);
194
218
  const need = versionParts(since);
195
- if (have === undefined || need === undefined)
219
+ if (have === undefined || need === undefined) {
196
220
  return false;
221
+ }
197
222
  for (let i = 0; i < 3; i += 1) {
198
- if (have[i] !== need[i])
223
+ if (have[i] !== need[i]) {
199
224
  return (have[i] ?? 0) < (need[i] ?? 0);
225
+ }
200
226
  }
201
227
  return false;
202
228
  }
203
229
  /** The state, when the page's SDK is older than the first release that answers it. */
204
230
  function stateTheSdkPredates(sdk, state) {
205
231
  const since = state === undefined ? undefined : ELEMENT_STATE_SINCE[state];
206
- if (sdk === undefined || state === undefined || since === undefined)
232
+ if (sdk === undefined || state === undefined || since === undefined) {
207
233
  return undefined;
234
+ }
208
235
  return sdkPredates(sdk, since) ? { sdk, state, since } : undefined;
209
236
  }
210
237
  /** The first SDK release whose element query accepts `matchCase`; an older page refuses the query. */
211
238
  const MATCH_CASE_SINCE = '3.7.0';
212
- export async function evalElement(session, query, state, absent, diagnose) {
239
+ export async function evalElement(session, query, state, absent, diagnose,
240
+ /** Describe the matches with their full text, for a caller that will JUDGE it (see `withTextProperty`). */
241
+ fullText = false) {
213
242
  const tooOld = stateTheSdkPredates(session.sdkVersion, state);
214
243
  if (tooOld !== undefined) {
215
244
  const reason = `the page's SDK is ${tooOld.sdk}, and the '${tooOld.state}' state needs ${tooOld.since} or ` +
@@ -232,8 +261,24 @@ export async function evalElement(session, query, state, absent, diagnose) {
232
261
  const reason = describeUnusableElementQuery(query, residual.unusable);
233
262
  return { pass: false, failureReason: reason, inconclusive: reason };
234
263
  }
235
- let match = await matchOnce(session, withAltProjected(query, residual.checks), state, diagnose);
264
+ let match = await matchOnce(session, withAltProjected(query, residual.checks), state, diagnose, fullText);
236
265
  const subject = JSON.stringify(query);
266
+ // Full text was asked for to JUDGE it, so a reading that is not the full text is not graded.
267
+ if (fullText && !absent && match.matched) {
268
+ // A page too old to know the argument ignores it and answers with the 80-character display form,
269
+ // which looks exactly like a short text. It cannot say so, which is why the page echoes the ask.
270
+ if (true !== match.fullText) {
271
+ const reason = `the page's SDK did not return the whole text of ${subject}, so a property of it was not ` +
272
+ `decided. Update the page's @reticlehq packages`;
273
+ return { pass: false, failureReason: reason, inconclusive: reason };
274
+ }
275
+ // `elements` is only the described prefix, and a text property is judged on all that matched.
276
+ if (match.count > match.elements.length) {
277
+ const reason = `${String(match.count)} elements matched ${subject} and only ${String(match.elements.length)} ` +
278
+ `were read in full, so a property of their text was not decided on all of it. Narrow the locator`;
279
+ return { pass: false, failureReason: reason, inconclusive: reason };
280
+ }
281
+ }
237
282
  // A residual narrows the SET; `count` is every match while `elements` is only the described prefix,
238
283
  // so a locator broad enough to be truncated cannot be narrowed honestly. Say so instead of guessing.
239
284
  if (residual.checks.length > 0 && match.count > match.elements.length) {
@@ -480,8 +525,9 @@ export async function evalElement(session, query, state, absent, diagnose) {
480
525
  */
481
526
  /** The text an element descriptor reported, or ''. Never `String(unknown)` — see `show` in property.ts. */
482
527
  function textOf(element) {
483
- if ('object' !== typeof element || null === element)
528
+ if ('object' !== typeof element || null === element) {
484
529
  return '';
530
+ }
485
531
  const value = element.text;
486
532
  return 'string' === typeof value ? value : '';
487
533
  }
@@ -490,11 +536,56 @@ export function joinedText(evidence) {
490
536
  const described = Array.isArray(evidence) ? evidence : [];
491
537
  return described.map(textOf).join(' ').trim();
492
538
  }
539
+ /**
540
+ * A match re-bounded to the text an agent is shown.
541
+ *
542
+ * The property was judged on the full text; the verdict that carries the match back is output,
543
+ * and judging more must not make it bigger.
544
+ */
545
+ function shownBounded(element) {
546
+ if ('object' !== typeof element || null === element) {
547
+ return element;
548
+ }
549
+ const max = TRANSPORT_LIMITS.MAX_DESCRIBED_TEXT;
550
+ const text = textOf(element);
551
+ return text.length > max ? { ...element, text: `${text.slice(0, max)}…` } : element;
552
+ }
553
+ /**
554
+ * Whether a described text was cut at the full-text bound. A cut text is that many characters and
555
+ * an ellipsis, so only a cut one is ever longer than the bound.
556
+ */
557
+ function wasCutAtFullBound(element) {
558
+ return textOf(element).length > TRANSPORT_LIMITS.MAX_FULL_TEXT;
559
+ }
560
+ /**
561
+ * The whole text of a passing match read in full (see `evalElement`'s `fullText`), or the result that
562
+ * says it was cut short.
563
+ *
564
+ * Whatever judges the text on a reading that stopped short could pass or fail on the part not read,
565
+ * so it is not judged: the same refusal a truncated state value gets. `undecided` names what was
566
+ * left undecided, so the caller's own question is the one the message answers.
567
+ */
568
+ export function wholeTextOf(evidence, subject, undecided) {
569
+ const matched = Array.isArray(evidence) ? evidence : [];
570
+ if (matched.some(wasCutAtFullBound)) {
571
+ const reason = `the text of ${subject} is longer than the ${String(TRANSPORT_LIMITS.MAX_FULL_TEXT)} characters ` +
572
+ `Reticle reads to judge it, so ${undecided} was not decided on all of it. ` +
573
+ `Scope the predicate to a smaller element`;
574
+ return { result: { pass: false, failureReason: reason, inconclusive: reason } };
575
+ }
576
+ return { text: joinedText(matched) };
577
+ }
493
578
  export function withTextProperty(base, assertion, subject, baseline) {
494
- if (!base.pass)
579
+ if (!base.pass) {
495
580
  return base;
496
- const described = Array.isArray(base.evidence) ? base.evidence : [];
497
- const text = joinedText(described);
581
+ }
582
+ const matched = Array.isArray(base.evidence) ? base.evidence : [];
583
+ const whole = wholeTextOf(matched, subject, assertion.property);
584
+ if ('result' in whole) {
585
+ return whole.result;
586
+ }
587
+ const { text } = whole;
588
+ const described = matched.map(shownBounded);
498
589
  const result = satisfiesProperty(text, assertion, baseline);
499
590
  // Nothing was compared — a relative property with no before-reading. See the twin in `evalState`.
500
591
  if (true === result.unevaluated) {
@@ -506,7 +597,7 @@ export function withTextProperty(base, assertion, subject, baseline) {
506
597
  return {
507
598
  pass: false,
508
599
  failureReason: `text of ${subject} ${result.because}`,
509
- observed: `text of ${subject} = ${JSON.stringify(text)}`,
600
+ observed: `text of ${subject} = ${JSON.stringify(clipBody(text))}`,
510
601
  expected: `text of ${subject} to satisfy ${assertion.property}`,
511
602
  assertion: `text.${assertion.property}`,
512
603
  evidence: described,
@@ -521,8 +612,9 @@ const MAX_BY_NAME = 3;
521
612
  async function nearestByName(session, name, state) {
522
613
  for (const query of [{ label: name }, { placeholder: name }]) {
523
614
  const found = await matchOnce(session, query, state);
524
- if (found.matched)
615
+ if (found.matched) {
525
616
  return found.elements.slice(0, MAX_BY_NAME);
617
+ }
526
618
  }
527
619
  return [];
528
620
  }
@@ -8,7 +8,7 @@ export { evalConsole } from './predicate-console.js';
8
8
  import { clipBody, dataMatches, describeBodyFieldMiss, describeFieldMiss, describeNetFilter, matchJsonBody, num, redactedOnPath, str, } from './predicate-eval-kit.js';
9
9
  import { keyFragmentOnly } from './body-key-fragment.js';
10
10
  import { evalExactCount } from '../../exact-count.js';
11
- import { PRE_ATTACH_CAVEAT, nativeDownloadReason, targetsNativeDownload, targetsUnobservedChannel, unobservedChannelReason, } from './net-blind-spots.js';
11
+ import { PRE_ATTACH_CAVEAT, mediaLoadReason, nativeDownloadReason, targetsMediaLoad, targetsNativeDownload, targetsUnobservedChannel, unobservedChannelReason, } from './net-blind-spots.js';
12
12
  export { clipBody, dataMatches, describeNetFilter, matchValue, str, } from './predicate-eval-kit.js';
13
13
  /** The oracle a net body clause reports, so an agent can branch on which one decided. */
14
14
  const NetBodyAssertion = {
@@ -81,17 +81,19 @@ function describeSignalFilter(p) {
81
81
  return JSON.stringify(filter);
82
82
  }
83
83
  function nativeDownloadMiss(events, p) {
84
- if (!targetsNativeDownload(p.urlContains)) {
84
+ const media = targetsMediaLoad(p.urlContains);
85
+ if (!media && !targetsNativeDownload(p.urlContains)) {
85
86
  return undefined;
86
87
  }
87
- const reason = nativeDownloadReason(describeNetFilter(p));
88
+ const filter = describeNetFilter(p);
89
+ const reason = media ? mediaLoadReason(filter) : nativeDownloadReason(filter);
88
90
  return {
89
91
  pass: false,
90
92
  failureReason: reason,
91
93
  inconclusive: reason,
92
94
  observed: observedNetCalls(events, p.urlContains),
93
- expected: `a fetch or XHR matching ${describeNetFilter(p)}`,
94
- assertion: 'net.native-download',
95
+ expected: `a fetch or XHR matching ${filter}`,
96
+ assertion: media ? 'net.media-load' : 'net.native-download',
95
97
  };
96
98
  }
97
99
  /**
@@ -44,6 +44,122 @@ const GENERIC_EXAMPLE = '{ kind: "text", contains: "Saved" }';
44
44
  function exampleFor(kind) {
45
45
  return EXAMPLES[kind] ?? GENERIC_EXAMPLE;
46
46
  }
47
+ /** The one example a refusal ends with: the agent's own predicate corrected, else the kind's sample. */
48
+ function exampleSentence(kind, corrected) {
49
+ return corrected === undefined
50
+ ? `A valid ${kind} predicate looks like: ${exampleFor(kind)}`
51
+ : `The corrected ${kind} predicate from your call: ${corrected}`;
52
+ }
53
+ /**
54
+ * The field that holds the value a kind checks. An unknown field's string value goes here when the
55
+ * agent left it empty. `element` holds it in `query.text`. Kinds not listed get no correction.
56
+ */
57
+ const PRIMARY_FIELD = {
58
+ [PredicateKind.TEXT]: 'contains',
59
+ [PredicateKind.ROUTE]: 'pathname',
60
+ [PredicateKind.NET]: 'urlContains',
61
+ [PredicateKind.SIGNAL]: 'name',
62
+ [PredicateKind.ANIMATION]: 'name',
63
+ [PredicateKind.CONSOLE]: 'contains',
64
+ [PredicateKind.STATE]: 'path',
65
+ };
66
+ /** `"200"` → 200 and `"true"` → true, the two type mistakes with one reading. */
67
+ const NUMERIC = /^-?\d+(\.\d+)?$/;
68
+ const BOOLEANS = { true: true, false: false };
69
+ /** A string value as the number or boolean the schema wanted, or undefined when it is not one. */
70
+ function readTyped(value, expected) {
71
+ if ('string' !== typeof value) {
72
+ return undefined;
73
+ }
74
+ if ('number' === expected && NUMERIC.test(value)) {
75
+ return Number(value);
76
+ }
77
+ if ('boolean' === expected) {
78
+ return BOOLEANS[value];
79
+ }
80
+ return undefined;
81
+ }
82
+ /** The predicate with the kind's check value set to `text`, or undefined for a kind with none. */
83
+ function withPrimary(kind, candidate, text) {
84
+ if (PredicateKind.ELEMENT === kind) {
85
+ return candidate['query'] === undefined ? { ...candidate, query: { text } } : undefined;
86
+ }
87
+ const field = PRIMARY_FIELD[kind];
88
+ if (field === undefined || candidate[field] !== undefined) {
89
+ return undefined;
90
+ }
91
+ return { ...candidate, [field]: text };
92
+ }
93
+ /**
94
+ * One corrected predicate built from the agent's own values, as JSON, or undefined.
95
+ *
96
+ * Unknown fields are removed, and the first one that holds a string becomes the kind's check value.
97
+ * A number or boolean written as a string is read as one. Call arguments (`ref`, `action`) are never
98
+ * used as the check value. When any value the agent wrote would be lost, there is no correction:
99
+ * a predicate that checks less than the agent asked for is not a correction.
100
+ */
101
+ function correctedFromCall(input, issues) {
102
+ if ('object' !== typeof input || null === input || Array.isArray(input)) {
103
+ return undefined;
104
+ }
105
+ const kind = kindAsWritten(input);
106
+ if ('string' !== typeof kind || 0 === predicateFieldsFor(kind).length) {
107
+ return undefined;
108
+ }
109
+ // On `element` a `ref` is the target. Removed, the check would find any element, not that one.
110
+ if (PredicateKind.ELEMENT === kind && input['ref'] !== undefined) {
111
+ return undefined;
112
+ }
113
+ let candidate = { ...input };
114
+ delete candidate[KIND_ALIAS];
115
+ candidate['kind'] = kind;
116
+ const donors = [];
117
+ for (const issue of issues) {
118
+ const field = issue.path[0];
119
+ if (z.ZodIssueCode.unrecognized_keys === issue.code && 0 === issue.path.length) {
120
+ for (const key of issue.keys) {
121
+ const value = candidate[key];
122
+ delete candidate[key];
123
+ if (CALL_LEVEL_FIELDS.includes(key)) {
124
+ continue;
125
+ }
126
+ if ('string' !== typeof value) {
127
+ return undefined;
128
+ }
129
+ donors.push(value);
130
+ }
131
+ continue;
132
+ }
133
+ // A refinement on the whole predicate, or a missing field: the parse at the end decides.
134
+ if (0 === issue.path.length || ('string' === typeof field && candidate[field] === undefined)) {
135
+ continue;
136
+ }
137
+ if (1 !== issue.path.length || 'string' !== typeof field) {
138
+ return undefined;
139
+ }
140
+ const typed = readTyped(candidate[field], 'expected' in issue ? issue.expected : undefined);
141
+ if (typed === undefined) {
142
+ return undefined;
143
+ }
144
+ candidate[field] = typed;
145
+ }
146
+ for (const field of CALL_LEVEL_FIELDS) {
147
+ delete candidate[field];
148
+ }
149
+ if (1 < donors.length) {
150
+ return undefined;
151
+ }
152
+ const [donor] = donors;
153
+ if (donor !== undefined) {
154
+ const filled = withPrimary(kind, candidate, donor);
155
+ if (filled === undefined) {
156
+ return undefined;
157
+ }
158
+ candidate = filled;
159
+ }
160
+ const parsed = PredicateSchema.safeParse(candidate);
161
+ return parsed.success ? JSON.stringify(parsed.data) : undefined;
162
+ }
47
163
  /** `path: ["net","urlContains"]` → `net.urlContains`; an empty path means the object itself. */
48
164
  function pathOf(issue) {
49
165
  return 0 === issue.path.length ? 'the predicate' : issue.path.map(String).join('.');
@@ -110,6 +226,7 @@ function onlyChildBlamed(input, issues) {
110
226
  const value = undefined === index ? container : container?.[Number(index)];
111
227
  return undefined === value ? undefined : { path: head, value };
112
228
  }
229
+ const NOTHING_RAN = 'Nothing ran — the predicate was not evaluated, so no verdict was produced.';
113
230
  export function parsePredicate(input) {
114
231
  const unfilled = placeholderValue(input);
115
232
  if (unfilled !== undefined) {
@@ -132,15 +249,20 @@ export function parsePredicate(input) {
132
249
  throw new Error(`${child.path}: ${error.message}`);
133
250
  }
134
251
  }
252
+ // A refused bare string carries its own readings, so nothing about kinds is added to it.
253
+ if ('string' === typeof input) {
254
+ const said = parsed.error.issues.map((issue) => issue.message).join('; ');
255
+ throw new Error(`that predicate did not parse: ${said}. ${NOTHING_RAN}`);
256
+ }
135
257
  const asWritten = kindAsWritten(input);
136
258
  const kind = 'string' === typeof asWritten ? asWritten : 'unknown';
137
259
  // Bounded on purpose: a union rejection can produce one issue per member, and pasting all of them
138
260
  // back is how the zod array became unreadable in the first place.
139
261
  const issues = parsed.error.issues.slice(0, 3).map(describeIssue).join('; ');
140
- throw new Error(`that predicate did not parse (kind "${kind}"): ${issues}. Nothing ran — the predicate was ` +
141
- `not evaluated, so no verdict was produced. ${accepted(kind, parsed.error.issues)}` +
262
+ throw new Error(`that predicate did not parse (kind "${kind}"): ${issues}. ${NOTHING_RAN} ` +
263
+ `${accepted(kind, parsed.error.issues)}` +
142
264
  `${misplacedCallFields(input)} ` +
143
- `A valid ${kind} predicate looks like: ${exampleFor(kind)}`);
265
+ exampleSentence(kind, correctedFromCall(input, parsed.error.issues)));
144
266
  }
145
267
  /**
146
268
  * Arguments of the CALL that agents write inside the predicate instead.
@@ -310,5 +432,11 @@ function accepted(kind, issues) {
310
432
  .join('');
311
433
  return `${kind} accepts: ${fields.join(', ')}.${nested}`;
312
434
  }
313
- return `"${kind}" is not a predicate kind — use one of: ${Object.values(PredicateKind).join(', ')}.`;
435
+ const kinds = Object.values(PredicateKind);
436
+ // `absent` is listed beside the kinds in the grammar, but it is a field. Say where it goes.
437
+ const takenBy = kinds.filter((each) => predicateFieldsFor(each).includes(kind));
438
+ const asField = 0 === takenBy.length
439
+ ? ''
440
+ : ` "${kind}" is a field of ${takenBy.join(', ')}: { kind: "${takenBy[0] ?? ''}", ..., ${kind}: … }.`;
441
+ return `"${kind}" is not a predicate kind — use one of: ${kinds.join(', ')}.${asField}`;
314
442
  }
@@ -48,45 +48,55 @@ function usedQueryFields(query) {
48
48
  // returns before `findBySource` is reached, so the predicate could pass for an element other than
49
49
  // the one the caller's source location identified. Unclaimed, it falls through to the residual
50
50
  // walk and is refused — exactly as `component` already is in the same position.
51
- if (query.scope !== undefined)
51
+ if (query.scope !== undefined) {
52
52
  used.add('scope');
53
- if (query.attrs !== undefined)
53
+ }
54
+ if (query.attrs !== undefined) {
54
55
  used.add('attrs');
55
- if (query.self !== undefined)
56
+ }
57
+ if (query.self !== undefined) {
56
58
  used.add('self');
59
+ }
57
60
  // A modifier of the text rule, not a locator: the browser honours it wherever it reads `text`, and
58
61
  // the residual text check below is already case-exact.
59
- if (query.matchCase !== undefined)
62
+ if (query.matchCase !== undefined) {
60
63
  used.add('matchCase');
64
+ }
61
65
  // The browser's `self` branch checks subtree text when supplied, but skips every other locator.
62
66
  // Mark only text as consumed so role/name/etc. remain residual checks on the returned descriptor.
63
- if (true === query.self)
67
+ if (true === query.self) {
64
68
  return query.text === undefined ? used : used.add('text');
69
+ }
65
70
  if (query.by !== undefined && query.value !== undefined) {
66
71
  used.add('by').add('value');
67
- if (QueryBy.ROLE === query.by)
72
+ if (QueryBy.ROLE === query.by) {
68
73
  used.add('name');
74
+ }
69
75
  // `by: "component"` resolves through `findByComponent`, which tries the source stamp first and
70
76
  // falls back to the component name — so a `source` written here IS consumed.
71
77
  if (QueryBy.COMPONENT === query.by) {
72
78
  used.add('component');
73
- if (query.source !== undefined)
79
+ if (query.source !== undefined) {
74
80
  used.add('source');
81
+ }
75
82
  }
76
83
  return used;
77
84
  }
78
85
  // The auto-anchor branch, reached only without `by`+`value`: `source` (precise) then `component`.
79
86
  if (query.component !== undefined || query.source !== undefined) {
80
87
  used.add('component');
81
- if (query.source !== undefined)
88
+ if (query.source !== undefined) {
82
89
  used.add('source');
90
+ }
83
91
  return used;
84
92
  }
85
- if (query.role !== undefined)
93
+ if (query.role !== undefined) {
86
94
  return used.add('role').add('name');
95
+ }
87
96
  for (const field of ['text', 'label', 'placeholder', 'testid', 'alt']) {
88
- if (query[field] !== undefined)
97
+ if (query[field] !== undefined) {
89
98
  return used.add(field);
99
+ }
90
100
  }
91
101
  return used;
92
102
  }
@@ -132,16 +142,29 @@ function isImage(element) {
132
142
  * keep matching it as well, so existing flows and recorded steps using `textbox` continue to match.
133
143
  */
134
144
  function matchesRole(actual, queried) {
135
- if (actual === queried)
145
+ if (actual === queried) {
136
146
  return true;
137
- if ('textbox' === queried && 'searchbox' === actual)
147
+ }
148
+ if ('textbox' === queried && 'searchbox' === actual) {
138
149
  return true;
150
+ }
139
151
  return false;
140
152
  }
153
+ /**
154
+ * The one name rule, on this side of the wire (#1839). The browser compares a name it CAN match
155
+ * through `exactVisibleText` - trim, collapse inner whitespace, compare in NFC - so a name the
156
+ * locator dropped and the engine enforces back here must answer the same question the same way,
157
+ * or a check flips its answer with the locator that carried it. Kept in step with
158
+ * `adapters/realm/browser/src/dom/text-match.ts` by hand: the engine cannot import the browser
159
+ * adapter, and moving the rule into core would move the wire contract for two lines.
160
+ */
161
+ function normaliseName(value) {
162
+ return value.replace(/\s+/g, ' ').trim().normalize('NFC');
163
+ }
141
164
  const RESIDUAL_CHECKS = {
142
165
  value: (element, want) => (element.value ?? '').trim() === want.trim(),
143
166
  role: (element, want) => matchesRole(element.role, want),
144
- name: (element, want) => element.name.trim() === want.trim(),
167
+ name: (element, want) => normaliseName(element.name) === normaliseName(want),
145
168
  text: (element, want) => (element.text ?? element.name).includes(want),
146
169
  [ALT_FIELD]: (element, want) => {
147
170
  const alt = element.attrs?.[ALT_FIELD];
@@ -151,8 +174,9 @@ const RESIDUAL_CHECKS = {
151
174
  /** The query to send, asking the browser to project `alt` when this side has to check it. */
152
175
  export function withAltProjected(query, checks) {
153
176
  const attrs = query.attrs ?? [];
154
- if (!checks.some(([field]) => ALT_FIELD === field) || attrs.includes(ALT_FIELD))
177
+ if (!checks.some(([field]) => ALT_FIELD === field) || attrs.includes(ALT_FIELD)) {
155
178
  return query;
179
+ }
156
180
  return { ...query, attrs: [...attrs, ALT_FIELD] };
157
181
  }
158
182
  /**
@@ -165,8 +189,9 @@ export function withAltProjected(query, checks) {
165
189
  */
166
190
  export function describeAltOnNonImage(checks, elements) {
167
191
  const wantsAlt = checks.some(([field]) => ALT_FIELD === field);
168
- if (!wantsAlt || 0 === elements.length || elements.some(isImage))
192
+ if (!wantsAlt || 0 === elements.length || elements.some(isImage)) {
169
193
  return undefined;
194
+ }
170
195
  const roles = [...new Set(elements.map((element) => element.role))].join(', ');
171
196
  return `${ALT_IMAGE_ONLY}, and the element matched is ${roles}, not ${IMAGE_ROLE}. ${ALT_USE_NAME}`;
172
197
  }
@@ -187,12 +212,15 @@ export function residualQueryChecks(query) {
187
212
  // question. Reading them off the query also means the set cannot drift from `ElementQuerySchema`.
188
213
  for (const field of Object.keys(query)) {
189
214
  const want = query[field];
190
- if (want === undefined || used.has(field))
215
+ if (want === undefined || used.has(field)) {
191
216
  continue;
192
- if ('string' === typeof want && RESIDUAL_CHECKS[field] !== undefined)
217
+ }
218
+ if ('string' === typeof want && RESIDUAL_CHECKS[field] !== undefined) {
193
219
  checks.push([field, want]);
194
- else
220
+ }
221
+ else {
195
222
  unusable.push(field);
223
+ }
196
224
  }
197
225
  return { checks, unusable };
198
226
  }
@@ -214,15 +242,22 @@ export function satisfiesResiduals(element, checks) {
214
242
  }
215
243
  /** How the element's own reading of a dropped field should be REPORTED back on a failure. */
216
244
  export function describeResidual(element, field) {
217
- const reading = 'value' === field
218
- ? (element.value ?? '')
219
- : 'text' === field
220
- ? (element.text ?? element.name)
221
- : 'role' === field
222
- ? element.role
223
- : ALT_FIELD === field
224
- ? (element.attrs?.[ALT_FIELD] ?? NO_ALT_ATTRIBUTE)
225
- : element.name;
245
+ let reading;
246
+ if ('value' === field) {
247
+ reading = element.value ?? '';
248
+ }
249
+ else if ('text' === field) {
250
+ reading = element.text ?? element.name;
251
+ }
252
+ else if ('role' === field) {
253
+ reading = element.role;
254
+ }
255
+ else if (ALT_FIELD === field) {
256
+ reading = element.attrs?.[ALT_FIELD] ?? NO_ALT_ATTRIBUTE;
257
+ }
258
+ else {
259
+ reading = element.name;
260
+ }
226
261
  return `${element.role} "${element.name}" ${field}=${JSON.stringify(reading)}`;
227
262
  }
228
263
  /**
@@ -234,8 +269,9 @@ export function describeResidual(element, field) {
234
269
  */
235
270
  export function predicateFieldsFor(kind) {
236
271
  const shape = shapeForKind(kind);
237
- if (null === shape)
272
+ if (null === shape) {
238
273
  return [];
274
+ }
239
275
  return Object.keys(shape).filter((field) => 'kind' !== field);
240
276
  }
241
277
  /**
@@ -301,8 +337,9 @@ export function predicateGrammar() {
301
337
  * none of these paths; that is exactly why they are worth a case each.
302
338
  */
303
339
  export function nestedKeysOf(schema) {
304
- if (undefined === schema)
340
+ if (undefined === schema) {
305
341
  return [];
342
+ }
306
343
  const inner = unwrapSchema(schema);
307
344
  // `instanceof z.ZodObject` narrows to ZodObject<any>, whose `.shape` is `any`. Name the shape
308
345
  // type so the keys are read off something typed rather than laundering an `any` through
@@ -313,8 +350,9 @@ export function nestedKeysOf(schema) {
313
350
  const options = inner.options;
314
351
  return [...new Set(options.flatMap((option) => nestedKeysOf(option)))];
315
352
  }
316
- if (!(inner instanceof z.ZodObject))
353
+ if (!(inner instanceof z.ZodObject)) {
317
354
  return [];
355
+ }
318
356
  return Object.keys(inner.shape);
319
357
  }
320
358
  /** Peel optional/nullable/default/pipe wrappers off a field to reach the schema underneath. */
@@ -348,15 +386,18 @@ function unwrapSchema(schema) {
348
386
  */
349
387
  export function predicateNestedFieldsFor(kind) {
350
388
  const shape = shapeForKind(kind);
351
- if (null === shape)
389
+ if (null === shape) {
352
390
  return {};
391
+ }
353
392
  const nested = {};
354
393
  for (const [field, schema] of Object.entries(shape)) {
355
- if ('kind' === field)
394
+ if ('kind' === field) {
356
395
  continue;
396
+ }
357
397
  const keys = nestedKeysOf(schema);
358
- if (0 < keys.length)
398
+ if (0 < keys.length) {
359
399
  nested[field] = keys;
400
+ }
360
401
  }
361
402
  return nested;
362
403
  }
@@ -87,6 +87,11 @@ export interface PredicateSession {
87
87
  * Optional: a fake that omits it gets its callback back unchanged.
88
88
  */
89
89
  keepCallerContext?: KeepCallerContextFn;
90
+ /**
91
+ * The commands the page DECLARED it can serve, from its hello. Undefined means the SDK is too old
92
+ * to declare anything, so silence is unknown — read to refuse an unserved command (#1990).
93
+ */
94
+ commands?: readonly string[] | undefined;
90
95
  }
91
96
  /**
92
97
  * The least time a page read is given, even at the very end of a budget: the final read at the
@@ -185,13 +185,47 @@ function clearStarvedWhenSiblingsSaw(predicates, results) {
185
185
  });
186
186
  if (!rendered)
187
187
  return results;
188
- return results.map((r) => {
189
- if (THROTTLED_STARVED_NOTE !== r.inconclusive)
190
- return r;
191
- const { inconclusive: _dropped, ...rest } = r;
192
- return rest;
188
+ return results.map((r, i) => {
189
+ const p = predicates[i];
190
+ return p === undefined ? r : clearStarved(p, r);
193
191
  });
194
192
  }
193
+ /**
194
+ * One arm without the starved-tab note.
195
+ *
196
+ * A `not` that was unreadable kept its child's result as evidence and never applied the negation.
197
+ * Dropping only the note left it at `pass: false`, which is the child's answer, not the negated
198
+ * one: a `not` of an absent element failed (reported on 3.8.2). So a `not` clears its child, then
199
+ * negates it again. Nested `not` recurses.
200
+ */
201
+ function clearStarved(predicate, result) {
202
+ if (THROTTLED_STARVED_NOTE !== result.inconclusive)
203
+ return result;
204
+ const child = result.evidence;
205
+ if (PredicateKind.NOT === predicate.kind && isEvalResult(child)) {
206
+ const inner = clearStarved(predicate.predicate, child);
207
+ return inner.inconclusive === undefined ? negate(predicate.predicate, inner) : result;
208
+ }
209
+ const { inconclusive: _dropped, ...rest } = result;
210
+ return rest;
211
+ }
212
+ /** A `not` keeps its child's result as its evidence. */
213
+ function isEvalResult(value) {
214
+ return ('object' === typeof value && null !== value && 'boolean' === typeof Reflect.get(value, 'pass'));
215
+ }
216
+ /**
217
+ * The `not` of a readable result.
218
+ *
219
+ * A green negation used to return a bare `{ pass: true }`, so the payload fell back to whatever
220
+ * the caller had — every element matching the OUTER locator. Three clauses negating three
221
+ * different names then produced byte-identical responses. The evidence is the whole answer here:
222
+ * what was looked for, and that it was not there.
223
+ */
224
+ function negate(negated, inner) {
225
+ return inner.pass
226
+ ? { pass: false, failureReason: 'negated predicate unexpectedly held', evidence: inner }
227
+ : { pass: true, evidence: { negated, held: false, saw: inner } };
228
+ }
195
229
  /**
196
230
  * Does this predicate FAIL by having seen something, rather than by not having seen it?
197
231
  *
@@ -282,7 +316,10 @@ diagnose = true, baselines) {
282
316
  // `scope` passes straight through: the text predicate has always been an element query with
283
317
  // only `text` filled in, so scoping it needs the field, not a second code path.
284
318
  const query = textPredicateQuery(predicate, session.sdkVersion);
285
- const found = await evalElement(session, query, true === predicate.visible ? ElementState.VISIBLE : undefined, predicate.absent ?? false, diagnose);
319
+ const found = await evalElement(session, query, true === predicate.visible ? ElementState.VISIBLE : undefined, predicate.absent ?? false, diagnose,
320
+ // A property is judged on the whole text. An absence check judges nothing, and a failed
321
+ // absence returns the matches as evidence, which would otherwise carry the full text out.
322
+ undefined !== predicate.satisfies && !(predicate.absent ?? false));
286
323
  if (undefined === predicate.satisfies)
287
324
  return found;
288
325
  return withTextProperty(found, predicate.satisfies, JSON.stringify(query), baselines?.get(predicate));
@@ -383,14 +420,7 @@ diagnose = true, baselines) {
383
420
  // You cannot negate an answer nobody had.
384
421
  if (inner.inconclusive !== undefined)
385
422
  return unreadableComposite(inner, inner);
386
- // A green negation used to return a bare `{ pass: true }`, so the payload fell back to
387
- // whatever the caller had — every element matching the OUTER locator. Three clauses negating
388
- // three different names then produced byte-identical responses, which reads as a checker that
389
- // dropped the name rather than one that correctly found all three absent. The evidence is the
390
- // whole answer here: what was looked for, and that it was not there.
391
- return inner.pass
392
- ? { pass: false, failureReason: 'negated predicate unexpectedly held', evidence: inner }
393
- : { pass: true, evidence: { negated: predicate.predicate, held: false, saw: inner } };
423
+ return negate(predicate.predicate, inner);
394
424
  }
395
425
  default:
396
426
  return { pass: false, failureReason: 'unknown predicate' };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reticlehq/engine",
3
- "version": "3.8.2",
3
+ "version": "3.9.0",
4
4
  "description": "The rules that decide a verdict: read what happened in a running app and say whether the declared consequence held. No browser, no daemon, no command line - an implementation of the OpenVerification specification you can use on its own.",
5
5
  "keywords": [
6
6
  "verification",
@@ -57,8 +57,8 @@
57
57
  },
58
58
  "dependencies": {
59
59
  "zod": "^4.6.6",
60
- "open-verification": "1.1.0",
61
- "@reticlehq/core": "3.8.2"
60
+ "@reticlehq/core": "3.9.0",
61
+ "open-verification": "1.1.0"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "tsc -b && node ../scripts/alias-dist.mjs",