@reticlehq/engine 3.5.0 → 3.7.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 (57) hide show
  1. package/dist/disagreement/body-failures.js +2 -1
  2. package/dist/disagreement/contradiction-evidence.d.ts +73 -1
  3. package/dist/disagreement/contradiction-evidence.js +154 -6
  4. package/dist/disagreement/contradiction-types.d.ts +8 -1
  5. package/dist/disagreement/contradictions.d.ts +17 -1
  6. package/dist/disagreement/contradictions.js +111 -38
  7. package/dist/disagreement/echo-mismatch.js +42 -3
  8. package/dist/disagreement/reconcile.js +15 -0
  9. package/dist/disagreement/stale-response.js +37 -2
  10. package/dist/evidence/accepted-write.d.ts +26 -2
  11. package/dist/evidence/accepted-write.js +35 -18
  12. package/dist/evidence/already-true.d.ts +16 -0
  13. package/dist/evidence/already-true.js +48 -0
  14. package/dist/evidence/baseline.js +2 -6
  15. package/dist/evidence/blind-spots.d.ts +14 -3
  16. package/dist/evidence/blind-spots.js +48 -10
  17. package/dist/evidence/body-capture-remedy.d.ts +10 -0
  18. package/dist/evidence/body-capture-remedy.js +15 -2
  19. package/dist/evidence/instrumentation-gaps.js +3 -1
  20. package/dist/evidence/state-bookkeeping.d.ts +2 -0
  21. package/dist/evidence/state-bookkeeping.js +2 -0
  22. package/dist/evidence/superseded-checks.d.ts +29 -0
  23. package/dist/evidence/superseded-checks.js +30 -0
  24. package/dist/evidence/unsettled.js +4 -2
  25. package/dist/evidence/verified.d.ts +8 -1
  26. package/dist/evidence/verified.js +42 -4
  27. package/dist/question/declared.d.ts +24 -4
  28. package/dist/question/declared.js +26 -5
  29. package/dist/question/predicate/name-near-miss.d.ts +24 -0
  30. package/dist/question/predicate/name-near-miss.js +39 -0
  31. package/dist/question/predicate/net-blind-spots.d.ts +49 -0
  32. package/dist/question/predicate/net-blind-spots.js +153 -0
  33. package/dist/question/predicate/predicate-compare.js +13 -4
  34. package/dist/question/predicate/predicate-element.d.ts +15 -1
  35. package/dist/question/predicate/predicate-element.js +108 -7
  36. package/dist/question/predicate/predicate-eval-kit.d.ts +25 -0
  37. package/dist/question/predicate/predicate-eval-kit.js +31 -0
  38. package/dist/question/predicate/predicate-eval.d.ts +17 -2
  39. package/dist/question/predicate/predicate-eval.js +117 -180
  40. package/dist/question/predicate/predicate-parse.js +153 -13
  41. package/dist/question/predicate/predicate-request-body.d.ts +6 -1
  42. package/dist/question/predicate/predicate-request-body.js +7 -2
  43. package/dist/question/predicate/predicate-route.d.ts +2 -0
  44. package/dist/question/predicate/predicate-route.js +30 -0
  45. package/dist/question/predicate/predicate-schema.d.ts +11 -0
  46. package/dist/question/predicate/predicate-schema.js +110 -24
  47. package/dist/question/predicate/predicate-session.d.ts +10 -0
  48. package/dist/question/predicate/predicate-state.js +7 -0
  49. package/dist/question/predicate/predicate-to-links.js +1 -0
  50. package/dist/question/predicate/predicate.js +76 -25
  51. package/dist/question/predicate/split-text-miss.d.ts +6 -0
  52. package/dist/question/predicate/split-text-miss.js +10 -0
  53. package/dist/question/reaction.d.ts +1 -1
  54. package/dist/question/reaction.js +1 -1
  55. package/dist/state-bookkeeping.d.ts +25 -0
  56. package/dist/state-bookkeeping.js +70 -0
  57. package/package.json +2 -2
