@reticlehq/engine 3.2.0 → 3.4.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 (45) hide show
  1. package/NOTICE +5 -0
  2. package/dist/disagreement/body-failures.js +32 -12
  3. package/dist/disagreement/contradiction-evidence.d.ts +1 -1
  4. package/dist/disagreement/contradiction-evidence.js +3 -3
  5. package/dist/disagreement/contradiction-types.d.ts +6 -0
  6. package/dist/disagreement/contradictions.js +24 -30
  7. package/dist/disagreement/echo-mismatch.js +16 -0
  8. package/dist/evidence/already-true.js +14 -3
  9. package/dist/evidence/baseline.d.ts +21 -0
  10. package/dist/evidence/baseline.js +129 -0
  11. package/dist/evidence/instrumentation-gaps.js +8 -2
  12. package/dist/evidence/unsettled.js +7 -1
  13. package/dist/evidence/verified.d.ts +7 -0
  14. package/dist/evidence/verified.js +35 -1
  15. package/dist/question/declared.js +11 -2
  16. package/dist/question/lineage.d.ts +14 -5
  17. package/dist/question/lineage.js +65 -10
  18. package/dist/question/predicate/predicate-asks.js +7 -1
  19. package/dist/question/predicate/predicate-compare.d.ts +18 -0
  20. package/dist/question/predicate/predicate-compare.js +226 -0
  21. package/dist/question/predicate/predicate-element.d.ts +5 -2
  22. package/dist/question/predicate/predicate-element.js +122 -8
  23. package/dist/question/predicate/predicate-eval-kit.d.ts +43 -2
  24. package/dist/question/predicate/predicate-eval-kit.js +107 -14
  25. package/dist/question/predicate/predicate-eval.d.ts +6 -0
  26. package/dist/question/predicate/predicate-eval.js +60 -13
  27. package/dist/question/predicate/predicate-parse.js +1 -0
  28. package/dist/question/predicate/predicate-precheck.js +3 -5
  29. package/dist/question/predicate/predicate-request-body.d.ts +1 -1
  30. package/dist/question/predicate/predicate-request-body.js +7 -3
  31. package/dist/question/predicate/predicate-route.d.ts +2 -1
  32. package/dist/question/predicate/predicate-schema.d.ts +14 -93
  33. package/dist/question/predicate/predicate-schema.js +33 -288
  34. package/dist/question/predicate/predicate-session.d.ts +20 -1
  35. package/dist/question/predicate/predicate-session.js +25 -1
  36. package/dist/question/predicate/predicate-state.d.ts +15 -0
  37. package/dist/question/predicate/predicate-state.js +317 -0
  38. package/dist/question/predicate/predicate-to-links.js +3 -1
  39. package/dist/question/predicate/predicate.d.ts +17 -3
  40. package/dist/question/predicate/predicate.js +200 -336
  41. package/dist/question/predicate/property.d.ts +24 -73
  42. package/dist/question/predicate/property.js +134 -20
  43. package/dist/window/json-salvage.d.ts +2 -1
  44. package/dist/window/json-salvage.js +2 -1
  45. package/package.json +5 -6
@@ -1,12 +1,14 @@
1
- import { ElementState, PredicateKind, ReticleCommand, THROTTLED_STARVED_NOTE, capDepth, isSameDocument, selectPath, } from '@reticlehq/core';
2
- import { satisfiesProperty } from './property.js';
1
+ import { ElementState, PredicateKind, THROTTLED_STARVED_NOTE, isSameDocument, } from '@reticlehq/core';
3
2
  import { predicateToExpectedLinks } from './predicate-to-links.js';
4
3
  import { isAmbient, ambientKeyOf } from '../../window/ambient.js';
5
4
  import { evalRoute } from './predicate-route.js';
6
5
  import { describeSuperseded } from './observed-in-window.js';
7
- import { evalElement } from './predicate-element.js';
8
- import { PredicateSchema, matchValue, evalNet, evalConsole, evalAnimation, evalSignal, evalSettled, } from './predicate-eval.js';
6
+ import { evalElement, withTextProperty } from './predicate-element.js';
7
+ import { evalState } from './predicate-state.js';
8
+ import { evalCompare } from './predicate-compare.js';
9
+ import { PredicateSchema, evalNet, evalConsole, evalAnimation, evalSignal, evalSettled, } from './predicate-eval.js';
9
10
  export { PredicateSchema, PredicateKind };
