@reticlehq/engine 3.8.2 → 3.10.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 (46) hide show
  1. package/dist/disagreement/body-failures.js +16 -2
  2. package/dist/disagreement/contradiction-evidence.d.ts +119 -0
  3. package/dist/disagreement/contradiction-evidence.js +360 -48
  4. package/dist/disagreement/contradiction-types.d.ts +25 -0
  5. package/dist/disagreement/contradictions.d.ts +17 -1
  6. package/dist/disagreement/contradictions.js +146 -78
  7. package/dist/disagreement/echo-mismatch.js +205 -32
  8. package/dist/disagreement/stale-response.d.ts +10 -1
  9. package/dist/disagreement/stale-response.js +122 -47
  10. package/dist/evidence/already-true.d.ts +1 -1
  11. package/dist/evidence/already-true.js +13 -7
  12. package/dist/evidence/baseline.d.ts +1 -0
  13. package/dist/evidence/baseline.js +28 -12
  14. package/dist/evidence/blind-spots.d.ts +20 -3
  15. package/dist/evidence/blind-spots.js +127 -21
  16. package/dist/evidence/step-effect.d.ts +5 -0
  17. package/dist/evidence/step-effect.js +5 -2
  18. package/dist/evidence/verified.d.ts +23 -0
  19. package/dist/evidence/verified.js +53 -2
  20. package/dist/question/declared.d.ts +27 -0
  21. package/dist/question/declared.js +64 -13
  22. package/dist/question/predicate/net-blind-spots.d.ts +40 -1
  23. package/dist/question/predicate/net-blind-spots.js +110 -1
  24. package/dist/question/predicate/predicate-animation.d.ts +52 -0
  25. package/dist/question/predicate/predicate-animation.js +258 -0
  26. package/dist/question/predicate/predicate-compare.js +53 -26
  27. package/dist/question/predicate/predicate-element.d.ts +20 -2
  28. package/dist/question/predicate/predicate-element.js +207 -45
  29. package/dist/question/predicate/predicate-eval-kit.d.ts +2 -0
  30. package/dist/question/predicate/predicate-eval-kit.js +19 -0
  31. package/dist/question/predicate/predicate-eval.d.ts +1 -4
  32. package/dist/question/predicate/predicate-eval.js +41 -47
  33. package/dist/question/predicate/predicate-parse.js +132 -4
  34. package/dist/question/predicate/predicate-route.js +81 -27
  35. package/dist/question/predicate/predicate-schema.js +84 -34
  36. package/dist/question/predicate/predicate-session.d.ts +5 -0
  37. package/dist/question/predicate/predicate.js +119 -50
  38. package/dist/question/predicate/truncated-body-advice.d.ts +5 -0
  39. package/dist/question/predicate/truncated-body-advice.js +25 -0
  40. package/dist/state-bookkeeping.d.ts +24 -0
  41. package/dist/state-bookkeeping.js +31 -0
  42. package/dist/window/event-filters.d.ts +64 -0
  43. package/dist/window/event-filters.js +149 -20
  44. package/dist/window/network-detail-merge.d.ts +6 -0
  45. package/dist/window/network-detail-merge.js +43 -2
  46. package/package.json +3 -3
@@ -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, sdkPredates } 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,10 +89,25 @@ 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
  }
97
+ /**
98
+ * How many elements a CSS scope matched, when it matched more than one, or nothing. The search covers
99
+ * all of them, and without the count a miss across a list of items read like a miss in one (#1663).
100
+ */
101
+ function describeScopeMatches(scopeMatches) {
102
+ if (scopeMatches === undefined || scopeMatches <= 1) {
103
+ return '';
104
+ }
105
+ return ` (searched all ${String(scopeMatches)} elements the scope matched)`;
106
+ }
107
+ /** ` (ref e3)` for a described element, or '' when there is none or it has no ref. */
108
+ function describeRef(element) {
109
+ return element === undefined || '' === element.ref ? '' : ` (ref ${element.ref})`;
110
+ }
93
111
  /**
94
112
  * Why an `absent` check failed. `absent` means removed from the DOM, so an element the app hid but
95
113
  * kept mounted still fails it, correctly. But "found 1" beside `visible: false` evidence reads as a
@@ -99,14 +117,15 @@ function describePresentTestidsCut(shown, total) {
99
117
  * check names no state: with `state: "hidden"` the advice would repeat the check itself, and with any
100
118
  * other state it would ask the caller to drop the condition they actually wrote.
101
119
  */