@@ -62,8 +62,13 @@ export function checkRequestBody(data, predicate, state) {
62
62
  *
63
63
  * Ranked the way the response side ranks its own: the two nobody could have answered (redacted,
64
64
  * unrecorded, truncated) come before the one that WAS answered and came out false.
65
+ *
66
+ * `responseMismatch` is the response body of a call whose request DID satisfy the clause and whose
67
+ * response did not. When it is set, a definite request mismatch on some OTHER call is not the
68
+ * explanation and yields to it; the unknowns above still win, because the call they describe may
69
+ * be the one that would have satisfied the whole predicate.
65
70
  */
66
- export function requestBodyVerdict(state, predicate, matchCount) {
71
+ export function requestBodyVerdict(state, predicate, matchCount, responseMismatch) {
67
72
  if (matchCount > 0)
68
73
  return undefined;
69
74
  const wanted = JSON.stringify(predicate.requestBodyContains ?? predicate.requestBodyMatches);
@@ -95,7 +100,7 @@ export function requestBodyVerdict(state, predicate, matchCount) {
95
100
  assertion: 'net.requestBody',
96
101
  };
97
102
  }
98
- if (state.mismatch !== undefined) {
103
+ if (state.mismatch !== undefined && responseMismatch === undefined) {
99
104
  // Named separately from "no call matched", for the reason the response side already learned: the
100
105
  // request DID fire, and reporting zero matches sends the caller to check the url and the method,
101
106
  // which are both fine, instead of to the value the UI actually sent.
@@ -47,6 +47,8 @@ interface RouteParts {
47
47
  }
48
48
  /** A `ROUTE_CHANGE` event, or its `data` — one reading, so the sixth copy cannot drift. */
49
49
  export declare function routeOfEvent(eventOrData: ReticleEvent | Record<string, unknown>): RouteParts | undefined;
50
+ /** A route as a navigable path, pathname + app query + hash, with Reticle's own params dropped. */
51
+ export declare function navigablePath(parts: Pick<RouteParts, 'docPath' | 'search' | 'hash'>): string;
50
52
  /** Same shape from a session URL (the fallback when the tab hard-loaded and emitted no route event). */
51
53
  export declare function routeOfUrl(url: string): RouteParts | undefined;
52
54
  export declare function evalRoute(events: ReticleEvent[], p: Extract<Predicate, {
@@ -100,6 +100,36 @@ function withoutIdentityParams(value) {
100
100
  parsed.searchParams.delete(name);
101
101
  return parsed.toString();
102
102
  }
103
+ /**
104
+ * A `?query` with Reticle's own params removed and the app's pairs left exactly as written. A recording keeps the app's query in `startPath` and replay compares against it,
105
+ * so a leased tab's `__reticle_*` params must be dropped on both sides or a tab already on the page
106
+ * reads as somewhere else (#1411).
107
+ */
108
+ function searchWithoutIdentityParams(search) {
109
+ const query = search.startsWith('?') ? search.slice(1) : search;
110
+ if ('' === query)
111
+ return '';
112
+ // Pair by pair, not through URLSearchParams: its round trip re-encodes what it keeps (`%20` comes
113
+ // back as `+`), so a hand-written startPath `/search?q=red%20shirt` would stop matching a tab on
114
+ // exactly that URL. Only Reticle's own pairs are removed; the rest keep their spelling.
115
+ const ours = new Set(Object.values(RETICLE_URL_PARAM));
116
+ const kept = query.split('&').filter((pair) => !ours.has(paramNameOf(pair)));
117
+ return 0 === kept.length ? '' : `?${kept.join('&')}`;
118
+ }
119
+ /** The decoded name of one `name=value` query pair, or the raw text when it does not decode. */
120
+ function paramNameOf(pair) {
121
+ const raw = pair.split('=', 1)[0] ?? '';
122
+ try {
123
+ return decodeURIComponent(raw.replaceAll('+', ' '));
124
+ }
125
+ catch {
126
+ return raw;
127
+ }
128
+ }
129
+ /** A route as a navigable path, pathname + app query + hash, with Reticle's own params dropped. */
130
+ export function navigablePath(parts) {
131
+ return `${parts.docPath}${searchWithoutIdentityParams(parts.search)}${parts.hash}`;
132
+ }
103
133
  /** The event payload as evidence: every URL-ish field scrubbed of our own params. */
104
134
  function routeEvidence(data) {
105
135
  return Object.fromEntries(Object.entries(data).map(([key, value]) => [key, withoutIdentityParams(value)]));
@@ -11,6 +11,17 @@ import { z } from 'zod';
11
11
  import { type ElementDescriptor, type ElementQuery } from '@reticlehq/core';
12
12
  export { PredicateSchema } from '@reticlehq/core';
13
13
  export type { Predicate, PropertyAssertion } from '@reticlehq/core';
14
+ /** The query to send, asking the browser to project `alt` when this side has to check it. */
15
+ export declare function withAltProjected(query: ElementQuery, checks: readonly [string, string][]): ElementQuery;
16
+ /**
17
+ * Why `alt` cannot be checked, when none of the matched elements is an image — or `undefined` when
18
+ * it can. A button has no alt, so grading it "no" would read as "the alt is wrong" when the truth is
19
+ * "this is not an image": a refusal that says what to use instead costs one turn.
20
+ *
21
+ * Only the case where NO match is an image is refused. With an image among them, the others simply do
22
+ * not satisfy `alt`, and the verdict is about the images.
23
+ */
24
+ export declare function describeAltOnNonImage(checks: readonly [string, string][], elements: readonly ElementDescriptor[]): string | undefined;
14
25
  interface ResidualQueryChecks {
15
26
  /** Dropped fields this side CAN check, as [field, wanted value] pairs. */
16
27
  checks: [string, string][];
@@ -12,25 +12,15 @@ import { PredicateKind, PredicateSchema, QueryBy, predicateShapeFor, } from '@re
12
12
  // One public surface, two packages. A caller asking this module for the shape is asking the right
13
13
  // module; it simply no longer OWNS it.
14
14
  export { PredicateSchema } from '@reticlehq/core';
15
- /**
16
- * Element-query fields an agent writes FLAT on an `element` predicate instead of nested under
17
- * `query`. `reticle_query` takes exactly these at the top level, so an agent that has just located
18
- * something writes the same words again when it asserts on it — and got `query: Required` plus an
19
- * `unknown field` list for its trouble. Lifting them is unambiguous: they have no other meaning on
20
- * this kind.
15
+ /*
16
+ * This file used to keep its own list of element-query fields, and issue #1375 is what that cost:
17
+ *
18
+ * core's copy had fallen four fields behind `ElementQuerySchema` (`scope`, `self`,
19
+ * `attrs`, `source`) while this one had not, so the two disagreed about what a flat element
20
+ * predicate may say. The list is gone: `residualQueryChecks` walks the query's OWN keys instead —
21
+ * the fields the caller actually wrote — which cannot fall behind a schema the query was parsed
22
+ * against, and costs no new core import (the engine's borrow count is a ceiling, not a budget).
21
23
  */
22
- const ELEMENT_QUERY_FIELDS = [
23
- 'by',
24
- 'value',
25
- 'role',
26
- 'name',
27
- 'text',
28
- 'label',
29
- 'placeholder',
30
- 'testid',
31
- 'alt',
32
- 'component',
33
- ];
34
24
  /**
35
25
  * The locator fields the browser actually CONSUMES for a given query — mirrors the precedence in
36
26
  * `findIn` (adapters/realm/browser/src/dom/query.ts).
@@ -46,6 +36,28 @@ const ELEMENT_QUERY_FIELDS = [
46
36
  */
47
37
  function usedQueryFields(query) {
48
38
  const used = new Set();
39
+ // `scope`, `attrs` and `self` are not locator fields, so no branch below consumes them and none is
40
+ // dropped: `scope` narrows WHERE the search runs (resolved before any locator branch runs),
41
+ // `attrs` projects the match, and `self` selects the scope root. Claiming these here — whatever
42
+ // their value — is what keeps them from being refused for merely existing.
43
+ //
44
+ // `source` is deliberately NOT one of them. It IS a locator — the anchor `component` is, consumed
45
+ // on exactly the same two branches — and it is claimed there and only there. Claiming it here too
46
+ // is what let a `by`+`value` query, or a `self: true` one, report the locator as having used a
47
+ // `source` it never read: the browser resolves those by `by`+`value` (or the scope root) and
48
+ // returns before `findBySource` is reached, so the predicate could pass for an element other than
49
+ // the one the caller's source location identified. Unclaimed, it falls through to the residual
50
+ // walk and is refused — exactly as `component` already is in the same position.
51
+ if (query.scope !== undefined)
52
+ used.add('scope');
53
+ if (query.attrs !== undefined)
54
+ used.add('attrs');
55
+ if (query.self !== undefined)
56
+ used.add('self');
57
+ // A modifier of the text rule, not a locator: the browser honours it wherever it reads `text`, and
58
+ // the residual text check below is already case-exact.
59
+ if (query.matchCase !== undefined)
60
+ used.add('matchCase');
49
61
  // The browser's `self` branch checks subtree text when supplied, but skips every other locator.
50
62
  // Mark only text as consumed so role/name/etc. remain residual checks on the returned descriptor.
51
63
  if (true === query.self)
@@ -54,12 +66,22 @@ function usedQueryFields(query) {
54
66
  used.add('by').add('value');
55
67
  if (QueryBy.ROLE === query.by)
56
68
  used.add('name');
57
- if (QueryBy.COMPONENT === query.by)
69
+ // `by: "component"` resolves through `findByComponent`, which tries the source stamp first and
70
+ // falls back to the component name — so a `source` written here IS consumed.
71
+ if (QueryBy.COMPONENT === query.by) {
58
72
  used.add('component');
73
+ if (query.source !== undefined)
74
+ used.add('source');
75
+ }
76
+ return used;
77
+ }
78
+ // The auto-anchor branch, reached only without `by`+`value`: `source` (precise) then `component`.
79
+ if (query.component !== undefined || query.source !== undefined) {
80
+ used.add('component');
81
+ if (query.source !== undefined)
82
+ used.add('source');
59
83
  return used;
60
84
  }
61
- if (query.component !== undefined || query.source !== undefined)
62
- return used.add('component');
63
85
  if (query.role !== undefined)
64
86
  return used.add('role').add('name');
65
87
  for (const field of ['text', 'label', 'placeholder', 'testid', 'alt']) {
@@ -68,6 +90,20 @@ function usedQueryFields(query) {
68
90
  }
69
91
  return used;
70
92
  }
93
+ /**
94
+ * The role the browser reports for an `<img>`. It stands in for "an image" because the descriptor
95
+ * carries no tag name, so anything else with this role — an `<svg role="img">` — counts as one too.
96
+ */
97
+ const IMAGE_ROLE = 'img';
98
+ const ALT_FIELD = 'alt';
99
+ /** How a failure reports an image that carries no `alt` attribute at all. */
100
+ const NO_ALT_ATTRIBUTE = '(no alt attribute)';
101
+ /** What the refusal says about `alt` on something that is not an image, and what to assert instead. */
102
+ const ALT_IMAGE_ONLY = '`alt` can only be checked on an image';
103
+ const ALT_USE_NAME = 'For an element that is not an image, assert its accessible name with `name` instead.';
104
+ function isImage(element) {
105
+ return IMAGE_ROLE === element.role;
106
+ }
71
107
  /**
72
108
  * How a dropped field is checked back on the server, against the descriptor the match returned.
73
109
  *
@@ -82,13 +118,58 @@ function usedQueryFields(query) {
82
118
  * copies out of a query result are the words that match here. `text` is a substring match, matching
83
119
  * Testing Library's `exact: false`, and falls back to the name because describe() omits `text` when it
84
120
  * equals the accessible name.
121
+ *
122
+ * `alt` is read from the image's `alt` ATTRIBUTE, projected onto the match by `withAltProjected` —
123
+ * not from its accessible name. Both a decorative `alt=""` and a missing alt give an empty name, and
124
+ * only the attribute tells them apart: a missing alt is the defect `alt: ""` exists to rule out. On
125
+ * anything but an image it is false, and `describeAltOnNonImage` turns that into a refusal.
85
126
  */
127
+ /**
128
+ * Does an element whose computed role is `actual` satisfy a query for `queried`?
129
+ *
130
+ * `searchbox` is an ARIA sub-role of `textbox`. A standard search input computes as `searchbox`
131
+ * (per HTML-AAM), which matches `{ role: "searchbox" }`. A `{ role: "textbox" }` query must
132
+ * keep matching it as well, so existing flows and recorded steps using `textbox` continue to match.
133
+ */
134
+ function matchesRole(actual, queried) {
135
+ if (actual === queried)
136
+ return true;
137
+ if ('textbox' === queried && 'searchbox' === actual)
138
+ return true;
139
+ return false;
140
+ }
86
141
  const RESIDUAL_CHECKS = {
87
142
  value: (element, want) => (element.value ?? '').trim() === want.trim(),
88
- role: (element, want) => element.role === want,
143
+ role: (element, want) => matchesRole(element.role, want),
89
144
  name: (element, want) => element.name.trim() === want.trim(),
90
145
  text: (element, want) => (element.text ?? element.name).includes(want),
146
+ [ALT_FIELD]: (element, want) => {
147
+ const alt = element.attrs?.[ALT_FIELD];
148
+ return isImage(element) && alt !== undefined && alt.trim() === want.trim();
149
+ },
91
150
  };
151
+ /** The query to send, asking the browser to project `alt` when this side has to check it. */
152
+ export function withAltProjected(query, checks) {
153
+ const attrs = query.attrs ?? [];
154
+ if (!checks.some(([field]) => ALT_FIELD === field) || attrs.includes(ALT_FIELD))
155
+ return query;
156
+ return { ...query, attrs: [...attrs, ALT_FIELD] };
157
+ }
158
+ /**
159
+ * Why `alt` cannot be checked, when none of the matched elements is an image — or `undefined` when
160
+ * it can. A button has no alt, so grading it "no" would read as "the alt is wrong" when the truth is
161
+ * "this is not an image": a refusal that says what to use instead costs one turn.
162
+ *
163
+ * Only the case where NO match is an image is refused. With an image among them, the others simply do
164
+ * not satisfy `alt`, and the verdict is about the images.
165
+ */
166
+ export function describeAltOnNonImage(checks, elements) {
167
+ const wantsAlt = checks.some(([field]) => ALT_FIELD === field);
168
+ if (!wantsAlt || 0 === elements.length || elements.some(isImage))
169
+ return undefined;
170
+ const roles = [...new Set(elements.map((element) => element.role))].join(', ');
171
+ return `${ALT_IMAGE_ONLY}, and the element matched is ${roles}, not ${IMAGE_ROLE}. ${ALT_USE_NAME}`;
172
+ }
92
173
  /**
93
174
  * Split a query's dropped fields into the ones the server can still enforce and the ones it cannot.
94
175
  *
@@ -101,7 +182,10 @@ export function residualQueryChecks(query) {
101
182
  const used = usedQueryFields(query);
102
183
  const checks = [];
103
184
  const unusable = [];
104
- for (const field of ELEMENT_QUERY_FIELDS) {
185
+ // The query's own keys, not a list beside the schema. Every field here was written by the caller
186
+ // and survived parsing, so it is one the locator either consumes or drops — which is the whole
187
+ // question. Reading them off the query also means the set cannot drift from `ElementQuerySchema`.
188
+ for (const field of Object.keys(query)) {
105
189
  const want = query[field];
106
190
  if (want === undefined || used.has(field))
107
191
  continue;
@@ -136,7 +220,9 @@ export function describeResidual(element, field) {
136
220
  ? (element.text ?? element.name)
137
221
  : 'role' === field
138
222
  ? element.role
139
- : element.name;
223
+ : ALT_FIELD === field
224
+ ? (element.attrs?.[ALT_FIELD] ?? NO_ALT_ATTRIBUTE)
225
+ : element.name;
140
226
  return `${element.role} "${element.name}" ${field}=${JSON.stringify(reading)}`;
141
227
  }
142
228
  /**
@@ -31,6 +31,16 @@ export interface PredicateSession {
31
31
  * navigates simply omits it and route falls back to change-only, as before.
32
32
  */
33
33
  url?: string;
34
+ /**
35
+ * Same-origin endpoints the project DECLARED the app fires on its own — `.reticle.json`
36
+ * `background`, matched the way `urlContains` is.
37
+ *
38
+ * The settle oracle asks "has the app finished its work", and a declared telemetry endpoint that
39
+ * keeps firing answers that question with a permanent no. Excluded only when declared, because
40
+ * nothing in a URL separates the app's own telemetry from the app's work. Optional: a fake that
41
+ * omits it excludes nothing, and same-origin traffic is never guessed at.
42
+ */
43
+ background?: readonly string[] | undefined;
34
44
  /**
35
45
  * The document currently under observation, as the session derived it from its own event stream.
36
46
  *
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import { PredicateKind, ReticleCommand, capDepth, selectPath } from '@reticlehq/core';
10
10
  import { matchValue } from './predicate-eval.js';
11
+ import { isStringifiedPrimitiveMismatch, stringifiedPrimitiveResult, } from './predicate-eval-kit.js';
11
12
  import { satisfiesProperty } from './property.js';
12
13
  /** One name, or none — two candidates is a question, not an answer. */
13
14
  function oneOf(names) {
@@ -159,6 +160,9 @@ async function evalStateNamed(session, p, storeName, baseline) {
159
160
  evidence: { store: storeName, path: p.path, value: capDepth(selection.value, 1) },
160
161
  };
161
162
  }
163
+ if (isStringifiedPrimitiveMismatch(selection.value, want)) {
164
+ return stringifiedPrimitiveResult(storeName, p.path, selection.value, want, capDepth);
165
+ }
162
166
  return {
163
167
  pass: false,
164
168
  failureReason: `state '${p.path}' is ${JSON.stringify(capDepth(selection.value, 0))}, expected ${JSON.stringify(want)}`,
@@ -306,6 +310,9 @@ export async function evalState(session, p, baseline) {
306
310
  evidence: { store: storeName, path: p.path, value: capDepth(selection.value, 1) },
307
311
  };
308
312
  }
313
+ if (isStringifiedPrimitiveMismatch(selection.value, want)) {
314
+ return stringifiedPrimitiveResult(storeName, p.path, selection.value, want, capDepth);
315
+ }
309
316
  return {
310
317
  pass: false,
311
318
  failureReason: `state '${p.path}' is ${JSON.stringify(capDepth(selection.value, 0))}, expected ${JSON.stringify(want)}`,
@@ -23,6 +23,7 @@ export function predicateToExpectedLinks(predicate) {
23
23
  kind: ConsequenceKind.NET,
24
24
  urlContains: predicate.urlContains,
25
25
  ...(predicate.status === undefined ? {} : { status: predicate.status }),
26
+ ...(predicate.method === undefined ? {} : { method: predicate.method }),
26
27
  },
27
28
  ];
28
29
  case PredicateKind.STATE: {
@@ -3,7 +3,7 @@ import { predicateToExpectedLinks } from './predicate-to-links.js';
3
3
  import { isAmbient, ambientKeyOf } from '../../window/ambient.js';
4
4
  import { evalRoute } from './predicate-route.js';
5
5
  import { describeSuperseded } from './observed-in-window.js';
6
- import { evalElement, withTextProperty } from './predicate-element.js';
6
+ import { evalElement, textPredicateQuery, withTextProperty } from './predicate-element.js';
7
7
  import { evalState } from './predicate-state.js';
8
8
  import { evalCompare } from './predicate-compare.js';
9
9
  import { PredicateSchema, evalNet, evalConsole, evalAnimation, evalSignal, evalSettled, } from './predicate-eval.js';
@@ -71,22 +71,37 @@ function annotateThrottledMiss(session, predicate, result) {
71
71
  return result;
72
72
  if (failureRestsOnSeeing(predicate))
73
73
  return result;
74
- if (foundTextSplitAcrossChildren(result))
74
+ if (evidenceProvesPageRendered(result))
75
75
  return result;
76
76
  return { ...result, inconclusive: THROTTLED_STARVED_NOTE };
77
77
  }
78
78
  /**
79
- * Did the miss come with proof that the page rendered the very string it was looking for?
79
+ * Did the miss come with proof that the page rendered?
80
80
  *
81
- * The starved-tab caveat is for a page that may not have painted. A text miss that carries a
82
- * split-text owner is the browser saying the string IS in the rendered page, split across one
83
- * container's children — so the tab ran, and the failure is the locator's. Reported from Next's
84
- * template: the throttle note led a response whose own near-miss named the heading holding the text,
85
- * and the agent was sent to wait out a starvation that had not happened.
81
+ * The starved-tab caveat is for a page that may not have painted. Evidence that the page IS alive
82
+ * means the miss is real, not an artefact of throttling.
83
+ *
84
+ * - `splitText`: the browser found the requested string in the rendered page, split across
85
+ * children. Target-specific — the text IS the thing that was asked for.
86
+ * - `caseMiss`: the browser found it in another case, for a case-exact check.
87
+ * - `nearMiss` from `element.state`: the target element exists but in the wrong state. The DOM
88
+ * painted the element itself, so starvation is not the explanation.
89
+ *
90
+ * Excluded:
91
+ * - `nearMiss` from `element.role+name`: a role-only match on a partially rendered page does not
92
+ * prove the named target rendered. The same role may come from a static shell.
93
+ * - `presentTestids`: testids can come from a static shell or another part of a partially rendered
94
+ * page while the requested target remains starved.
86
95
  */
87
- function foundTextSplitAcrossChildren(result) {
96
+ function evidenceProvesPageRendered(result) {
88
97
  const evidence = result.evidence;
89
- return 'object' === typeof evidence && null !== evidence && 'splitText' in evidence;
98
+ if ('object' !== typeof evidence || null === evidence)
99
+ return false;
100
+ if ('splitText' in evidence || 'caseMiss' in evidence)
101
+ return true;
102
+ if ('nearMiss' in evidence && 'element.state' === result.assertion)
103
+ return true;
104
+ return false;
90
105
  }
91
106
  /**
92
107
  * Has this predicate's failure ALREADY been adjudicated, one level down?
@@ -238,15 +253,8 @@ diagnose = true, baselines) {
238
253
  return evalElement(session, predicate.query, predicate.state, predicate.absent ?? false, diagnose);
239
254
  case PredicateKind.TEXT: {
240
255
  // `scope` passes straight through: the text predicate has always been an element query with
241
- // only `text` filled in, so scoping it needs the field, not a second code path. `contains` is
242
- // optional now that `satisfies` can carry the claim, and an undefined one must not reach the
243
- // query as `text: undefined` — that is a locator asking for the empty string.
244
- const query = {
245
- ...(undefined === predicate.contains ? {} : { text: predicate.contains }),
246
- ...(undefined === predicate.scope
247
- ? {}
248
- : { scope: predicate.scope, ...(true === predicate.self ? { self: true } : {}) }),
249
- };
256
+ // only `text` filled in, so scoping it needs the field, not a second code path.
257
+ const query = textPredicateQuery(predicate);
250
258
  const found = await evalElement(session, query, true === predicate.visible ? ElementState.VISIBLE : undefined, predicate.absent ?? false, diagnose);
251
259
  if (undefined === predicate.satisfies)
252
260
  return found;
@@ -272,7 +280,12 @@ diagnose = true, baselines) {
272
280
  // heuristic, never causation, so a chat message arriving mid-window must not hold settle open.
273
281
  const counts = session.ambientCounts?.();
274
282
  const settleEvents = counts === undefined ? events : events.filter((e) => !isAmbient(counts, ambientKeyOf(e)));
275
- return evalSettled(settleEvents, predicate, session.elapsed());
283
+ // The same two facts the act settle-wait reads, so `settled` and `act_and_wait`'s own wait stop
284
+ // disagreeing about what is in flight — see `SettleScope`.
285
+ return evalSettled(settleEvents, predicate, session.elapsed(), {
286
+ appUrl: session.url,
287
+ background: session.background,
288
+ });
276
289
  }
277
290
  case PredicateKind.COMPARE:
278
291
  return evalCompare(session, events, predicate, diagnose);
@@ -367,6 +380,23 @@ const MIN_RECHECK_GAP_MS = 25;
367
380
  * assertion that latency, so this trades an unbounded false green for a bounded one and says so.
368
381
  */
369
382
  const COUNT_CONFIRM_MS = 300;
383
+ /**
384
+ * The least time an absence claim keeps watching after it first reads true, before the page's
385
+ * settle is consulted.
386
+ *
387
+ * An absence is not a count: the thing it rules out is usually a reaction the action scheduled, such
388
+ * as a `setTimeout(() => console.error(...), 800)` in a click handler. Held for COUNT_CONFIRM_MS, that
389
+ * step passed and the error landed in nobody's window (#1344). So an absence holds for this floor
390
+ * AND until the page has gone quiet by the `settled` oracle's own rule, whichever ends later, and the
391
+ * caller's budget still ends both.
392
+ *
393
+ * It is a ceiling, not a proof: an error scheduled more than a second after an otherwise silent
394
+ * action still passes. Nothing on the page says a timer is pending, so a longer floor is the only
395
+ * way to see further, and every live absence check would pay it.
396
+ */
397
+ const ABSENCE_HOLD_MS = 1_000;
398
+ /** "Has the page gone quiet", asked of the same window the absence is about. */
399
+ const SETTLED_PROBE = { kind: PredicateKind.SETTLED };
370
400
  /**
371
401
  * Does this predicate assert an exact cardinality anywhere inside it?
372
402
  *
@@ -393,7 +423,7 @@ function assertsExactCount(predicate) {
393
423
  * Such a claim is about the END of a window for the same reason an exact count is, and reads true
394
424
  * at the start of every window by construction. Settled on its first reading, a clean-console check
395
425
  * passed on a page whose `console.error` landed a few milliseconds later, which the bench measured
396
- * once the page ran slower. It holds for the same bounded window as a count; see COUNT_CONFIRM_MS.
426
+ * once the page ran slower. It holds until the page goes quiet; see ABSENCE_HOLD_MS.
397
427
  */
398
428
  function claimsAbsence(predicate) {
399
429
  if (PredicateKind.NOT === predicate.kind)
@@ -434,8 +464,9 @@ baselines) {
434
464
  /** One-shot re-check timed to when a time-based predicate could first pass. See retryAfterMs. */
435
465
  let hintTimer;
436
466
  // An exact count or an absence keeps watching after it first reads true — see COUNT_CONFIRM_MS
437
- // and claimsAbsence.
438
- const holdsForCount = assertsExactCount(predicate) || claimsAbsence(predicate);
467
+ // and ABSENCE_HOLD_MS.
468
+ const holdsForAbsence = claimsAbsence(predicate);
469
+ const holdsForCount = assertsExactCount(predicate) || holdsForAbsence;
439
470
  let confirming = false;
440
471
  let confirmTimer;
441
472
  /** Report a wait that could not run, and END it — see guardedCheck. */
@@ -523,13 +554,33 @@ baselines) {
523
554
  if (confirming)
524
555
  return;
525
556
  confirming = true;
526
- confirmTimer = setTimeout(() => {
557
+ const confirm = () => {
527
558
  void evaluatePredicate(reader, predicate, since, true, baselines)
528
559
  .then(finish)
529
560
  .catch((error) => {
530
561
  finish(failed(error));
531
562
  });
532
- }, COUNT_CONFIRM_MS);
563
+ };
564
+ if (!holdsForAbsence) {
565
+ confirmTimer = setTimeout(confirm, COUNT_CONFIRM_MS);
566
+ return;
567
+ }
568
+ // An absence waits out ABSENCE_HOLD_MS, then for the page to go quiet. A settle read that
569
+ // could not answer is not a reason to hold on: the confirming read still decides.
570
+ const holdUntilQuiet = () => {
571
+ void evaluatePredicate(reader, SETTLED_PROBE, since, false)
572
+ .then((settled) => {
573
+ if (done)
574
+ return;
575
+ if (settled.pass) {
576
+ confirm();
577
+ return;
578
+ }
579
+ confirmTimer = setTimeout(holdUntilQuiet, settled.retryAfterMs ?? POLL_INTERVAL_MS);
580
+ })
581
+ .catch(confirm);
582
+ };
583
+ confirmTimer = setTimeout(holdUntilQuiet, ABSENCE_HOLD_MS);
533
584
  })
534
585
  .catch((error) => {
535
586
  finish(failed(error));
@@ -29,4 +29,10 @@ interface SplitTextOwner {
29
29
  * short message it already had. A clause that fires on every failure stops carrying information.
30
30
  */
31
31
  export declare function describeSplitTextMiss(owner: SplitTextOwner | undefined, searchedText?: string): string | undefined;
32
+ /**
33
+ * The clause for a case-exact check that missed only on case: what the page shows, and the one
34
+ * change that matches it. It used to read "split across the children" with the same check as the
35
+ * recovery, which fails again.
36
+ */
37
+ export declare function describeCaseMiss(shown: string | undefined): string | undefined;
32
38
  export {};
@@ -49,3 +49,13 @@ export function describeSplitTextMiss(owner, searchedText) {
49
49
  })}`;
50
50
  return `that text IS on the page, split across the children of ${where} — no single element's own text carries it, so no text query can match it; ${recovery}`;
51
51
  }
52
+ /**
53
+ * The clause for a case-exact check that missed only on case: what the page shows, and the one
54
+ * change that matches it. It used to read "split across the children" with the same check as the
55
+ * recovery, which fails again.
56
+ */
57
+ export function describeCaseMiss(shown) {
58
+ if (shown === undefined || 0 === shown.length)
59
+ return undefined;
60
+ return `the page shows "${truncate(shown)}", which differs only by case — this check is case-exact; retry with ignoreCase: true if the case does not matter`;
61
+ }
@@ -4,7 +4,7 @@ interface ReactionReport {
4
4
  events: ReticleEvent[];
5
5
  summary: ReactionSummary;
6
6
  }
7
- /** Turn a slice of the event buffer into the structured "what the app did" report (plan/05). */
7
+ /** Turn a slice of the event buffer into the structured "what the app did" report. */
8
8
  export declare function buildReactionReport(events: ReticleEvent[], windowMs: number): ReactionReport;
9
9
  /**
10
10
  * Drop the per-event `events` array, keeping the window and counts. The counts already answer "what
@@ -1,5 +1,5 @@
1
1
  import { EventType, } from '@reticlehq/core';
2
- /** Turn a slice of the event buffer into the structured "what the app did" report (plan/05). */
2
+ /** Turn a slice of the event buffer into the structured "what the app did" report. */
3
3
  export function buildReactionReport(events, windowMs) {
4
4
  const summary = {
5
5
  total: events.length,
@@ -0,0 +1,25 @@
1
+ import { type ReticleEvent } from '@reticlehq/core';
2
+ /**
3
+ * Meaningful state vs cache bookkeeping.
4
+ *
5
+ * A query cache (TanStack Query, SWR-shaped stores) re-emits every entry as it moves through
6
+ * pending → fetching → idle, stamping `fetchStatus`, `isStale` and `dataUpdatedAt` on the way. Those
7
+ * transitions are real, and they are not what an action CHANGED: one click on a cache-backed page
8
+ * reported a dozen `stateDiffs` whose only difference was the cache's own clock, and the one diff
9
+ * that mattered was the thirteenth.
10
+ *
11
+ * This rule classifies ONE before→after pair. It is deliberately narrow: a diff is bookkeeping only
12
+ * when both sides are plain objects AND every key that differs is a bookkeeping key. A change to
13
+ * `data`, `error`, or any key this list does not name is meaningful — so a value nobody anticipated
14
+ * is always reported, never silently classed as noise. `status` is included because on its own
15
+ * (no `data`/`error` move) it is the cache narrating its fetch, not the app changing.
16
+ *
17
+ * Predicates never read this: they evaluate the event window directly, so a `state` assertion on
18
+ * `isStale` still sees every transition. One verdict does: `state-vs-render` ignores a change this
19
+ * classes as bookkeeping, so a cache's own clock cannot stand in for an app change nobody rendered.
20
+ */
21
+ export declare const CACHE_BOOKKEEPING_KEYS: ReadonlySet<string>;
22
+ /** TRUE when this before→after differs only in cache-bookkeeping keys, and differs at all. */
23
+ export declare function isCacheBookkeepingDiff(from: unknown, to: unknown): boolean;
24
+ /** Whether a state event carries movement that can support state-vs-render. */
25
+ export declare function isMeaningfulStateChange(event: ReticleEvent): boolean;
@@ -0,0 +1,70 @@
1
+ import { EventType } from '@reticlehq/core';
2
+ /**
3
+ * Meaningful state vs cache bookkeeping.
4
+ *
5
+ * A query cache (TanStack Query, SWR-shaped stores) re-emits every entry as it moves through
6
+ * pending → fetching → idle, stamping `fetchStatus`, `isStale` and `dataUpdatedAt` on the way. Those
7
+ * transitions are real, and they are not what an action CHANGED: one click on a cache-backed page
8
+ * reported a dozen `stateDiffs` whose only difference was the cache's own clock, and the one diff
9
+ * that mattered was the thirteenth.
10
+ *
11
+ * This rule classifies ONE before→after pair. It is deliberately narrow: a diff is bookkeeping only
12
+ * when both sides are plain objects AND every key that differs is a bookkeeping key. A change to
13
+ * `data`, `error`, or any key this list does not name is meaningful — so a value nobody anticipated
14
+ * is always reported, never silently classed as noise. `status` is included because on its own
15
+ * (no `data`/`error` move) it is the cache narrating its fetch, not the app changing.
16
+ *
17
+ * Predicates never read this: they evaluate the event window directly, so a `state` assertion on
18
+ * `isStale` still sees every transition. One verdict does: `state-vs-render` ignores a change this
19
+ * classes as bookkeeping, so a cache's own clock cannot stand in for an app change nobody rendered.
20
+ */
21
+ export const CACHE_BOOKKEEPING_KEYS = new Set([
22
+ 'status',
23
+ 'fetchStatus',
24
+ 'isStale',
25
+ 'dataUpdatedAt',
26
+ 'errorUpdatedAt',
27
+ 'isFetching',
28
+ 'isInvalidated',
29
+ 'fetchFailureCount',
30
+ ]);
31
+ function plainObject(value) {
32
+ return 'object' === typeof value && null !== value && !Array.isArray(value);
33
+ }
34
+ function same(a, b) {
35
+ if (Object.is(a, b))
36
+ return true;
37
+ try {
38
+ return JSON.stringify(a) === JSON.stringify(b);
39
+ }
40
+ catch {
41
+ // Not comparable is not "equal": a pair we cannot read is reported, never classed as noise.
42
+ return false;
43
+ }
44
+ }
45
+ /** TRUE when this before→after differs only in cache-bookkeeping keys, and differs at all. */
46
+ export function isCacheBookkeepingDiff(from, to) {
47
+ if (!plainObject(from) || !plainObject(to))
48
+ return false;
49
+ let differed = false;
50
+ for (const key of new Set([...Object.keys(from), ...Object.keys(to)])) {
51
+ if (same(from[key], to[key]))
52
+ continue;
53
+ if (!CACHE_BOOKKEEPING_KEYS.has(key))
54
+ return false;
55
+ differed = true;
56
+ }
57
+ return differed;
58
+ }
59
+ /** Whether a state event carries movement that can support state-vs-render. */
60
+ export function isMeaningfulStateChange(event) {
61
+ if (event.type !== EventType.STATE_CHANGE)
62
+ return false;
63
+ if (!('old' in event.data))
64
+ return true;
65
+ const hasAfter = 'value' in event.data || 'new' in event.data;
66
+ if (!hasAfter)
67
+ return true;
68
+ const after = 'value' in event.data ? event.data['value'] : event.data['new'];
69
+ return !isCacheBookkeepingDiff(event.data['old'], after);
70
+ }