11
+ import { withinBudget } from './predicate-session.js';
10
12
  /**
11
13
  * A composite result that carries a child's "nobody could evaluate this" up to the verdict rule.
12
14
  *
@@ -19,301 +21,6 @@ function unreadableComposite(child, evidence) {
19
21
  const reason = child.inconclusive ?? 'a sub-predicate could not be evaluated';
20
22
  return { pass: false, failureReason: reason, inconclusive: reason, evidence };
21
23
  }
22
- function oneOf(names) {
23
- return 1 === names.length ? names[0] : undefined;
24
- }
25
- /**
26
- * `readState`'s truncation report, when the caps actually fired.
27
- *
28
- * Its PRESENCE is the warning — the field is omitted entirely on an intact read, which is what lets
29
- * "the list is short" stay distinguishable from "I shortened the list".
30
- */
31
- function truncationOf(result) {
32
- if ('object' !== typeof result || null === result)
33
- return undefined;
34
- const report = result.truncation;
35
- return 'object' === typeof report && null !== report
36
- ? report
37
- : undefined;
38
- }
39
- /** A scoped `readState` reply, narrowed to the shape `selectPath` would have produced. */
40
- function asSelection(result) {
41
- if ('object' !== typeof result || null === result)
42
- return undefined;
43
- const record = result;
44
- return 'boolean' === typeof record.found
45
- ? { found: record.found, value: record.value }
46
- : undefined;
47
- }
48
- /**
49
- * A NAMED store needs no whole-store read. `reticle_state`'s scoped mode selects the path out of the
50
- * RAW store IN-PAGE and returns only it, so the assertion resolves in one round trip against a payload
51
- * the size of the value — not the store. The unnamed case below still needs the wide read, because
52
- * that is how it discovers WHICH store carries the path; only the named branch changes.
53
- *
54
- * A scoped read answers `found: false` for both "no such store" and "no such path", so the two are
55
- * kept distinct here using the `storeNames` list the reply always carries — otherwise the payload gets
56
- * cheaper while the message gets worse.
57
- */
58
- async function evalStateNamed(session, p, storeName) {
59
- const scoped = await session.command(ReticleCommand.STATE_READ, {
60
- store: storeName,
61
- path: p.path,
62
- });
63
- if (!scoped.ok) {
64
- return {
65
- pass: false,
66
- failureReason: 'state read failed',
67
- observed: 'the store could not be read',
68
- expected: 'a readable registered store',
69
- assertion: 'state.unreadable',
70
- };
71
- }
72
- const reply = (scoped.result ?? {});
73
- const names = Array.isArray(reply.storeNames) ? reply.storeNames : [];
74
- // Resolve the value. A CURRENT SDK honours the scoped read and answers `{ found, value }` selected
75
- // in-page — the whole point of this path. An OLDER SDK (version skew) or any transport that ignores
76
- // `path` answers the whole-store shape `{ stores }`; walk the path server-side there so the verdict
77
- // stays correct across SDK versions. The scoped win is simply unavailable on the old ones.
78
- const scopedSel = asSelection(scoped.result);
79
- const wholeStores = reply.stores;
80
- const scopedKeys = Array.isArray(reply.availableKeys)
81
- ? reply.availableKeys
82
- : undefined;
83
- let selection;
84
- if (scopedSel !== undefined) {
85
- selection =
86
- scopedKeys === undefined
87
- ? { found: scopedSel.found, value: scopedSel.value }
88
- : { found: scopedSel.found, value: scopedSel.value, availableKeys: scopedKeys };
89
- }
90
- else if (wholeStores !== undefined) {
91
- selection = selectPath(wholeStores[storeName], p.path);
92
- }
93
- else {
94
- selection = { found: false };
95
- }
96
- // "no store named X" and "X has no such path" both surface as found:false; keep them distinct using
97
- // the store list the reply carries, or the message regresses while the payload improves.
98
- const storeAbsent = wholeStores !== undefined
99
- ? !(storeName in wholeStores)
100
- : names.length > 0 && !names.includes(storeName);
101
- if (!selection.found && storeAbsent) {
102
- return {
103
- pass: false,
104
- failureReason: `no store named '${storeName}' is registered (${names.join(', ')})`,
105
- observed: `store '${storeName}' is not registered`,
106
- expected: `a registered store named '${storeName}'`,
107
- assertion: 'state.store-missing',
108
- evidence: { searchedStores: names },
109
- };
110
- }
111
- // A scoped sub-tree can itself be too big for the caps; a comparison against a value known to be
112
- // incomplete is an unanswered question, not a failure. Same rule the whole-store path applies.
113
- if (truncationOf(scoped.result) !== undefined) {
114
- const reason = `state '${p.path}' could not be read intact — the transport caps truncated it, so the ` +
115
- 'value was never compared. Assert a narrower path, or a smaller field inside it';
116
- return { pass: false, failureReason: reason, inconclusive: reason };
117
- }
118
- if (!selection.found) {
119
- return {
120
- pass: false,
121
- failureReason: `state path '${p.path}' not found in store '${storeName}'`,
122
- observed: `no path '${p.path}' in store '${storeName}'`,
123
- expected: `store '${storeName}' to expose '${p.path}'`,
124
- assertion: 'state.path-missing',
125
- evidence: { availableKeys: selection.availableKeys },
126
- };
127
- }
128
- /*
129
- * A PROPERTY assertion runs before equality and can stand alone.
130
- *
131
- * `satisfies` is what makes a generated value verifiable at all: its exact bytes differ every run
132
- * and are right every time, so `equals` can only ever be wrong about it. Both may be supplied and
133
- * then both must hold — `satisfies` narrows, it never excuses.
134
- */
135
- if (p.satisfies !== undefined) {
136
- const r = satisfiesProperty(selection.value, p.satisfies);
137
- if (!r.ok) {
138
- return {
139
- pass: false,
140
- failureReason: `state '${p.path}' ${r.because}`,
141
- observed: `${p.path} = ${JSON.stringify(capDepth(selection.value, 0))}`,
142
- expected: `${p.path} to satisfy ${p.satisfies.property}`,
143
- assertion: `state.${p.satisfies.property}`,
144
- evidence: { store: storeName, path: p.path, value: capDepth(selection.value, 1) },
145
- };
146
- }
147
- if (p.equals === undefined) {
148
- return {
149
- pass: true,
150
- evidence: {
151
- store: storeName,
152
- path: p.path,
153
- value: capDepth(selection.value, 1),
154
- satisfied: r.because,
155
- },
156
- };
157
- }
158
- }
159
- const want = p.equals === undefined ? '*' : p.equals;
160
- if (matchValue(selection.value, want)) {
161
- return {
162
- pass: true,
163
- evidence: { store: storeName, path: p.path, value: capDepth(selection.value, 1) },
164
- };
165
- }
166
- return {
167
- pass: false,
168
- failureReason: `state '${p.path}' is ${JSON.stringify(capDepth(selection.value, 0))}, expected ${JSON.stringify(want)}`,
169
- observed: `${p.path} = ${JSON.stringify(capDepth(selection.value, 0))}`,
170
- expected: `${p.path} = ${JSON.stringify(want)}`,
171
- assertion: 'state.equals',
172
- evidence: { store: storeName, path: p.path, value: capDepth(selection.value, 1) },
173
- };
174
- }
175
- async function evalState(session, p) {
176
- // Named store: one scoped read, no whole-store payload (issue #336).
177
- if (p.store !== undefined)
178
- return await evalStateNamed(session, p, p.store);
179
- const res = await session.command(ReticleCommand.STATE_READ, {});
180
- if (!res.ok) {
181
- return {
182
- pass: false,
183
- failureReason: 'state read failed',
184
- observed: 'the store could not be read',
185
- expected: 'a readable registered store',
186
- assertion: 'state.unreadable',
187
- };
188
- }
189
- const stores = (res.result ?? {}).stores ?? {};
190
- const names = Object.keys(stores);
191
- // Ambiguity is about the PATH, not the store count.
192
- //
193
- // Registering more than one store is normal — an app store, a query cache, and the render meter
194
- // Reticle registers itself — and asking "which of these three?" when only one of them HAS the
195
- // path is a question with one possible answer. It was costing a real verdict: a bench-app drive
196
- // asserting `{path:'view'}` returned `unknown` while the same response body carried the matching
197
- // `view` state diff. `unknown` is not a pass, so that is a verification that did not happen.
198
- //
199
- // So narrow to the stores that actually carry the path, and refuse only when THOSE collide.
200
- const candidates = p.store === undefined ? names.filter((n) => selectPath(stores[n], p.path).found) : [];
201
- const storeName = p.store ?? (1 === names.length ? names[0] : oneOf(candidates));
202
- if (storeName === undefined) {
203
- // With no store registered there is nothing to read, and with two stores that both carry the
204
- // path there is no way to pick — neither is a finding about the app, no assertion was evaluated,
205
- // so both are inconclusive rather than failed: an unevaluated predicate is never a failure.
206
- //
207
- // Zero candidates is the one case that is NOT a question: every registered store was searched
208
- // and none exposes the path, so the assertion cannot hold anywhere. That is the same verdict a
209
- // named store has always produced for a missing path, and it falls through to it below.
210
- if (0 === names.length) {
211
- const reason = 'no registered store to read state from';
212
- return { pass: false, failureReason: reason, inconclusive: reason };
213
- }
214
- if (candidates.length > 1) {
215
- // Names the stores that actually collide. Listing all of them made the reader weigh
216
- // candidates that could never have matched.
217
- const reason = `multiple stores (${candidates.join(', ')}) expose '${p.path}'; name one with \`store\``;
218
- return { pass: false, failureReason: reason, inconclusive: reason };
219
- }
220
- return {
221
- pass: false,
222
- failureReason: `state path '${p.path}' not found in any registered store (${names.join(', ')})`,
223
- observed: `no path '${p.path}' in ${names.join(', ')}`,
224
- expected: `some registered store to expose '${p.path}'`,
225
- assertion: 'state.path-missing',
226
- evidence: { searchedStores: names },
227
- };
228
- }
229
- let selection = selectPath(stores[storeName], p.path);
230
- // The whole-store read walks into a value the transport caps may already have mangled.
231
- //
232
- // `readState` has a SCOPED mode that selects the path out of the RAW store before sanitising, added
233
- // precisely so a large or deep path still resolves. This path was not using it, so a store with one
234
- // big collection in it truncated the small value sitting beside it, and the comparison then ran
235
- // against the literal string "[TRUNCATED]" and returned a confident `no`. Measured on the Atlas
236
- // fixture: a one-element array reported as a failed assertion while the same payload's state diffs
237
- // showed the assertion holding.
238
- //
239
- // Re-read only when a cap actually fired, so an intact read costs exactly what it did before.
240
- if (truncationOf(res.result) !== undefined) {
241
- const scoped = await session.command(ReticleCommand.STATE_READ, {
242
- store: storeName,
243
- path: p.path,
244
- });
245
- const result = scoped.ok ? scoped.result : undefined;
246
- const scopedTruncation = truncationOf(result);
247
- if (scopedTruncation !== undefined) {
248
- // Even the raw sub-tree was too big. Nothing here knows what the value IS, so nothing here can
249
- // say the assertion failed — that would be an accusation the evidence does not support.
250
- const reason = `state '${p.path}' could not be read intact — the transport caps truncated it, so the ` +
251
- 'value was never compared. Assert a narrower path, or a smaller field inside it';
252
- return { pass: false, failureReason: reason, inconclusive: reason };
253
- }
254
- if (result !== undefined) {
255
- const scopedSelection = asSelection(result);
256
- if (scopedSelection !== undefined)
257
- selection = scopedSelection;
258
- }
259
- }
260
- if (!selection.found) {
261
- return {
262
- pass: false,
263
- failureReason: `state path '${p.path}' not found in store '${storeName}'`,
264
- observed: `no path '${p.path}' in store '${storeName}'`,
265
- expected: `store '${storeName}' to expose '${p.path}'`,
266
- assertion: 'state.path-missing',
267
- evidence: { availableKeys: selection.availableKeys },
268
- };
269
- }
270
- /*
271
- * A PROPERTY assertion runs before equality and can stand alone.
272
- *
273
- * `satisfies` is what makes a generated value verifiable at all: its exact bytes differ every run
274
- * and are right every time, so `equals` can only ever be wrong about it. Both may be supplied and
275
- * then both must hold — `satisfies` narrows, it never excuses.
276
- */
277
- if (p.satisfies !== undefined) {
278
- const r = satisfiesProperty(selection.value, p.satisfies);
279
- if (!r.ok) {
280
- return {
281
- pass: false,
282
- failureReason: `state '${p.path}' ${r.because}`,
283
- observed: `${p.path} = ${JSON.stringify(capDepth(selection.value, 0))}`,
284
- expected: `${p.path} to satisfy ${p.satisfies.property}`,
285
- assertion: `state.${p.satisfies.property}`,
286
- evidence: { store: storeName, path: p.path, value: capDepth(selection.value, 1) },
287
- };
288
- }
289
- if (p.equals === undefined) {
290
- return {
291
- pass: true,
292
- evidence: {
293
- store: storeName,
294
- path: p.path,
295
- value: capDepth(selection.value, 1),
296
- satisfied: r.because,
297
- },
298
- };
299
- }
300
- }
301
- const want = p.equals === undefined ? '*' : p.equals;
302
- if (matchValue(selection.value, want)) {
303
- return {
304
- pass: true,
305
- evidence: { store: storeName, path: p.path, value: capDepth(selection.value, 1) },
306
- };
307
- }
308
- return {
309
- pass: false,
310
- failureReason: `state '${p.path}' is ${JSON.stringify(capDepth(selection.value, 0))}, expected ${JSON.stringify(want)}`,
311
- observed: `${p.path} = ${JSON.stringify(capDepth(selection.value, 0))}`,
312
- expected: `${p.path} = ${JSON.stringify(want)}`,
313
- assertion: 'state.equals',
314
- evidence: { store: storeName, path: p.path, value: capDepth(selection.value, 1) },
315
- };
316
- }
317
24
  /**
318
25
  * Oracles whose ONLY source of truth is the event window.
319
26
  *
@@ -360,10 +67,97 @@ function annotateThrottledMiss(session, predicate, result) {
360
67
  }
361
68
  if (true !== session.throttled?.())
362
69
  return result;
70
+ if (decidedByAnAlreadyAnnotatedClause(predicate))
71
+ return result;
363
72
  if (failureRestsOnSeeing(predicate))
364
73
  return result;
74
+ if (foundTextSplitAcrossChildren(result))
75
+ return result;
365
76
  return { ...result, inconclusive: THROTTLED_STARVED_NOTE };
366
77
  }
78
+ /**
79
+ * Did the miss come with proof that the page rendered the very string it was looking for?
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.
86
+ */
87
+ function foundTextSplitAcrossChildren(result) {
88
+ const evidence = result.evidence;
89
+ return 'object' === typeof evidence && null !== evidence && 'splitText' in evidence;
90
+ }
91
+ /**
92
+ * Has this predicate's failure ALREADY been adjudicated, one level down?
93
+ *
94
+ * `allOf`/`anyOf` evaluate their clauses through `evaluatePredicate`, so every clause arrives here
95
+ * first and carries its own verdict on the starved-tab question. Asking again at the composite
96
+ * re-decides it with strictly less information: the composite knows only that SOMETHING failed.
97
+ *
98
+ * A readable `allOf` failure is a clause that failed by having SEEN something, because a clause that
99
+ * failed by NOT seeing is stamped starved before the composite looks (or cleared by
100
+ * `clearStarvedWhenSiblingsSaw` when a sibling proved the tab renders). An `anyOf` reports "no
101
+ * sub-predicate matched" only when every clause failed readably. Without this, an `absent: true`
102
+ * clause that matched 13 elements was graded honestly as a clause and then re-graded `unknown` as an
103
+ * `allOf` of one (#897).
104
+ *
105
+ * `not` is deliberately absent: it fails when its child PASSED, and a passing child is never
106
+ * annotated, so there is nothing decided to defer to. `failureRestsOnSeeing` answers it by flipping.
107
+ */
108
+ function decidedByAnAlreadyAnnotatedClause(predicate) {
109
+ return PredicateKind.ALL_OF === predicate.kind || PredicateKind.ANY_OF === predicate.kind;
110
+ }
111
+ /**
112
+ * Did this arm PROVE the tab rendered?
113
+ *
114
+ * An element predicate that passed did so by finding matches, and nothing about a starved tab
115
+ * conjures elements that were not there. `absent: true` is the exception and the reason this is not
116
+ * simply `result.pass`: that one passes by finding NOTHING, which is precisely the reading a starved
117
+ * tab makes untrustworthy, so it proves the opposite of a render.
118
+ *
119
+ * Composites recurse: a passing `allOf` proves a render if any of its own arms did.
120
+ */
121
+ function provesRender(predicate, result) {
122
+ if (!result.pass)
123
+ return false;
124
+ if (PredicateKind.ELEMENT === predicate.kind)
125
+ return true !== predicate.absent;
126
+ if (PredicateKind.ALL_OF === predicate.kind || PredicateKind.ANY_OF === predicate.kind) {
127
+ return predicate.predicates.some((p) => provesRender(p, result));
128
+ }
129
+ return false;
130
+ }
131
+ /**
132
+ * Drop the starved-tab caveat from arms whose SIBLINGS demonstrated that the tab renders.
133
+ *
134
+ * Reported as the most frequent condition in the whole field export (#1004), in its sharpest form:
135
+ * "A negative arm inside `allOf` was graded 'unknown / this tab is throttled and has not rendered'
136
+ * in the SAME evaluation where three sibling arms returned rendered, visible, inViewport elements."
137
+ * A verdict that contradicts its own evidence is worse than either answer on its own.
138
+ *
139
+ * The caveat exists because a negative reading on a starved tab may mean "I could not look". A
140
+ * sibling that found an element is direct proof that looking worked, in this evaluation, on this
141
+ * tab. Keeping the caveat anyway turns a real product failure into `unknown` — which an agent
142
+ * re-drives or walks away from, so the defect it was holding proof of never reaches anybody.
143
+ *
144
+ * Only the throttle note is cleared. An arm that was unreadable for its own reason — an unparseable
145
+ * locator, a superseded window — is still unreadable however well its siblings did.
146
+ */
147
+ function clearStarvedWhenSiblingsSaw(predicates, results) {
148
+ const rendered = results.some((r, i) => {
149
+ const p = predicates[i];
150
+ return p !== undefined && provesRender(p, r);
151
+ });
152
+ if (!rendered)
153
+ return results;
154
+ return results.map((r) => {
155
+ if (THROTTLED_STARVED_NOTE !== r.inconclusive)
156
+ return r;
157
+ const { inconclusive: _dropped, ...rest } = r;
158
+ return rest;
159
+ });
160
+ }
367
161
  /**
368
162
  * Does this predicate FAIL by having seen something, rather than by not having seen it?
369
163
  *
@@ -377,27 +171,42 @@ function annotateThrottledMiss(session, predicate, result) {
377
171
  * agent re-drives or walks away from — so the proof it was holding never reached anybody.
378
172
  *
379
173
  * `not` flips the polarity again, and nests, so this recurses rather than checking one level.
380
- * Composites (`allOf` / `anyOf`) deliberately fall through to `false`: a composite fails for a
381
- * reason this cannot name, and keeping the caveat is the conservative half of the trade — an
382
- * over-cautious `unknown` costs a re-drive, a missing one costs a wrong verdict.
174
+ *
175
+ * A composite reaches here only under a `not` (a bare one is answered by
176
+ * `decidedByAnAlreadyAnnotatedClause`). There the question is whether it could have PASSED by not
177
+ * seeing something, and `some` is the conservative answer: one clause that passes by absence makes
178
+ * the whole pass untrustworthy on a starved tab. An over-cautious `unknown` costs a re-drive, a
179
+ * missing one costs a wrong verdict.
383
180
  */