102
- function describeAbsentMiss(match, state) {
103
- const found = `expected element to be absent but found ${String(match.count)}`;
120
+ function describeAbsentMiss(match, state, subject) {
121
+ const found = `expected no element matching ${subject} but found ${String(match.count)}`;
104
122
  const allDescribedHidden = undefined === state &&
105
123
  match.elements.length > 0 &&
106
124
  match.elements.length === match.count &&
107
125
  match.elements.every((element) => !element.visible);
108
- if (!allDescribedHidden)
126
+ if (!allDescribedHidden) {
109
127
  return found;
128
+ }
110
129
  const which = 1 === match.count ? 'it is' : 'every one is';
111
130
  return (`${found}, but ${which} hidden — \`absent\` means removed from the DOM; ` +
112
131
  `to assert it isn't shown, use \`state: "${ElementState.HIDDEN}"\``);
@@ -127,15 +146,71 @@ function describeUnreadable(why) {
127
146
  return (`the text is on the page, but a user cannot read it (${why}). ` +
128
147
  'Fix the colour or the opacity, then check again');
129
148
  }
130
- async function matchOnce(session, query, state, diagnose) {
149
+ /**
150
+ * Why a match is refused before the round-trip (#1990): the page DECLARED its commands and match is
151
+ * not one of them, so sending it could only end in a timeout that reads as a slow page.
152
+ */
153
+ function matchNotServedMessage(sdkVersion, declared) {
154
+ const sdk = sdkVersion === undefined ? 'does not serve' : `is ${sdkVersion} and does not serve`;
155
+ return (`this page's SDK ${sdk} 'match': it declared ${String(declared.length)} command(s) when it ` +
156
+ "connected and this is not one of them. Update the page's @reticlehq packages: " +
157
+ '`reticle update` in the app.');
158
+ }
159
+ export async function matchOnce(session, query, state, diagnose, fullText = false) {
160
+ // A page that declared its commands and left match out can never answer (#1990): the session
161
+ // refuses the send, and that refusal used to be read as "zero matches". Refuse before the trip.
162
+ if (session.commands !== undefined && !session.commands.includes(ReticleCommand.MATCH)) {
163
+ throw new Error(matchNotServedMessage(session.sdkVersion, session.commands));
164
+ }
131
165
  const res = await session.command(ReticleCommand.MATCH, {
132
166
  query,
133
167
  state,
134
168
  ...(true === diagnose ? { diagnose: true } : {}),
169
+ ...(fullText ? { [MatchArg.FULL_TEXT]: true } : {}),
135
170
  });
136
- if (!res.ok)
137
- return { matched: false, count: 0, elements: [] };
138
- return (res.result ?? { matched: false, count: 0, elements: [] });
171
+ // A reply with an error never looked at the page. Read as zero matches, a query the page's schema
172
+ // refused or a matcher that threw became a false `no`. Thrown, the verdict reads it as unknown.
173
+ if (!res.ok) {
174
+ const error = res.error ?? 'no error given';
175
+ // An SDK older than MATCH_CASE_SINCE refuses the whole query for this one key, and a page that
176
+ // reports no version is still sent it. Ask once more without it and check the case here.
177
+ if (true === query.matchCase && error.includes(MATCH_CASE_FIELD)) {
178
+ return matchCaseOnThisSide(session, query, state, diagnose, fullText);
179
+ }
180
+ throw new Error(`the page could not answer 'match': ${error}`);
181
+ }
182
+ // An ok reply with no result said nothing about the page either. Defaulting it to zero matches
183
+ // was the same false `no`.
184
+ if (undefined === res.result || null === res.result) {
185
+ throw new Error(`the page could not answer 'match': the reply carried no result`);
186
+ }
187
+ return res.result;
188
+ }
189
+ /** The query key an SDK older than MATCH_CASE_SINCE does not know. Its refusal names the key. */
190
+ const MATCH_CASE_FIELD = 'matchCase';
191
+ /**
192
+ * Match without `matchCase`, then keep only the elements whose text holds the exact case.
193
+ *
194
+ * The case is checked on the text the page describes. When that text cannot show the match (a
195
+ * truncated description, or more matches than the page described), the result is not decided: the
196
+ * error makes the verdict unknown, never a false `no`.
197
+ */
198
+ async function matchCaseOnThisSide(session, query, state, diagnose, fullText) {
199
+ const caseBlind = { ...query };
200
+ delete caseBlind.matchCase;
201
+ const match = await matchOnce(session, caseBlind, state, diagnose, fullText);
202
+ const want = query.text;
203
+ if (undefined === want) {
204
+ return match;
205
+ }
206
+ const undecided = match.count > match.elements.length ||
207
+ match.elements.some((element) => !(element.text ?? element.name).toLowerCase().includes(want.toLowerCase()));
208
+ if (undecided) {
209
+ throw new Error(`the page's SDK cannot match case, and its description of the matches does not show ` +
210
+ `${JSON.stringify(want)}, so the case was not checked. Update the page's @reticlehq packages`);
211
+ }
212
+ const kept = match.elements.filter((element) => satisfiesResiduals(element, [['text', want]]));
213
+ return { ...match, matched: kept.length > 0, count: kept.length, elements: kept };
139
214
  }
140
215
  /**
141
216
  * Roles that exist to ANNOUNCE something. An empty one is the container, not the message.
@@ -165,13 +240,15 @@ function substantiveMatches(query, elements) {
165
240
  query.name === undefined &&
166
241
  query.text === undefined &&
167
242
  query.testid === undefined;
168
- if (!bareRole || !ANNOUNCEMENT_ROLES.has(query.role ?? ''))
243
+ if (!bareRole || !ANNOUNCEMENT_ROLES.has(query.role ?? '')) {
169
244
  return elements;
245
+ }
170
246
  // Nothing described, nothing to judge. `elements` is only the described PREFIX of a match — the
171
247
  // browser truncates it, and it can be empty while `count` is not. Calling that hollow would turn a
172
248
  // truncation into a verdict, so an unjudgeable set keeps the old answer.
173
- if (0 === elements.length)
249
+ if (0 === elements.length) {
174
250
  return elements;
251
+ }
175
252
  return elements.filter((e) => e.name.length > 0 || (e.text ?? '').trim().length > 0);
176
253
  }
177
254
  /**
@@ -182,34 +259,23 @@ function substantiveMatches(query, elements) {
182
259
  const ELEMENT_STATE_SINCE = {
183
260
  // The key is checked against ElementState by the Record type, so a misspelt state cannot compile.
184
261
  pressed: '3.4.0',
262
+ receivesPointer: '3.10.0',
185
263
  };
186
- /** Leading `major.minor.patch` as numbers; a pre-release of a version counts as that version. */
187
- function versionParts(version) {
188
- const m = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
189
- return null === m ? undefined : [Number(m[1]), Number(m[2]), Number(m[3])];
190
- }
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);
194
- const need = versionParts(since);
195
- if (have === undefined || need === undefined)
196
- return false;
197
- for (let i = 0; i < 3; i += 1) {
198
- if (have[i] !== need[i])
199
- return (have[i] ?? 0) < (need[i] ?? 0);
200
- }
201
- return false;
202
- }
203
264
  /** The state, when the page's SDK is older than the first release that answers it. */
204
265
  function stateTheSdkPredates(sdk, state) {
205
266
  const since = state === undefined ? undefined : ELEMENT_STATE_SINCE[state];
206
- if (sdk === undefined || state === undefined || since === undefined)
267
+ if (sdk === undefined || state === undefined || since === undefined) {
207
268
  return undefined;
269
+ }
208
270
  return sdkPredates(sdk, since) ? { sdk, state, since } : undefined;
209
271
  }
210
272
  /** The first SDK release whose element query accepts `matchCase`; an older page refuses the query. */
211
273
  const MATCH_CASE_SINCE = '3.7.0';
212
- export async function evalElement(session, query, state, absent, diagnose) {
274
+ export async function evalElement(session, query, state, absent, diagnose,
275
+ /** Describe the matches with their full text, for a caller that will JUDGE it (see `withTextProperty`). */
276
+ fullText = false,
277
+ /** For an absence: only an element whose text satisfies this fails it. See `absentUnlessSatisfied`. */
278
+ unlessText) {
213
279
  const tooOld = stateTheSdkPredates(session.sdkVersion, state);
214
280
  if (tooOld !== undefined) {
215
281
  const reason = `the page's SDK is ${tooOld.sdk}, and the '${tooOld.state}' state needs ${tooOld.since} or ` +
@@ -232,8 +298,27 @@ export async function evalElement(session, query, state, absent, diagnose) {
232
298
  const reason = describeUnusableElementQuery(query, residual.unusable);
233
299
  return { pass: false, failureReason: reason, inconclusive: reason };
234
300
  }
235
- let match = await matchOnce(session, withAltProjected(query, residual.checks), state, diagnose);
301
+ // A `text` checked on this side is checked against the element's text, which is the 80-character
302
+ // display form unless the full text is asked for: words past the cut read as absent.
303
+ const textOnThisSide = residual.checks.some(([field]) => 'text' === field);
304
+ let match = await matchOnce(session, withAltProjected(query, residual.checks), state, diagnose, fullText || textOnThisSide);
236
305
  const subject = JSON.stringify(query);
306
+ // Full text was asked for to JUDGE it, so a reading that is not the full text is not graded.
307
+ if (fullText && !absent && match.matched) {
308
+ // A page too old to know the argument ignores it and answers with the 80-character display form,
309
+ // which looks exactly like a short text. It cannot say so, which is why the page echoes the ask.
310
+ if (true !== match.fullText) {
311
+ const reason = `the page's SDK did not return the whole text of ${subject}, so a property of it was not ` +
312
+ `decided. Update the page's @reticlehq packages`;
313
+ return { pass: false, failureReason: reason, inconclusive: reason };
314
+ }
315
+ // `elements` is only the described prefix, and a text property is judged on all that matched.
316
+ if (match.count > match.elements.length) {
317
+ const reason = `${String(match.count)} elements matched ${subject} and only ${String(match.elements.length)} ` +
318
+ `were read in full, so a property of their text was not decided on all of it. Narrow the locator`;
319
+ return { pass: false, failureReason: reason, inconclusive: reason };
320
+ }
321
+ }
237
322
  // A residual narrows the SET; `count` is every match while `elements` is only the described prefix,
238
323
  // so a locator broad enough to be truncated cannot be narrowed honestly. Say so instead of guessing.
239
324
  if (residual.checks.length > 0 && match.count > match.elements.length) {
@@ -279,10 +364,13 @@ export async function evalElement(session, query, state, absent, diagnose) {
279
364
  if (true === match.scopeMissing) {
280
365
  return { pass: true, evidence: { absent: true, scopeMissing: true } };
281
366
  }
367
+ if (match.matched && unlessText !== undefined) {
368
+ return absentUnlessSatisfied(match, unlessText, subject);
369
+ }
282
370
  return match.matched
283
371
  ? {
284
372
  pass: false,
285
- failureReason: describeAbsentMiss(match, state),
373
+ failureReason: describeAbsentMiss(match, state, subject),
286
374
  observed: `${String(match.count)} element(s) matching ${subject}`,
287
375
  expected: `no element matching ${subject}`,
288
376
  assertion: 'element.absent',
@@ -351,7 +439,7 @@ export async function evalElement(session, query, state, absent, diagnose) {
351
439
  if (!diagnose) {
352
440
  return {
353
441
  pass: false,
354
- failureReason: `no element matched ${subject}${state === undefined ? '' : ` in state '${state}'`}`,
442
+ failureReason: `no element matched ${subject}${state === undefined ? '' : ` in state '${state}'`}${describeScopeMatches(match.scopeMatches)}`,
355
443
  observed: 'no matching element on the page',
356
444
  expected: `an element matching ${subject}${state === undefined ? '' : ` in state '${state}'`}`,
357
445
  assertion: 'element.present',
@@ -363,7 +451,7 @@ export async function evalElement(session, query, state, absent, diagnose) {
363
451
  if (relaxed.matched) {
364
452
  return {
365
453
  pass: false,
366
- failureReason: `element exists but not in state '${state}'`,
454
+ failureReason: `element matching ${subject} exists${describeRef(relaxed.elements[0])} but not in state '${state}'`,
367
455
  observed: `element matching ${subject} is present, states: ${relaxed.elements[0]?.states.join(', ') ?? 'unknown'}`,
368
456
  expected: `element matching ${subject} in state '${state}'`,
369
457
  assertion: 'element.state',
@@ -376,7 +464,7 @@ export async function evalElement(session, query, state, absent, diagnose) {
376
464
  if (roleOnly.matched) {
377
465
  return {
378
466
  pass: false,
379
- failureReason: `no '${query.role}' named '${query.name}'; saw: ${roleOnly.elements
467
+ failureReason: `no '${query.role}' named '${query.name}' (query ${subject}); saw: ${roleOnly.elements
380
468
  .map((e) => e.name)
381
469
  .filter((n) => n.length > 0)
382
470
  .join(', ')}`,
@@ -398,7 +486,7 @@ export async function evalElement(session, query, state, absent, diagnose) {
398
486
  const seen = byName.map((e) => `${'' === e.role ? 'no role' : e.role} "${'' === e.name ? (e.text ?? '') : e.name}" (${e.ref})`);
399
487
  return {
400
488
  pass: false,
401
- failureReason: `no '${query.role}' named '${query.name}'; that name is on: ${seen.join(', ')}`,
489
+ failureReason: `no '${query.role}' named '${query.name}' (query ${subject}); that name is on: ${seen.join(', ')}`,
402
490
  observed: `no element has role '${query.role}'; elements named '${query.name}': ${seen.join(', ')}`,
403
491
  expected: `a '${query.role}' named '${query.name}'`,
404
492
  assertion: 'element.role+name',
@@ -447,7 +535,7 @@ export async function evalElement(session, query, state, absent, diagnose) {
447
535
  caseOnlyMiss: true,
448
536
  wouldHold: `the same check with ignoreCase: true (the page shows "${match.hint?.caseMiss ?? ''}")`,
449
537
  }),
450
- failureReason: `no element matched ${subject}${state === undefined ? '' : ` in state '${state}'`}${suffix}${cut}`,
538
+ failureReason: `no element matched ${subject}${state === undefined ? '' : ` in state '${state}'`}${describeScopeMatches(match.scopeMatches)}${suffix}${cut}`,
451
539
  observed: `no matching element on the page${suffix}`,
452
540
  expected: `an element matching ${subject}${state === undefined ? '' : ` in state '${state}'`}`,
453
541
  assertion: 'element.present',
@@ -480,8 +568,9 @@ export async function evalElement(session, query, state, absent, diagnose) {
480
568
  */
481
569
  /** The text an element descriptor reported, or ''. Never `String(unknown)` — see `show` in property.ts. */
482
570
  function textOf(element) {
483
- if ('object' !== typeof element || null === element)
571
+ if ('object' !== typeof element || null === element) {
484
572
  return '';
573
+ }
485
574
  const value = element.text;
486
575
  return 'string' === typeof value ? value : '';
487
576
  }
@@ -490,11 +579,83 @@ export function joinedText(evidence) {
490
579
  const described = Array.isArray(evidence) ? evidence : [];
491
580
  return described.map(textOf).join(' ').trim();
492
581
  }
582
+ /**
583
+ * A match re-bounded to the text an agent is shown.
584
+ *
585
+ * The property was judged on the full text; the verdict that carries the match back is output,
586
+ * and judging more must not make it bigger.
587
+ */
588
+ function shownBounded(element) {
589
+ if ('object' !== typeof element || null === element) {
590
+ return element;
591
+ }
592
+ const max = TRANSPORT_LIMITS.MAX_DESCRIBED_TEXT;
593
+ const text = textOf(element);
594
+ return text.length > max ? { ...element, text: `${text.slice(0, max)}…` } : element;
595
+ }
596
+ /**
597
+ * An absence check that carries a property: "no element whose text satisfies it".
598
+ *
599
+ * The recorder writes "no 'bookmark 02'" as text containing 'bookmark' that matches /bookmark \d+/.
600
+ * Read as a plain absence, any other 'bookmark' on the page ("Add bookmark") failed it, and the
601
+ * property was then judged on an empty text. Only a match whose text satisfies the property fails
602
+ * it. A match that was not described, or not read in full, could be the one, so it is undecided.
603
+ */
604
+ function absentUnlessSatisfied(match, assertion, subject) {
605
+ const hits = match.elements.filter((el) => satisfiesProperty(textOf(el), assertion).ok);
606
+ if (0 < hits.length) {
607
+ return {
608
+ pass: false,
609
+ failureReason: `expected no element matching ${subject} to satisfy ${assertion.property}, but found ${String(hits.length)}`,
610
+ observed: `${String(hits.length)} element(s) matching ${subject} satisfy ${assertion.property}`,
611
+ expected: `no element matching ${subject} that satisfies ${assertion.property}`,
612
+ assertion: 'element.absent',
613
+ evidence: hits.map(shownBounded),
614
+ };
615
+ }
616
+ if (match.count > match.elements.length || match.elements.some(wasCutAtFullBound)) {
617
+ const reason = `${String(match.count)} element(s) match ${subject} and not all of their text was read, so ` +
618
+ `whether one satisfies ${assertion.property} was not decided. Scope the predicate to a smaller element`;
619
+ return { pass: false, failureReason: reason, inconclusive: reason };
620
+ }
621
+ return { pass: true, evidence: { absent: true, unsatisfiedMatches: match.count } };
622
+ }
623
+ /**
624
+ * Whether a described text was cut at the full-text bound. A cut text is that many characters and
625
+ * an ellipsis, so only a cut one is ever longer than the bound.
626
+ */
627
+ function wasCutAtFullBound(element) {
628
+ return textOf(element).length > TRANSPORT_LIMITS.MAX_FULL_TEXT;
629
+ }
630
+ /**
631
+ * The whole text of a passing match read in full (see `evalElement`'s `fullText`), or the result that
632
+ * says it was cut short.
633
+ *
634
+ * Whatever judges the text on a reading that stopped short could pass or fail on the part not read,
635
+ * so it is not judged: the same refusal a truncated state value gets. `undecided` names what was
636
+ * left undecided, so the caller's own question is the one the message answers.
637
+ */
638
+ export function wholeTextOf(evidence, subject, undecided) {
639
+ const matched = Array.isArray(evidence) ? evidence : [];
640
+ if (matched.some(wasCutAtFullBound)) {
641
+ const reason = `the text of ${subject} is longer than the ${String(TRANSPORT_LIMITS.MAX_FULL_TEXT)} characters ` +
642
+ `Reticle reads to judge it, so ${undecided} was not decided on all of it. ` +
643
+ `Scope the predicate to a smaller element`;
644
+ return { result: { pass: false, failureReason: reason, inconclusive: reason } };
645
+ }
646
+ return { text: joinedText(matched) };
647
+ }
493
648
  export function withTextProperty(base, assertion, subject, baseline) {
494
- if (!base.pass)
649
+ if (!base.pass) {
495
650
  return base;
496
- const described = Array.isArray(base.evidence) ? base.evidence : [];
497
- const text = joinedText(described);
651
+ }
652
+ const matched = Array.isArray(base.evidence) ? base.evidence : [];
653
+ const whole = wholeTextOf(matched, subject, assertion.property);
654
+ if ('result' in whole) {
655
+ return whole.result;
656
+ }
657
+ const { text } = whole;
658
+ const described = matched.map(shownBounded);
498
659
  const result = satisfiesProperty(text, assertion, baseline);
499
660
  // Nothing was compared — a relative property with no before-reading. See the twin in `evalState`.
500
661
  if (true === result.unevaluated) {
@@ -506,7 +667,7 @@ export function withTextProperty(base, assertion, subject, baseline) {
506
667
  return {
507
668
  pass: false,
508
669
  failureReason: `text of ${subject} ${result.because}`,
509
- observed: `text of ${subject} = ${JSON.stringify(text)}`,
670
+ observed: `text of ${subject} = ${JSON.stringify(clipBody(text))}`,
510
671
  expected: `text of ${subject} to satisfy ${assertion.property}`,
511
672
  assertion: `text.${assertion.property}`,
512
673
  evidence: described,
@@ -521,8 +682,9 @@ const MAX_BY_NAME = 3;
521
682
  async function nearestByName(session, name, state) {
522
683
  for (const query of [{ label: name }, { placeholder: name }]) {
523
684
  const found = await matchOnce(session, query, state);
524
- if (found.matched)
685
+ if (found.matched) {
525
686
  return found.elements.slice(0, MAX_BY_NAME);
687
+ }
526
688
  }
527
689
  return [];
528
690
  }
@@ -175,3 +175,5 @@ export declare function clipBody(body: string): string;
175
175
  export declare function describeNetFilter(p: Extract<Predicate, {
176
176
  kind: typeof PredicateKind.NET;
177
177
  }>): string;
178
+ /** Whether the page's SDK is older than `since`. An unknown or unreadable version is not. */
179
+ export declare function sdkPredates(sdk: string | undefined, since: string): boolean;
@@ -271,3 +271,22 @@ export function describeNetFilter(p) {
271
271
  const { kind: _kind, count: _count, since: _since, ...filter } = p;
272
272
  return JSON.stringify(filter);
273
273
  }
274
+ /** Leading `major.minor.patch` as numbers; a pre-release of a version counts as that version. */
275
+ function versionParts(version) {
276
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
277
+ return null === m ? undefined : [Number(m[1]), Number(m[2]), Number(m[3])];
278
+ }
279
+ /** Whether the page's SDK is older than `since`. An unknown or unreadable version is not. */
280
+ export function sdkPredates(sdk, since) {
281
+ const have = sdk === undefined ? undefined : versionParts(sdk);
282
+ const need = versionParts(since);
283
+ if (have === undefined || need === undefined) {
284
+ return false;
285
+ }
286
+ for (let i = 0; i < 3; i += 1) {
287
+ if (have[i] !== need[i]) {
288
+ return (have[i] ?? 0) < (need[i] ?? 0);
289
+ }
290
+ }
291
+ return false;
292
+ }
@@ -22,10 +22,7 @@ export declare function skippedBodyRemedy(reason: unknown): string | undefined;
22
22
  export declare function sharedSkipReason(reasons: readonly unknown[]): unknown;
23
23
  export declare function evalNet(events: ReticleEvent[], p: Extract<Predicate, {
24
24
  kind: typeof PredicateKind.NET;
25
- }>): EvalResult;
26
- export declare function evalAnimation(events: ReticleEvent[], p: Extract<Predicate, {
27
- kind: typeof PredicateKind.ANIMATION;
28
- }>): EvalResult;
25
+ }>, sdkVersion?: string): EvalResult;
29
26
  export declare function evalSignal(events: ReticleEvent[], p: Extract<Predicate, {
30
27
  kind: typeof PredicateKind.SIGNAL;
31
28
  }>): EvalResult;
@@ -1,27 +1,22 @@
1
- import { EventType, NetInitiator, PredicateKind, ResponseBodyReason, SettledChannel, StreamDirection, isDevToolingUrl, isForeignTraffic, urlForMatch, REDACTED_VALUE, } from '@reticlehq/core';
1
+ import { EventType, neverAnswered, PredicateKind, ResponseBodyReason, SettledChannel, StreamDirection, isDevToolingUrl, isForeignTraffic, urlForMatch, REDACTED_VALUE, } from '@reticlehq/core';
2
2
  import { isReticleVoice } from '../../state-bookkeeping.js';
3
3
  import { describeObserved } from './observed-in-window.js';
4
4
  import { netEvidence } from './net-evidence.js';
5
- import { mergeNetworkDetail } from '../../window/network-detail-merge.js';
5
+ import { truncatedBodyAdvice } from './truncated-body-advice.js';
6
+ import { mergeNetworkDetail, withDownloadRequests } from '../../window/network-detail-merge.js';
7
+ import { departedInWindow, mediaEntryBeforeWindow } from '../../window/event-filters.js';
6
8
  import { checkRequestBody, REMEDY_BODY_CAPTURE, newRequestBodyState, requestBodyVerdict, } from './predicate-request-body.js';
7
9
  export { evalConsole } from './predicate-console.js';
8
10
  import { clipBody, dataMatches, describeBodyFieldMiss, describeFieldMiss, describeNetFilter, matchJsonBody, num, redactedOnPath, str, } from './predicate-eval-kit.js';
9
11
  import { keyFragmentOnly } from './body-key-fragment.js';
10
12
  import { evalExactCount } from '../../exact-count.js';
11
- import { PRE_ATTACH_CAVEAT, nativeDownloadReason, targetsNativeDownload, targetsUnobservedChannel, unobservedChannelReason, } from './net-blind-spots.js';
13
+ import { PRE_ATTACH_CAVEAT, earlierMediaReason, mediaLoadReason, nativeDownloadReason, targetsMediaLoad, targetsNativeDownload, targetsUnobservedChannel, unobservedChannelReason, unrecordedCallMiss, } from './net-blind-spots.js';
12
14
  export { clipBody, dataMatches, describeNetFilter, matchValue, str, } from './predicate-eval-kit.js';
13
15
  /** The oracle a net body clause reports, so an agent can branch on which one decided. */
14
16
  const NetBodyAssertion = {
15
17
  CONTAINS: 'net.bodyContains',
16
18
  MATCHES: 'net.bodyMatches',
17
19
  };
18
- /** A truncated body missed a `bodyContains`: the kept prefix can still answer a substring. */
19
- const TRUNCATED_PREFIX_REMEDY = "Raise it past this response's size and re-run, or assert on something inside the recorded prefix";
20
- /**
21
- * A truncated body missed a `bodyMatches`. That clause parses the whole body and a JSON prefix never
22
- * parses, so "assert inside the prefix" changes nothing for it (#1417): name what can work instead.
23
- */
24
- const TRUNCATED_MATCHES_REMEDY = "Raise it past this response's size and re-run. `bodyMatches` parses the whole body, and a JSON prefix never parses, so it cannot be judged on the kept part: to assert on what was kept, use `bodyContains` with a substring from it";
25
20
  // The predicate SHAPE — the discriminated union, its aliases and its zod schema — lives in
26
21
  // predicate-schema.ts, and is re-exported here: the two halves are ONE public surface.
27
22
  export * from './predicate-schema.js';
@@ -81,17 +76,33 @@ function describeSignalFilter(p) {
81
76
  return JSON.stringify(filter);
82
77
  }
83
78
  function nativeDownloadMiss(events, p) {
84
- if (!targetsNativeDownload(p.urlContains)) {
79
+ const media = targetsMediaLoad(p.urlContains);
80
+ const download = targetsNativeDownload(p.urlContains);
81
+ const departed = departedInWindow(events, p.since ?? 0, p.method, p.urlContains);
82
+ const earlierMedia = mediaEntryBeforeWindow(events, p.since ?? 0, p.method, p.urlContains);
83
+ if (!media && !download && !departed && earlierMedia === undefined) {
85
84
  return undefined;
86
85
  }
87
- const reason = nativeDownloadReason(describeNetFilter(p));
86
+ const filter = describeNetFilter(p);
87
+ let reason = nativeDownloadReason(filter);
88
+ let assertion = 'net.native-download';
89
+ if (media) {
90
+ reason = mediaLoadReason(filter);
91
+ assertion = 'net.media-load';
92
+ }
93
+ else if (!download && !departed) {
94
+ // The load the filter names was recorded before this window, and the observer reports no
95
+ // second entry for its URL: the empty window cannot say the load did not repeat inside it.
96
+ reason = earlierMediaReason(filter);
97
+ assertion = 'net.media-before-window';
98
+ }
88
99
  return {
89
100
  pass: false,
90
101
  failureReason: reason,
91
102
  inconclusive: reason,
92
103
  observed: observedNetCalls(events, p.urlContains),
93
- expected: `a fetch or XHR matching ${describeNetFilter(p)}`,
94
- assertion: 'net.native-download',
104
+ expected: `a fetch or XHR matching ${filter}`,
105
+ assertion,
95
106
  };
96
107
  }
97
108
  /**
@@ -177,11 +188,15 @@ function unrecordedBodyReason(p, reason) {
177
188
  const head = `a call matching ${describeNetFilter(p)} was answered, but its body was not recorded, so ${wantedBody(p)} could not be checked, which is not the same as absent.`;
178
189
  return `${head} ${skippedBodyRemedy(reason) ?? REMEDY_BODY_CAPTURE}`;
179
190
  }
180
- export function evalNet(events, p) {
191
+ export function evalNet(events, p, sdkVersion) {
181
192
  // SSE headers close the request immediately. A later detail supplies its captured body without another call.
182
193
  if (p.bodyContains !== undefined || p.bodyMatches !== undefined) {
183
194
  events = mergeNetworkDetail(events);
184
195
  }
196
+ else {
197
+ // A server-sent download is a request even when nothing asks for its body.
198
+ events = withDownloadRequests(events);
199
+ }
185
200
  const since = p.since ?? 0;
186
201
  /**
187
202
  * Computed once: the gate every zero-match downgrade below reads. True means the resource-timing
@@ -363,10 +378,9 @@ export function evalNet(events, p) {
363
378
  // stays inconclusive either way: a partial parse must not decide it, since a later duplicate key
364
379
  // could overturn whatever the prefix seemed to say.
365
380
  const missedMatch = NetBodyAssertion.MATCHES === truncatedClause;
366
- const remedy = missedMatch ? TRUNCATED_MATCHES_REMEDY : TRUNCATED_PREFIX_REMEDY;
367
381
  return {
368
382
  pass: false,
369
- inconclusive: `a call matching ${describeNetFilter(p)} was answered with a body that was TRUNCATED before it was recorded, and ${wantedBody(p)} is not in the part that was kept — so this is undecidable, not a failure. The cap is per-body and set where the app calls connect(): \`reticle.connect({ captureNetworkBodies: true, networkBodyMaxChars: 65536 })\`, or for the Vite plugin \`reticle({ networkBodyMaxChars: 65536 })\` / VITE_RETICLE_BODY_MAX_CHARS=65536 (default 8192, max 262144). An SDK older than this daemon ignores the option; a version skew on the session says so. ${remedy}`,
383
+ inconclusive: `a call matching ${describeNetFilter(p)} was answered with a body that was TRUNCATED before it was recorded, and ${wantedBody(p)} is not in the part that was kept — so this is undecidable, not a failure. ${truncatedBodyAdvice(sdkVersion, missedMatch)}`,
370
384
  observed: `the first ${String(truncatedBody.length)} characters of a truncated response body ${JSON.stringify(clipBody(truncatedBody))}`,
371
385
  expected: `a response body carrying ${wantedBody(p)}`,
372
386
  assertion: truncatedClause ?? NetBodyAssertion.CONTAINS,
@@ -394,6 +408,11 @@ export function evalNet(events, p) {
394
408
  // useEffect-double-fire / retry-storm regression class, where the request DID fire (presence passes)
395
409
  // but fired the WRONG number of times. Without `count`, the matcher is presence-only (≥1).
396
410
  if (p.count !== undefined) {
411
+ // A marked call is not in `matches`, so no count over its URL can be judged, a pass included.
412
+ const unpatched = unrecordedCallMiss(events, p, () => observedNetCalls(events, p.urlContains));
413
+ if (unpatched !== undefined) {
414
+ return unpatched;
415
+ }
397
416
  if (0 === matches.length) {
398
417
  const download = nativeDownloadMiss(events, p);
399
418
  if (download !== undefined) {
@@ -428,7 +447,8 @@ export function evalNet(events, p) {
428
447
  }
429
448
  const hit = matches[0];
430
449
  if (hit === undefined) {
431
- const download = nativeDownloadMiss(events, p);
450
+ const download = nativeDownloadMiss(events, p) ??
451
+ unrecordedCallMiss(events, p, () => observedNetCalls(events, p.urlContains));
432
452
  if (download !== undefined) {
433
453
  return download;
434
454
  }
@@ -456,32 +476,6 @@ export function evalNet(events, p) {
456
476
  assertion: 'net.present',
457
477
  };
458
478
  }
459
- export function evalAnimation(events, p) {
460
- const wantType = true === p.completed ? EventType.ANIM_END : EventType.ANIM_START;
461
- const hit = events.find((e) => {
462
- if (e.type !== wantType) {
463
- return false;
464
- }
465
- const name = str(e.data['name']);
466
- // A check with no name asks about the app, so Reticle's own bookkeeping signals do not count.
467
- if (p.name === undefined ? isReticleVoice(name ?? '') : name !== p.name) {
468
- return false;
469
- }
470
- if (p.target !== undefined && e.ref !== p.target) {
471
- return false;
472
- }
473
- return true;
474
- });
475
- return hit !== undefined
476
- ? { pass: true, evidence: hit.data }
477
- : {
478
- pass: false,
479
- failureReason: `no animation matched ${JSON.stringify(p)}`,
480
- observed: 'no matching animation in the window',
481
- expected: `an animation matching ${JSON.stringify(p)}`,
482
- assertion: 'animation.present',
483
- };
484
- }
485
479
  export function evalSignal(events, p) {
486
480
  /**
487
481
  * A pattern key the transport sanitizer redacted on a payload of the right name. The marker is
@@ -631,10 +625,10 @@ const RETICLE_BUSY_SIGNAL = 'reticle:busy';
631
625
  * The act wait (`server/src/surface/tools/act/settle-in-flight.ts`) has always excluded it and
632
626
  * `core/src/wire/net.ts` says it must be; this predicate counted it, so `act_and_wait { until:
633
627
  * settled }` after a plain `<a href>` never passed and agents dropped `settled` from their `until`.
634
- * Spelled against the shared constant rather than the string, so the two settle decisions cannot
635
- * drift onto two vocabularies.
628
+ * Read through core's `neverAnswered`, so every settle decision uses one rule. It also covers a
629
+ * request whose page unloaded before its answer arrived (#1944): that answer went away too.
636
630
  */
637
- const isDeparture = (data) => data['initiator'] === NetInitiator.NAVIGATION;
631
+ const isDeparture = neverAnswered;
638
632
  /**
639
633
  * "The page has gone quiet": no network/DOM/animation activity for at least `quietMs`. Needs the
640
634
  * wall-clock `now` (in the buffer's time base) because "no activity in the last N ms" is relative to