384
181
  function failureRestsOnSeeing(predicate) {
385
182
  if (PredicateKind.NOT === predicate.kind)
386
183
  return !failureRestsOnSeeing(predicate.predicate);
184
+ if (PredicateKind.ALL_OF === predicate.kind || PredicateKind.ANY_OF === predicate.kind) {
185
+ return predicate.predicates.some(failureRestsOnSeeing);
186
+ }
387
187
  if ('absent' in predicate && true === predicate.absent)
388
188
  return true;
389
189
  // `count: 0` is absence written as arithmetic, and fails the same way: by matching something.
390
190
  return 'count' in predicate && 0 === predicate.count;
391
191
  }
392
- export async function evaluatePredicate(session, predicate, since = 0, diagnose = true) {
393
- return annotateThrottledMiss(session, predicate, await evaluatePredicateRaw(session, predicate, since, diagnose));
192
+ export async function evaluatePredicate(session, predicate, since = 0, diagnose = true,
193
+ /**
194
+ * The readings taken BEFORE the action, keyed by the leaf that asked for one.
195
+ *
196
+ * Only the relative properties (`changed`/`unchanged`/`increased`/`decreased`) look at it, and a
197
+ * leaf with none evaluates as `inconclusive` rather than false — nothing was compared, so a
198
+ * `false` would blame the app for a reading nobody took. Keyed by the predicate OBJECT because
199
+ * the same parsed tree is evaluated before and after, so identity is exact and needs no path.
200
+ */
201
+ baselines) {
202
+ return annotateThrottledMiss(session, predicate, await evaluatePredicateRaw(session, predicate, since, diagnose, baselines));
394
203
  }
395
204
  async function evaluatePredicateRaw(session, predicate, since = 0,
396
205
  // Compute the (extra-round-trip) near-miss diagnostics on element failures. Default true so a
397
206
  // one-shot assert is fully diagnostic; the wait loop passes false on its interim polls (which read
398
207
  // only `pass`) and true on the final timeout eval, so a flood no longer pays for a diagnostic nobody
399
208
  // reads. Only element/text failures have a near-miss; everything else ignores this.
400
- diagnose = true) {
209
+ diagnose = true, baselines) {
401
210
  // A predicate's own `since` is a TIGHTER event-time floor than the caller's — an agent that took
402
211
  // `since` from the act it just performed is scoping the assertion to that action's aftermath. It is
403
212
  // applied here, once, rather than in each eval: the floor means the same thing for every kind that
@@ -427,17 +236,22 @@ diagnose = true) {
427
236
  switch (predicate.kind) {
428
237
  case PredicateKind.ELEMENT:
429
238
  return evalElement(session, predicate.query, predicate.state, predicate.absent ?? false, diagnose);
430
- case PredicateKind.TEXT:
431
- return evalElement(session,
432
- // `scope` passes straight through: the text predicate has always been an element query
433
- // with only `text` filled in, so scoping it needs the field, not a second code path.
434
- undefined === predicate.scope
435
- ? { text: predicate.contains }
436
- : {
437
- text: predicate.contains,
438
- scope: predicate.scope,
439
- ...(true === predicate.self ? { self: true } : {}),
440
- }, true === predicate.visible ? ElementState.VISIBLE : undefined, predicate.absent ?? false, diagnose);
239
+ case PredicateKind.TEXT: {
240
+ // `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
+ };
250
+ const found = await evalElement(session, query, true === predicate.visible ? ElementState.VISIBLE : undefined, predicate.absent ?? false, diagnose);
251
+ if (undefined === predicate.satisfies)
252
+ return found;
253
+ return withTextProperty(found, predicate.satisfies, JSON.stringify(query), baselines?.get(predicate));
254
+ }
441
255
  case PredicateKind.NET:
442
256
  return evalNet(events, predicate);
443
257
  case PredicateKind.ROUTE:
@@ -451,7 +265,7 @@ diagnose = true) {
451
265
  case PredicateKind.SIGNAL:
452
266
  return evalSignal(events, predicate);
453
267
  case PredicateKind.STATE:
454
- return evalState(session, predicate);
268
+ return evalState(session, predicate, baselines?.get(predicate));
455
269
  case PredicateKind.SETTLED: {
456
270
  // Drop events on learned-ambient regions (chat/ticker churn) before the settle check — by ref
457
271
  // alone, NOT by attribution: window-attribution ("happened during the action window") is a time
@@ -460,21 +274,24 @@ diagnose = true) {
460
274
  const settleEvents = counts === undefined ? events : events.filter((e) => !isAmbient(counts, ambientKeyOf(e)));
461
275
  return evalSettled(settleEvents, predicate, session.elapsed());
462
276
  }
277
+ case PredicateKind.COMPARE:
278
+ return evalCompare(session, events, predicate, diagnose);
463
279
  case PredicateKind.ALL_OF: {
464
- const results = await Promise.all(predicate.predicates.map((p) => evaluatePredicate(session, p, since, diagnose)));
280
+ const results = clearStarvedWhenSiblingsSaw(predicate.predicates, await Promise.all(predicate.predicates.map((p) => evaluatePredicate(session, p, since, diagnose, baselines))));
465
281
  // A clause that genuinely failed OUTRANKS one nobody could read. Softening a real failure to
466
282
  // UNKNOWN would hide the defect the agent came for, which is the more expensive of the two
467
283
  // mistakes; the reverse — grading an unreadable clause as a defect in the app — is the one
468
284
  // that was happening.
469
285
  const failed = results.find((r) => !r.pass && r.inconclusive === undefined);
470
286
  if (failed !== undefined) {
287
+ // A conjunction is decided as soon as ANY clause is permanently false: nothing the
288
+ // others do later can rescue it. Scan all failed clauses, not just the first —
289
+ // `.find()` picks by array order, and the decided clause is not always first.
290
+ const anyDecided = results.some((r) => !r.pass && r.inconclusive === undefined && true === r.decided);
471
291
  return {
472
292
  pass: false,
473
293
  failureReason: failed.failureReason ?? 'a sub-predicate of allOf failed',
474
- // A conjunction is decided as soon as ONE clause is: nothing the others do later can
475
- // rescue it. This is what makes the early exit reach real calls, since an exact count is
476
- // usually asserted alongside the UI change it is meant to accompany.
477
- ...(true === failed.decided ? { decided: true } : {}),
294
+ ...(anyDecided ? { decided: true } : {}),
478
295
  evidence: results,
479
296
  };
480
297
  }
@@ -484,7 +301,7 @@ diagnose = true) {
484
301
  return { pass: true, evidence: results.map((r) => r.evidence) };
485
302
  }
486
303
  case PredicateKind.ANY_OF: {
487
- const results = await Promise.all(predicate.predicates.map((p) => evaluatePredicate(session, p, since, diagnose)));
304
+ const results = clearStarvedWhenSiblingsSaw(predicate.predicates, await Promise.all(predicate.predicates.map((p) => evaluatePredicate(session, p, since, diagnose, baselines))));
488
305
  const passed = results.find((r) => r.pass);
489
306
  if (passed !== undefined)
490
307
  return { pass: true, evidence: passed.evidence };
@@ -493,10 +310,19 @@ diagnose = true) {
493
310
  const unreadable = results.find((r) => r.inconclusive !== undefined);
494
311
  if (unreadable !== undefined)
495
312
  return unreadableComposite(unreadable, results);
496
- return { pass: false, failureReason: 'no sub-predicate of anyOf matched', evidence: results };
313
+ // A disjunction is decided when EVERY clause is permanently false: no branch can
314
+ // ever become true, so waiting out the budget buys nothing. By this point every
315
+ // result is a non-inconclusive failure (passing and inconclusive returned above).
316
+ const allDecided = results.every((r) => true === r.decided);
317
+ return {
318
+ pass: false,
319
+ failureReason: 'no sub-predicate of anyOf matched',
320
+ ...(allDecided ? { decided: true } : {}),
321
+ evidence: results,
322
+ };
497
323
  }
498
324
  case PredicateKind.NOT: {
499
- const inner = await evaluatePredicate(session, predicate.predicate, since, diagnose);
325
+ const inner = await evaluatePredicate(session, predicate.predicate, since, diagnose, baselines);
500
326
  // The sharpest case of the three, and the only one that produced a GREEN. `not` read the
501
327
  // child's `pass: false` as "the inner predicate did not hold" and passed — so an assertion
502
328
  // nobody could evaluate became a verdict of verified, manufactured out of a missing reading.
@@ -523,7 +349,8 @@ const POLL_INTERVAL_MS = 150;
523
349
  * poll cadence, large enough to collapse a per-frame event storm into a bounded recheck rate. */
524
350
  const MIN_RECHECK_GAP_MS = 25;
525
351
  /**
526
- * How long an exact-count predicate keeps watching AFTER it first reads true.
352
+ * How long an exact-count predicate, or one claiming something is absent, keeps watching AFTER it
353
+ * first reads true.
527
354
  *
528
355
  * A count only rises while a window is open, so "exactly N" is a statement about the END of one and
529
356
  * cannot be settled early — yet every wait here resolves the moment a check passes. Live, on a real
@@ -560,22 +387,52 @@ function assertsExactCount(predicate) {
560
387
  return ((PredicateKind.NET === predicate.kind || PredicateKind.SIGNAL === predicate.kind) &&
561
388
  predicate.count !== undefined);
562
389
  }
390
+ /**
391
+ * Does this predicate claim that something did NOT happen: an `absent` check, or a `not`?
392
+ *
393
+ * Such a claim is about the END of a window for the same reason an exact count is, and reads true
394
+ * at the start of every window by construction. Settled on its first reading, a clean-console check
395
+ * 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.
397
+ */
398
+ function claimsAbsence(predicate) {
399
+ if (PredicateKind.NOT === predicate.kind)
400
+ return true;
401
+ if (PredicateKind.ALL_OF === predicate.kind || PredicateKind.ANY_OF === predicate.kind) {
402
+ return predicate.predicates.some(claimsAbsence);
403
+ }
404
+ return 'absent' in predicate && true === predicate.absent;
405
+ }
563
406
  /**
564
407
  * Evaluate now, else wait for it to become true (on each event + a poll) until timeout. `since` is
565
408
  * the event-time floor (see evaluatePredicate) so a waiter cannot resolve on a stale buffered event.
566
409
  */
567
- export function waitForPredicate(session, predicate, timeoutMs, since = 0) {
410
+ export function waitForPredicate(session, predicate, timeoutMs, since = 0,
411
+ /** Pre-action readings, for the relative properties. See `evaluatePredicate`. */
412
+ baselines) {
413
+ // Every read in this wait shares the caller's budget; see withinBudget.
414
+ const deadline = session.elapsed() + timeoutMs;
415
+ const reader = withinBudget(session, () => deadline - session.elapsed());
568
416
  return new Promise((resolve) => {
569
417
  let done = false;
570
- const failed = (error) => ({
571
- pass: false,
572
- failureReason: error instanceof Error ? error.message : String(error),
573
- });
418
+ // A read that threw never looked at the app: the page did not answer, or went away. That is
419
+ // "could not tell", not "looked and it was false", so it is inconclusive, which the verdict rule
420
+ // turns into unknown. As a plain false it was graded assertion_failed: a command timeout on a
421
+ // live, throttled tab came back verified:no against a page that was never read.
422
+ const failed = (error) => {
423
+ const reason = error instanceof Error ? error.message : String(error);
424
+ return {
425
+ pass: false,
426
+ failureReason: reason,
427
+ inconclusive: `the page did not answer: ${reason}`,
428
+ };
429
+ };
574
430
  let cooldownTimer;
575
431
  /** One-shot re-check timed to when a time-based predicate could first pass. See retryAfterMs. */
576
432
  let hintTimer;
577
- // An exact-count wait keeps watching after it first reads true — see COUNT_CONFIRM_MS.
578
- const holdsForCount = assertsExactCount(predicate);
433
+ // An exact count or an absence keeps watching after it first reads true — see COUNT_CONFIRM_MS
434
+ // and claimsAbsence.
435
+ const holdsForCount = assertsExactCount(predicate) || claimsAbsence(predicate);
579
436
  let confirming = false;
580
437
  let confirmTimer;
581
438
  /** Report a wait that could not run, and END it — see guardedCheck. */
@@ -629,7 +486,7 @@ export function waitForPredicate(session, predicate, timeoutMs, since = 0) {
629
486
  inFlight = true;
630
487
  // Interim poll: read only `pass`, so skip the extra near-miss round-trips (diagnose=false). The
631
488
  // final timeout eval below runs with full diagnostics.
632
- void evaluatePredicate(session, predicate, since, false)
489
+ void evaluatePredicate(reader, predicate, since, false, baselines)
633
490
  .then((r) => {
634
491
  if (!r.pass) {
635
492
  // Final already: stop rather than spend a budget that cannot change the answer. Only
@@ -663,7 +520,7 @@ export function waitForPredicate(session, predicate, timeoutMs, since = 0) {
663
520
  return;
664
521
  confirming = true;
665
522
  confirmTimer = setTimeout(() => {
666
- void evaluatePredicate(session, predicate, since)
523
+ void evaluatePredicate(reader, predicate, since, true, baselines)
667
524
  .then(finish)
668
525
  .catch((error) => {
669
526
  finish(failed(error));
@@ -738,8 +595,15 @@ export function waitForPredicate(session, predicate, timeoutMs, since = 0) {
738
595
  });
739
596
  const interval = setInterval(boundCheck, POLL_INTERVAL_MS);
740
597
  const timer = setTimeout(() => {
741
- void evaluatePredicate(session, predicate, since)
598
+ void evaluatePredicate(reader, predicate, since, true, baselines)
742
599
  .then((r) => {
600
+ // A count or an absence that already read true and was holding to confirm: the caller's
601
+ // budget IS the end of its window, so this reading is the answer, whichever way it went.
602
+ // Forcing it to a fail would turn every honest absence under a short budget into a red.
603
+ if (confirming) {
604
+ finish(r);
605
+ return;
606
+ }
743
607
  // Spread the near-miss, do NOT hand-copy two fields. The oracle computes observed / expected
744
608
  // / assertion — the structured cause the repair literature ranks above prose — and the old
745
609
  // `{ pass, evidence, failureReason }` construction DISCARDED them on every timed-out wait and